scip-query 0.10.7 → 0.10.10

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 (236) hide show
  1. package/README.md +4 -2
  2. package/dist/{chunk-OFO7BIRK.js → chunk-2UYQLFVC.js} +2 -2
  3. package/dist/chunk-2VM46FC5.js +8 -0
  4. package/dist/{chunk-WVRTGVHJ.js → chunk-3DGD6NKW.js} +2 -2
  5. package/dist/chunk-3Q77KKEY.js +2 -0
  6. package/dist/chunk-3VD3JMK2.js +2 -0
  7. package/dist/{chunk-U73YFD3P.js → chunk-4KTOV4QN.js} +2 -2
  8. package/dist/chunk-4N4WONI4.js +102 -0
  9. package/dist/{chunk-GOWLZ4NA.js → chunk-56P7PDST.js} +2 -2
  10. package/dist/{chunk-UBDFQBSE.js → chunk-5NVUWIAN.js} +2 -2
  11. package/dist/{chunk-S7DNZ6IW.js → chunk-5VG7RKEF.js} +2 -2
  12. package/dist/{chunk-MHATKJ3J.js → chunk-65AU3HFZ.js} +2 -2
  13. package/dist/{chunk-GKRRO3WC.js → chunk-6LNQOOTB.js} +2 -2
  14. package/dist/{chunk-OZUJ3VZS.js → chunk-72KY2ZFO.js} +2 -2
  15. package/dist/{chunk-QR337MAA.js → chunk-736BLPHR.js} +2 -2
  16. package/dist/chunk-7JRRXGVZ.js +2 -0
  17. package/dist/{chunk-XBIF45WK.js → chunk-7UQWUVRG.js} +2 -2
  18. package/dist/chunk-A6IDHNMC.js +4 -0
  19. package/dist/chunk-A6TANQNV.js +2 -0
  20. package/dist/{chunk-EOUTP32Q.js → chunk-AW2QHPLL.js} +2 -2
  21. package/dist/chunk-BSN22NRK.js +9 -0
  22. package/dist/{chunk-EW64FEJL.js → chunk-BVRS7RKQ.js} +2 -2
  23. package/dist/{chunk-FXWV2V7K.js → chunk-BZ53S4ZN.js} +2 -2
  24. package/dist/{chunk-MJXJ56LG.js → chunk-C5CTSJ6X.js} +2 -2
  25. package/dist/{chunk-OMGE3V2Q.js → chunk-CCKPYPDI.js} +2 -2
  26. package/dist/chunk-CZ425R2B.js +18 -0
  27. package/dist/{chunk-FPYQA7JK.js → chunk-DQVKIG3D.js} +2 -2
  28. package/dist/chunk-F6ICF7HL.js +40 -0
  29. package/dist/chunk-FAYI6KZ5.js +2 -0
  30. package/dist/{chunk-5JXH6VGF.js → chunk-FDEQIPPK.js} +2 -2
  31. package/dist/chunk-FRPEPTYJ.js +5 -0
  32. package/dist/chunk-GBEYTDY5.js +2 -0
  33. package/dist/{chunk-FXI3AAKO.js → chunk-GRJY65YT.js} +2 -2
  34. package/dist/chunk-HF25DFSC.js +3 -0
  35. package/dist/chunk-HHN2B5KA.js +2 -0
  36. package/dist/{chunk-H6RLM7D7.js → chunk-I46WR7MT.js} +2 -2
  37. package/dist/{chunk-GRZRMELG.js → chunk-IPQTC36U.js} +2 -2
  38. package/dist/{chunk-72QDTW5U.js → chunk-J7RWXLUL.js} +2 -2
  39. package/dist/{chunk-XYI7XRZC.js → chunk-KX5PLFZ5.js} +2 -2
  40. package/dist/{chunk-5LM7RJMQ.js → chunk-LPL4MA6R.js} +2 -2
  41. package/dist/chunk-LZHUWKGD.js +2 -0
  42. package/dist/{chunk-OT6CDRKC.js → chunk-MMLZEGMS.js} +2 -2
  43. package/dist/{chunk-LQSLW7K7.js → chunk-NZ4UDB5N.js} +2 -2
  44. package/dist/{chunk-3LQFMQPY.js → chunk-OBGRLXWF.js} +2 -2
  45. package/dist/chunk-P5RYBRIO.js +4 -0
  46. package/dist/chunk-PKMZCDQD.js +4 -0
  47. package/dist/{chunk-733EF5FD.js → chunk-PTQVNJ4Q.js} +2 -2
  48. package/dist/{chunk-EPPCGQUI.js → chunk-QPU7EXAW.js} +2 -2
  49. package/dist/chunk-QVI3NR7E.js +7 -0
  50. package/dist/{chunk-PTKQNPWX.js → chunk-QX7LLCGB.js} +2 -2
  51. package/dist/{chunk-27FU2KX7.js → chunk-QYB5P7GL.js} +2 -2
  52. package/dist/chunk-RVWSAMTT.js +2 -0
  53. package/dist/{chunk-GIOT3O6P.js → chunk-RXRLZFUL.js} +2 -2
  54. package/dist/{chunk-KT2ZO3CE.js → chunk-RYXW3KRC.js} +2 -2
  55. package/dist/{chunk-OWXN6ZS5.js → chunk-SGLLBSCV.js} +2 -2
  56. package/dist/{chunk-XAYARHNF.js → chunk-SULEXAHO.js} +2 -2
  57. package/dist/{chunk-IL2EVPYP.js → chunk-TH2N6QHW.js} +2 -2
  58. package/dist/{chunk-J43GIAVM.js → chunk-TL6QPNF5.js} +2 -2
  59. package/dist/{chunk-PQ6QG3EX.js → chunk-UDGXK2WA.js} +2 -2
  60. package/dist/{chunk-WMIQMXSK.js → chunk-UFX7EPBA.js} +2 -2
  61. package/dist/chunk-UQLFQLAF.js +2 -0
  62. package/dist/{chunk-WXMVK53S.js → chunk-UWYJDBDW.js} +2 -2
  63. package/dist/{chunk-VA3FJ3AY.js → chunk-UYD7FJ3K.js} +2 -2
  64. package/dist/{chunk-RISLKTKQ.js → chunk-VUKC6F77.js} +2 -2
  65. package/dist/{chunk-FRIASDLG.js → chunk-WG6KRH5F.js} +2 -2
  66. package/dist/{chunk-QMH2D6S5.js → chunk-XIVO4SDZ.js} +2 -2
  67. package/dist/{chunk-QPTVFG4O.js → chunk-XSNRACLV.js} +2 -2
  68. package/dist/chunk-XUGQU7PM.js +41 -0
  69. package/dist/{chunk-SXESPZUX.js → chunk-XXZXDXTD.js} +2 -2
  70. package/dist/chunk-Y6E3JHC4.js +2 -0
  71. package/dist/{chunk-DBTL56LR.js → chunk-YBEEVDJQ.js} +2 -2
  72. package/dist/chunk-YGHUVQLR.js +2 -0
  73. package/dist/chunk-YWDVDAD7.js +2 -0
  74. package/dist/chunk-YWOOQ4FF.js +2 -0
  75. package/dist/{chunk-NIGHS7UP.js → chunk-Z4I7BVIU.js} +2 -2
  76. package/dist/{chunk-TDBTVMHY.js → chunk-ZQO43G2T.js} +2 -2
  77. package/dist/{chunk-YNLK3G63.js → chunk-ZU6PROUY.js} +2 -2
  78. package/dist/cli.js +256 -205
  79. package/dist/{db-BAVwb4Pb.d.ts → db-Djj3Nqrb.d.ts} +2 -0
  80. package/dist/{health-B17sVFYf.d.ts → health-D5J42g4D.d.ts} +1 -1
  81. package/dist/index.d.ts +3 -2
  82. package/dist/index.js +3 -3
  83. package/dist/postinstall.js +1 -1
  84. package/dist/queries/affected.d.ts +1 -1
  85. package/dist/queries/affected.js +1 -1
  86. package/dist/queries/bottlenecks.d.ts +1 -1
  87. package/dist/queries/bottlenecks.js +1 -1
  88. package/dist/queries/by-kind.d.ts +1 -1
  89. package/dist/queries/by-kind.js +1 -1
  90. package/dist/queries/call-graph.d.ts +1 -1
  91. package/dist/queries/call-graph.js +1 -1
  92. package/dist/queries/change-surface.d.ts +1 -1
  93. package/dist/queries/change-surface.js +1 -1
  94. package/dist/queries/cleanup-plan.d.ts +1 -1
  95. package/dist/queries/cleanup-plan.js +1 -1
  96. package/dist/queries/co-change.d.ts +1 -1
  97. package/dist/queries/co-change.js +1 -1
  98. package/dist/queries/code.d.ts +1 -1
  99. package/dist/queries/code.js +1 -1
  100. package/dist/queries/complexity-hotspots.d.ts +1 -1
  101. package/dist/queries/complexity-hotspots.js +1 -1
  102. package/dist/queries/complexity.d.ts +1 -1
  103. package/dist/queries/complexity.js +1 -1
  104. package/dist/queries/convergence.d.ts +1 -1
  105. package/dist/queries/convergence.js +1 -1
  106. package/dist/queries/coupling.d.ts +1 -1
  107. package/dist/queries/coupling.js +1 -1
  108. package/dist/queries/cycles.d.ts +1 -1
  109. package/dist/queries/cycles.js +1 -1
  110. package/dist/queries/dataflow.d.ts +1 -1
  111. package/dist/queries/dataflow.js +1 -1
  112. package/dist/queries/dead.d.ts +1 -1
  113. package/dist/queries/dead.js +1 -1
  114. package/dist/queries/deep-chains.d.ts +1 -1
  115. package/dist/queries/deep-chains.js +1 -1
  116. package/dist/queries/deps.d.ts +1 -1
  117. package/dist/queries/deps.js +1 -1
  118. package/dist/queries/diff-gate.d.ts +1 -1
  119. package/dist/queries/diff-gate.js +1 -1
  120. package/dist/queries/diff-impact.d.ts +1 -1
  121. package/dist/queries/diff-impact.js +1 -1
  122. package/dist/queries/doc-drift.d.ts +1 -1
  123. package/dist/queries/doc-drift.js +1 -1
  124. package/dist/queries/drift.d.ts +2 -1
  125. package/dist/queries/drift.js +1 -1
  126. package/dist/queries/extract-candidates.d.ts +1 -1
  127. package/dist/queries/extract-candidates.js +1 -1
  128. package/dist/queries/fan.d.ts +1 -1
  129. package/dist/queries/fan.js +1 -1
  130. package/dist/queries/files.d.ts +1 -1
  131. package/dist/queries/health.d.ts +2 -2
  132. package/dist/queries/health.js +1 -1
  133. package/dist/queries/hierarchy.d.ts +1 -1
  134. package/dist/queries/hierarchy.js +1 -1
  135. package/dist/queries/hotspots.d.ts +1 -1
  136. package/dist/queries/hotspots.js +1 -1
  137. package/dist/queries/imports.d.ts +1 -1
  138. package/dist/queries/imports.js +1 -1
  139. package/dist/queries/incomplete-migration.d.ts +1 -1
  140. package/dist/queries/incomplete-migration.js +1 -1
  141. package/dist/queries/index.d.ts +2 -2
  142. package/dist/queries/index.js +1 -1
  143. package/dist/queries/isolated.d.ts +1 -1
  144. package/dist/queries/isolated.js +1 -1
  145. package/dist/queries/locality-candidates.d.ts +1 -1
  146. package/dist/queries/locality-candidates.js +1 -1
  147. package/dist/queries/members.d.ts +1 -1
  148. package/dist/queries/members.js +1 -1
  149. package/dist/queries/methods.d.ts +1 -1
  150. package/dist/queries/methods.js +1 -1
  151. package/dist/queries/outline.d.ts +1 -1
  152. package/dist/queries/outline.js +1 -1
  153. package/dist/queries/passthrough-candidates.d.ts +1 -1
  154. package/dist/queries/passthrough-candidates.js +1 -1
  155. package/dist/queries/plan-context.d.ts +1 -1
  156. package/dist/queries/plan-context.js +1 -1
  157. package/dist/queries/react-component-duplicates.d.ts +2 -1
  158. package/dist/queries/react-component-duplicates.js +1 -1
  159. package/dist/queries/react-hook-candidates.d.ts +2 -1
  160. package/dist/queries/react-hook-candidates.js +1 -1
  161. package/dist/queries/react-large-component-pressure.d.ts +1 -1
  162. package/dist/queries/react-large-component-pressure.js +1 -1
  163. package/dist/queries/recent-duplicates.d.ts +1 -1
  164. package/dist/queries/recent-duplicates.js +1 -1
  165. package/dist/queries/redundant-reexports.d.ts +1 -1
  166. package/dist/queries/redundant-reexports.js +1 -1
  167. package/dist/queries/refs.d.ts +1 -1
  168. package/dist/queries/refs.js +1 -1
  169. package/dist/queries/self-audit.d.ts +1 -1
  170. package/dist/queries/self-audit.js +1 -1
  171. package/dist/queries/similar-chains.d.ts +1 -1
  172. package/dist/queries/similar-chains.js +1 -1
  173. package/dist/queries/similar-files.d.ts +1 -1
  174. package/dist/queries/similar-files.js +1 -1
  175. package/dist/queries/similar-signatures.d.ts +1 -1
  176. package/dist/queries/similar-signatures.js +1 -1
  177. package/dist/queries/similar.d.ts +11 -2
  178. package/dist/queries/similar.js +1 -1
  179. package/dist/queries/slice.d.ts +1 -1
  180. package/dist/queries/slice.js +1 -1
  181. package/dist/queries/stale-abstractions.d.ts +1 -1
  182. package/dist/queries/stale-abstractions.js +1 -1
  183. package/dist/queries/stats.d.ts +1 -1
  184. package/dist/queries/surface.d.ts +1 -1
  185. package/dist/queries/surface.js +1 -1
  186. package/dist/queries/symbols.d.ts +1 -1
  187. package/dist/queries/symbols.js +1 -1
  188. package/dist/queries/system.d.ts +1 -1
  189. package/dist/queries/system.js +1 -1
  190. package/dist/queries/trace.d.ts +1 -1
  191. package/dist/queries/trace.js +1 -1
  192. package/dist/queries/unused-imports.d.ts +1 -1
  193. package/dist/queries/unused-imports.js +1 -1
  194. package/dist/queries/unused-params.d.ts +1 -1
  195. package/dist/queries/unused-params.js +1 -1
  196. package/dist/queries/vue-component-duplicates.d.ts +2 -1
  197. package/dist/queries/vue-component-duplicates.js +1 -1
  198. package/dist/queries/vue-composable-candidates.d.ts +2 -1
  199. package/dist/queries/vue-composable-candidates.js +1 -1
  200. package/dist/queries/vue-large-view-pressure.d.ts +1 -1
  201. package/dist/queries/wrapper-candidates.d.ts +1 -1
  202. package/dist/queries/wrapper-candidates.js +1 -1
  203. package/dist/runtime.js +1 -1
  204. package/docs/COMMAND_REFERENCE.md +1 -1
  205. package/docs/analyzer-inventory.md +29 -0
  206. package/docs/analyzer-validation-ledger.md +32 -1
  207. package/package.json +1 -1
  208. package/skills/scip-hyper-optimization/SKILL.md +97 -0
  209. package/skills/scip-hyper-optimization/agents/openai.yaml +4 -0
  210. package/skills/scip-query/SKILL.md +4 -0
  211. package/dist/chunk-3C4NIBY5.js +0 -2
  212. package/dist/chunk-5MHQI4RR.js +0 -3
  213. package/dist/chunk-7AOMEMOA.js +0 -4
  214. package/dist/chunk-BZ2RRK7Y.js +0 -8
  215. package/dist/chunk-C6ROZBJA.js +0 -32
  216. package/dist/chunk-CMXD5VC4.js +0 -2
  217. package/dist/chunk-CQEJU32R.js +0 -2
  218. package/dist/chunk-DOZ2X6TS.js +0 -2
  219. package/dist/chunk-FKYPOK7P.js +0 -5
  220. package/dist/chunk-G2CGUNQU.js +0 -4
  221. package/dist/chunk-HDBQHJNY.js +0 -2
  222. package/dist/chunk-IA7Q6HVP.js +0 -18
  223. package/dist/chunk-JOGZKF5W.js +0 -2
  224. package/dist/chunk-KRGBLZT2.js +0 -7
  225. package/dist/chunk-KUIIQPDA.js +0 -2
  226. package/dist/chunk-LONIY5FF.js +0 -2
  227. package/dist/chunk-M3YEHOCD.js +0 -2
  228. package/dist/chunk-MFWAZFYD.js +0 -2
  229. package/dist/chunk-P3K7LX7M.js +0 -4
  230. package/dist/chunk-PVZMPG5I.js +0 -2
  231. package/dist/chunk-QVS4SYAX.js +0 -7
  232. package/dist/chunk-TJXOD4IK.js +0 -62
  233. package/dist/chunk-UJEVABIR.js +0 -2
  234. package/dist/chunk-W2TIXAGN.js +0 -40
  235. package/dist/chunk-YOCYR7KJ.js +0 -2
  236. package/dist/chunk-ZUTV7DDX.js +0 -2
package/dist/cli.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import{program as Gs}from"commander";import{realpathSync as Rb}from"fs";import{fileURLToPath as XB}from"url";import{spawn as j0}from"child_process";import{createRequire as O0}from"module";import{availableParallelism as B0}from"os";import{fileURLToPath as ul}from"url";import{statSync as wb}from"fs";function Fe(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,...Lb(e.config.dbPath)}}function Lb(e){try{let t=wb(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function j(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 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
3
3
  FROM documents
4
4
  WHERE 1 = 1
5
5
  ${e.pathExclusionsFor("documents")}
6
6
  ${n}
7
7
  ${r}
8
- ORDER BY relative_path`,...i).map(a=>a.relative_path),s=t.extensions?o.filter(a=>t.extensions.some(c=>a.toLowerCase().endsWith(c.toLowerCase()))):o;return t.includeIgnored===!1?s.filter(a=>!e.isIgnored(a)):s}function Ib(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function Js(e,t){let n=Ib(t);return j(e,{like:n,includeIgnored:!1}).map(r=>({relativePath:r}))}import{extname as tu}from"path";var Db={".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 Db[tu(e).toLowerCase()]??null}function Rt(e){return tu(e).toLowerCase()===".vue"}var nu=[];function At(e){e.groups.length>0&&nu.push(e)}function Ks(e,t){let n=new Set(t.groups);for(let r of nu)r.groups.some(i=>n.has(i))&&(t.file!==void 0&&r.clearFile?r.clearFile(e,t.file):r.clearAll(e))}function ru(){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 U(e,t){let{cache:n,ensure:r}=ru(),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 At({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}function Y(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 At({name:e,groups:t.clearGroups,clearAll:i=>r.invalidate(i)}),r}var Pb={clearGroups:["whole-project","source-file"]};function Un(e){return rn(e,Pb)}function rn(e,t){let{cache:n,ensure:r}=ru(),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 At({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}import{createRequire as Nb}from"module";var Le=Nb(import.meta.url),Wi=null,iu=!1;function Eb(){if(iu)return null;if(Wi)return Wi;try{return Wi=Le("tree-sitter"),Wi}catch{return iu=!0,null}}var ou=new Map,Xs=new Set;function Tb(e){if(Xs.has(e))return null;let t=ou.get(e);if(t)return t;let n;try{switch(e){case"rust":n=Le("tree-sitter-rust");break;case"typescript":n=Le("tree-sitter-typescript").typescript;break;case"tsx":n=Le("tree-sitter-typescript").tsx;break;case"javascript":n=Le("tree-sitter-javascript");break;case"python":n=Le("tree-sitter-python");break;case"java":n=Le("tree-sitter-java");break;case"kotlin":n=Le("tree-sitter-kotlin");break;case"scala":n=Le("tree-sitter-scala");break;case"ruby":n=Le("tree-sitter-ruby");break;case"c":n=Le("tree-sitter-c");break;case"cpp":n=Le("tree-sitter-cpp");break;case"csharp":n=Le("tree-sitter-c-sharp");break;case"php":n=Le("tree-sitter-php").php;break;case"vb":{let r=Le("tree-sitter-vb-dotnet");n=r.language??r;break}}}catch{return Xs.add(e),null}return ou.set(e,n),n}var su=new Map;function _b(e){let t=su.get(e);if(t)return t;let n=Tb(e);if(!n)return null;let r=Eb();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return Xs.add(e),null}return su.set(e,i),i}function Fb(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function Br(e,t){let n=_b(e);if(!n)return null;try{return Fb(n,t)}catch{return null}}import{readFileSync as $b}from"fs";import{join as Ab}from"path";var Mb=U("source-text",{clearGroups:["whole-project","source-file"]}),jb=U("source-lines",{clearGroups:["whole-project","source-file"]});function F(e,t){let n=t.replace(/\\/g,"/");return Mb.get(e,n,()=>{let r=Ab(e.config.projectRoot,n);try{return $b(r,"utf-8")}catch(i){if(Ob(i))return"";throw i}})}function Ob(e){return typeof e=="object"&&e!==null&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function Qe(e,t){let n=t.replace(/\\/g,"/");return jb.get(e,n,()=>{let r=F(e,n);return r?r.split(`
9
- `):[]})}var Bb=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar))?\b/i;function Hr(e){let t=Bb.exec(e);return t?t[1]??"":null}function Gi(e,t,n){if(n<=0)return!1;let r=Qe(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(Hr(o)!==null)return!0;if(!o.startsWith("//")&&!o.startsWith("*")&&!o.startsWith("/*")&&!o.startsWith("@")&&!o.startsWith("#"))return!1}}return!1}import{parse as Gb}from"@vue/compiler-sfc";import{posix as Qs}from"path";import{parse as Hb}from"@vue/compiler-sfc";var Vb=Un("vue-sfc-units");function Ji(e,t){let n=lu(t),r=F(e,n);return Vb.get(e,n,r,()=>qb(e,n,r))}function lu(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Ys(e){let t=e?.toLowerCase();return!t||t==="js"||t==="javascript"||t==="jsx"?"javascript":t==="ts"||t==="typescript"?"typescript":t==="tsx"?"tsx":null}function on(e){return!e||e.body.length===0?0:e.body.split(`
10
- `).length}function qb(e,t,n){let r={relativePath:t,template:null,scripts:[],styles:[],customBlocks:[],errors:[]};if(!n)return r;let i;try{i=Hb(n,{filename:t})}catch(s){return r.errors.push(cu(s)),r}r.errors.push(...i.errors.map(cu));let{descriptor:o}=i;return o.template&&(r.template=zi(e,t,"template",o.template)),o.script&&r.scripts.push(au(e,t,o.script,!1)),o.scriptSetup&&r.scripts.push(au(e,t,o.scriptSetup,!0)),r.styles=o.styles.map(s=>zi(e,t,"style",s)),r.customBlocks=o.customBlocks.map(s=>zi(e,t,"custom",s)),r.errors.push(...[r.template,...r.scripts,...r.styles,...r.customBlocks].flatMap(s=>s?.errors??[])),r}function au(e,t,n,r){let i=zi(e,t,"script",n);return{...i,kind:"script",setup:r,astLanguage:Ys(i.lang)}}function zi(e,t,n,r){let i=Wb(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=Ub(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=F(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 Ub(e,t){let n=t.split(/[?#]/,1)[0];if(!n||n.startsWith("/")||n.includes("://"))return null;let r=lu(Qs.normalize(Qs.join(Qs.dirname(e),n)));return r===".."||r.startsWith("../")?null:r}function Wb(e){return{...e}}function cu(e){return e instanceof Error?e.message:String(e)}function Ki(e){let t=Gb(e),n=t.descriptor.scriptSetup??t.descriptor.script;if(!n||n.src)return null;let r=Ys(n.lang??null);return r?{body:n.content,startLine:Math.max(0,n.loc.start.line-1),language:r}:null}var uu=rn("ast-trees",{clearGroups:["whole-project","source-file"]});function fe(e,t){if(Rt(t))return zb(e,t);let n=W(t);if(!n)return null;let r=F(e,t);return r?uu.get(e,t,r,()=>Br(n,r)):null}function zb(e,t){let n=F(e,t);return n?uu.get(e,t,n,()=>{let r=Ki(n);if(!r)return null;let i=`
12
- `.repeat(r.startLine)+r.body;return Br(r.language,i)}):null}function Gn(e,t){let n=Jb(e,t);if(!n)return null;let r=Wn(n);return r?{calleeLeaf:r,memberAccess:Kb(n),line:e.startPosition.row}:null}function Jb(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 Kb(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function Wn(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?Wn(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?Wn(t):null}case"super":case"self":case"this":return null;default:return null}}import{createHash as Xb}from"crypto";import{readFileSync as Qb}from"fs";import{createRequire as Yb}from"module";import{dirname as du,join as mu}from"path";import Zb from"better-sqlite3";var eS=Yb(import.meta.url),tS="evidence.db",Xi=new WeakMap,nS=U("evidence-content-hash",{clearGroups:["whole-project","source-file"]}),rS=U("evidence-project-fingerprint",{clearGroups:["whole-project"]});function iS(){for(let e of["../package.json","../../package.json"])try{return eS(e).version}catch{}return"0.0.0"}var zn=iS();function Jn(e){return Xb("sha256").update(e).digest("hex")}function Ye(e,t,n){return nS.get(e,t,()=>Jn(n))}function pu(e){return rS.get(e,"current",()=>{try{let t=JSON.parse(Qb(mu(du(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 Jn(JSON.stringify({fingerprint:t.fingerprint,indexedLanguages:n}))}catch(t){return Zs("project fingerprint unavailable",t),null}})}function Zs(e,t){process.env.SCIP_QUERY_DEBUG&&console.error(`evidence-cache: ${e}: ${t instanceof Error?t.message:String(t)}`)}function Kn(e){if(Xi.has(e))return Xi.get(e)??null;let t=null;try{let n=new Zb(mu(du(e.config.dbPath),tS));n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),n.pragma("synchronous = NORMAL"),n.exec(`
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(`
13
13
  CREATE TABLE IF NOT EXISTS file_evidence (
14
14
  kind TEXT NOT NULL,
15
15
  relative_path TEXT NOT NULL,
@@ -35,20 +35,29 @@ import{program as Gs}from"commander";import{realpathSync as Rb}from"fs";import{f
35
35
  payload TEXT NOT NULL,
36
36
  PRIMARY KEY (relative_path, symbol)
37
37
  );
38
- `),t={evidence:n,readFileEvidence:n.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),writeFileEvidence:n.prepare("INSERT OR REPLACE INTO file_evidence (kind, relative_path, content_hash, version, payload) VALUES (?, ?, ?, ?, ?)"),readCallees:n.prepare(`SELECT payload FROM semantic_callees
39
- WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND version = ?`),writeCallees:n.prepare(`INSERT OR REPLACE INTO semantic_callees
38
+ `),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}
40
+ 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
42
+ 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}
44
+ ORDER BY version DESC
45
+ LIMIT 1`),writeCallees:n.prepare(`INSERT OR REPLACE INTO semantic_callees
40
46
  (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
41
- WHERE relative_path = ? AND symbol = ? AND project_fingerprint = ? AND version = ?`),writeReferences:n.prepare(`INSERT OR REPLACE INTO semantic_references
42
- (relative_path, symbol, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)`),dropStaleReferences:n.prepare("DELETE FROM semantic_references WHERE project_fingerprint != ?")}}catch(n){Zs("disabled (open failed)",n)}return Xi.set(e,t),t}function Xn(e,t,n){Zs(`disabled (${t})`,n),Xi.set(e,null)}function Mt(e,t,n,r){let i=Kn(e);if(!i)return null;try{return i.readFileEvidence.get(t,n,r,zn)?.payload??null}catch(o){return Xn(e,"file_evidence read",o),null}}function jt(e,t,n,r,i){let o=Kn(e);if(o)try{o.writeFileEvidence.run(t,n,r,zn,i)}catch(s){Xn(e,"file_evidence write",s)}}function fu(e,t,n,r,i){let o=Kn(e);if(!o)return null;try{return o.readCallees.get(t,n,r,i,zn)?.payload??null}catch(s){return Xn(e,"semantic_callees read",s),null}}function gu(e,t,n,r){let i=Kn(e);if(!i)return null;try{return i.readReferences.get(t,n,r,zn)?.payload??null}catch(o){return Xn(e,"semantic_references read",o),null}}function hu(e,t){if(t.length===0)return;let n=Kn(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){Xn(e,"semantic_callees write",r)}}function yu(e,t){if(t.length===0)return;let n=Kn(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){Xn(e,"semantic_references write",r)}}function Vr(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var oS=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function Qi(e,t){let n=aS(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:xu(n.functionNode),params:bu(n.functionNode),paramsEndLine:Su(n.functionNode),isLiteralPassthrough:Cu(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:xu(e),params:bu(e),paramsEndLine:Su(e),isLiteralPassthrough:Cu(e,t)}:null}function vu(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function bu(e){let t=vu(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(Vr(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 Su(e){let t=vu(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"?oS.has(e):!1}function aS(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 xu(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)Vr(r)||(n+=1);return n}function Cu(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=>!Vr(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=>!Vr(d)),l=e.namedChildren.find(d=>d.type==="parameters"||d.type==="formal_parameters");if(!l)return!1;let u=[];for(let d of l.namedChildren){if(d.type==="identifier"){u.push(d.text);continue}let m=d.namedChildren.find(f=>f.type==="identifier");m&&u.push(m.text)}if(c.length!==u.length)return!1;for(let d=0;d<u.length;d+=1){let m=c[d];if(m.type!=="identifier"||m.text!==u[d])return!1}return!0}var cS=new Set(["identifier","type_identifier","field_identifier"]),lS=new Set(["identifier"]),uS=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),dS=new Set(["rust","python"]),mS=/\{([^{}]*)\}/g,pS=/\b([A-Za-z_][\w]*)\b/g;function Ru(e,t){return fS(t).has(e.type)}function ku(e,t){return dS.has(t)&&e.type==="string_content"}function ea(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 fS(e){return e==="rust"?cS:e==="python"?lS:uS}function wu(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(mS)){let i=r[1]??"";for(let o of i.matchAll(pS))o[1]&&t(o[1],n)}}var gS=[/\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],hS=/^#!?\[\s*serde\s*\(/,yS=/^#!?\[\s*schemars\s*\(/,bS=/^#!?\[\s*validate\s*\(/,SS=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function Lu(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=Wn(r);if(!i||!SS.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 Iu(e,t){let n=hS.test(e),r=yS.test(e),i=bS.test(e);if(!(!n&&!r&&!i))for(let o of gS){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 Du(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 xS=rn("source-facts",{clearGroups:["whole-project","source-file"]});function ae(e,t){let n=F(e,t);if(!n)return null;let r=CS(t,n);return r?xS.get(e,t,n,()=>vS(e,t,r,n)):null}function CS(e,t){return Rt(e)?Ki(t)?.language??null:W(e)}function vS(e,t,n,r){let i=Ye(e,t,r),o=Mt(e,"source-facts",t,i);if(o){let c=kS(o);if(c&&c.language===n)return c}let s=fe(e,t);if(!s)return null;let a=LS(s,n);return jt(e,"source-facts",t,i,RS(a)),a}function RS(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 kS(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:ea(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function ta(e,t,n,r){let i=ae(e,t);return i?wS(i,n,r)?.isLiteralPassthrough??!0:!0}function wS(e,t,n){return e.callables.find(r=>r.startLine===t&&r.endLine===n)??null}function LS(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=Qi(l,t);u&&n.push(u);let d=Gn(l,t);d&&r.push(d),Lu(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&Iu(l.text,i),Ru(l,t)&&a(l.text,l.startPosition.row),ku(l,t)&&wu(l,a);for(let m of l.children)c(m)};return c(e.rootNode),{language:t,callables:n,callSites:r,typeContainerMap:Du(e,t),identifierLineMap:s,identifiersByLine:ea(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:i,crossLanguageDispatchNames:o}}var Pu=new Set(["rust","typescript","tsx","javascript","python"]);function na(e,t){let n=ae(e,t);return!n||!Pu.has(n.language)?null:n.callables.map(r=>({name:r.name,startLine:r.startLine,endLine:r.endLine}))}function Qn(e,t){let n=ae(e,t);return!n||!Pu.has(n.language)?null:n.callSites}function ra(e,t){return ae(e,t)?.typeContainerMap??new Map}import{ElementTypes as IS,NodeTypes as Eu,parse as DS}from"@vue/compiler-dom";import{parse as sH}from"@vue/compiler-sfc";function Yi(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var PS=Un("vue-template-facts"),NS=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),ES=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"]),TS=new Set(["div","span","template"]),_S=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 Tu(e,t){let n=t.replace(/\\/g,"/"),r=F(e,n);return PS.get(e,n,r,()=>FS(n,Ji(e,n).template))}function FS(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=DS(t.body,{comments:!1})}catch{return n}let i=new Set,o=s=>{s.trim()&&i.add(s)};return _u(r.children,t.startLine,n,o),n.structuralTokens=[...i].sort(),n}function _u(e,t,n,r){for(let i of e)i.type===Eu.ELEMENT&&($S(i,t,n,r),_u(i.children,t,n,r))}function $S(e,t,n,r){let i=qS(e.tag),o={tag:e.tag,normalized:i,kind:VS(e),startLine:Yn(t,e.loc.start.line),endLine:Yn(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),TS.has(e.tag)||r(`native:${e.tag}`));for(let s of e.props)AS(s,t,n,r)}function AS(e,t,n,r){if(e.type===Eu.ATTRIBUTE){let a=e.value?.content??null,c=Nu("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),r(`prop:${e.name}`);return}let i=jS(e),o=Fu(e.exp),s=Nu(MS(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&&OS(o,t,e.loc.start.line,n,r)}function Nu(e,t,n,r,i,o){return{kind:e,name:t,value:n,startLine:Yn(r,i),endLine:Yn(r,o)}}function MS(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function jS(e){let t=Fu(e.arg);return t||e.name}function Fu(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function OS(e,t,n,r,i){for(let o of BS(e)){let s={name:o,startLine:Yn(t,n),endLine:Yn(t,n)};r.expressionIdentifiers.push(s),i(`id:${o}`)}}function BS(e){let t=new Set,n=HS(e),r=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,i;for(;i=r.exec(n);){let o=i[0];_S.has(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function HS(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 VS(e){let t=e.tag;return e.tagType===IS.COMPONENT?"component":NS.has(t)?"builtin":ES.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function qS(e){return Yi(e,/[-_:]/)}function Yn(e,t){return e+Math.max(0,t-1)}import{readdirSync as US}from"fs";import{execFileSync as WS}from"child_process";import{extname as Zi,join as GS}from"path";var ia=[".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"],$u=[".vue"],Au=[".tsx",".jsx"],Mu=[".vue"],zS=[...Au,...Mu],JS=new Set(Au),KS=new Set(Mu),ju=new Set(ia.map(e=>e.toLowerCase())),XS=[...ju].sort().join(","),oa=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function Ie(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(c=>c.toLowerCase()),o=i?new Set(i):ju,s=i?[...o].sort().join(","):XS,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return QS.get(e,a,()=>{let c=new Set;if(n)for(let l of j(e,{includeIgnored:!1}))o.has(Zi(l).toLowerCase())&&c.add(l);if(r)for(let l of YS(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}function eo(e,t={}){let n=!1,r=!1;for(let i of Ie(e,{extensions:zS})){if(t.scope&&!i.includes(t.scope))continue;let o=Zi(i).toLowerCase();if(n||=JS.has(o),r||=KS.has(o),n&&r)break}return{react:n,vue:r}}var QS=U("source-files",{clearGroups:[]});function YS(e,t){return ZS(e,t)??ex(e,t)}function ZS(e,t){try{let n=WS("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(`
43
- `)){let o=i.trim();o&&t.has(Zi(o).toLowerCase())&&r.add(o)}return r}catch{return null}}function ex(e,t){let n=new Set,r=i=>{let o=i?GS(e,i):e,s;try{s=US(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!oa.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(Zi(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}var tx=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),nx=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),rx=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),ix=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),ox=new Set(["catch","for","function","if","return","switch","while"]);function Ou(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+=on(n),n.external&&(t.externalLineCount+=on(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(...lx(n));let r=Br(n.astLanguage,n.body);r?ax(n,r.rootNode,t):cx(n,t)}return sx(t),t.externalScriptPaths=Hu(t.externalScriptPaths),t}function sx(e){e.composables=Zn(e,"composable"),e.stores=Zn(e,"store"),e.reactivity=Zn(e,"reactivity"),e.lifecycle=Zn(e,"lifecycle"),e.requests=Zn(e,"request"),e.macros=Zn(e,"macro")}function Zn(e,t){return Hu(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function ax(e,t,n){let r=new Set,i=new Set,o=s=>{let a=Qi(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=Gn(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:Bu(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||ox.has(r)||t.calls.push({name:r,sourcePath:e.sourcePath,line:e.startLine+to(e.body,n.index??0),categories:Bu(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+to(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+to(e.body,n.index??0);t.functions.push({name:r,sourcePath:e.sourcePath,startLine:i,endLine:i,setup:e.setup})}}function lx(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+to(e.body,n.index??0);for(let s of ux(r))t.push({local:s,source:i,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function ux(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 Bu(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),tx.has(e)&&t.push("reactivity"),nx.has(e)&&t.push("lifecycle"),rx.has(e)&&t.push("request"),ix.has(e)&&t.push("macro"),t}function to(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 Hu(e){return[...new Set(e)].sort()}var dx=new Set(["in","key","of"]),mx=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]),px=Un("vue-component-behavior-profiles");function er(e,t={}){let n=Ie(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=>fx(e,i)).filter(i=>(t.minTemplateTokens===void 0||i.templateTokens.size>=t.minTemplateTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function fx(e,t){let n=t.replace(/\\/g,"/"),r=F(e,n),i=px.get(e,n,r,()=>gx(e,n,r));return hx(i)}function gx(e,t,n){let r=Ji(e,t),i=Tu(e,t),o=Ou(r),s=Sx(i),a=i.expressionIdentifiers.map(h=>h.name).filter(h=>!s.includes(h)).filter((h,g,y)=>y.indexOf(h)===g).sort(),c=i.componentTags.map(h=>h.normalized).filter((h,g,y)=>y.indexOf(h)===g).sort(),l=n?n.split(`
44
- `).length:0,u=on(r.template),d=o.lineCount,m=r.styles.reduce((h,g)=>h+on(g),0),f=r.customBlocks.reduce((h,g)=>h+on(g),0);return{file:t,sfc:r,templateFacts:i,scriptFacts:o,templateTokens:new Set(i.structuralTokens),behaviorTokens:bx(i,o,a),templateBindingNames:a,templateLocalNames:s,componentNames:c,sfcLines:l,totalLines:l+o.externalLineCount,templateLines:u,scriptLines:d,styleLines:m,externalScriptLines:o.externalLineCount,externalScriptPaths:o.externalScriptPaths,customBlockLines:f}}function hx(e){let t=yx(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 yx(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 bx(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(mx.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 Sx(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let r of xx(n.value))t.add(r);for(let n of e.slots)if(n.value)for(let r of Vu(n.value))t.add(r);return[...t].sort()}function xx(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?Vu(t[1]??""):[]}function Vu(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];dx.has(r)||t.push(r)}return t}import{extname as Cx}from"path";var vx=[".tsx",".jsx"],qu=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),Rx=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),kx=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),wx=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),Lx=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),Ix=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),Dx=new Set(["children","className","false","key","null","style","true","undefined"]),Px=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]);function tr(e,t={}){let n=Ie(e,{extensions:vx}).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=>Nx(e,i)).filter(i=>(t.minJsxTokens===void 0||i.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function Nx(e,t){let n=t.replace(/\\/g,"/"),r=Ex(n);if(!r)return[];let i=fe(e,n);if(!i)return[];let o=Qe(e,n).length;return Tx(i.rootNode,r).filter(a=>a.kind==="hook"||Ju(a.bodyNode)).map(a=>{let c=Mx(a.bodyNode),l=Vx(a.bodyNode,r);return{file:n,name:a.name,kind:a.kind,startLine:a.node.startPosition.row,endLine:a.node.endPosition.row,loc:Math.max(1,a.node.endPosition.row-a.node.startPosition.row+1),fileLines:o,jsxTokens:c.tokens,behaviorTokens:l.tokens,componentNames:kt(c.componentNames),nativeTags:kt(c.nativeTags),propNames:kt(c.propNames),eventNames:kt(c.eventNames),hookNames:kt(l.hookNames),requestNames:kt(l.requestNames),stateNames:kt(l.stateNames),effectNames:kt(l.effectNames),handlerNames:kt(l.handlerNames)}})}function Ex(e){let t=Cx(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:W(e)}function Tx(e,t){let n=[],r=new Set,i=o=>{let s=_x(o);if(s&&!$x(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 _x(e){if(e.type==="function_declaration"){let o=zu(e);return!o||!Uu(o)?null:{name:o,kind:Wu(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||!Uu(r))return null;let i=Fx(n);return i?{name:r,kind:Wu(r),node:e,bodyNode:i}:null}function Uu(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function Wu(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function Fx(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=Ax(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 $x(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 zu(e){return qr(e.childForFieldName("name")??e.namedChild(0))}function Ax(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function Ju(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(Ju)}function Mx(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"?jx(r,t):r.type==="jsx_expression"?Ox(r,t):r.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let i of r.namedChildren)n(i)};return n(e),t}function jx(e,t){let n=Bx(e),r=!1;if(n){let i=Gu(n);r=zx(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=Hx(i);if(!o)continue;let s=Gu(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 Px.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 Ox(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 Jx(n))Dx.has(r)||t.tokens.add(`binding:${r}`)}function Bx(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 Hx(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 Vx(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=Gn(i,t);o&&qx(o.calleeLeaf,n)}else if(i.type==="variable_declarator")Wx(i,n);else if(i.type==="function_declaration"){let o=zu(i);o&&Ku(o,n)}for(let o of i.namedChildren)r(o)};return r(e),n}function qx(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!qu.has(e)&&!wx.has(e)&&t.tokens.add(`hook:${e}`)),qu.has(e)&&t.tokens.add(`react-hook:${e}`),Rx.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),kx.has(e)&&t.tokens.add(`state-hook:${e}`),Ux(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function Ux(e){if(Lx.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function Wx(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&&Ku(i,t)}function Ku(e,t){let n=Gx(e);!n||!Ix.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function Gx(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 zx(e){return/^[A-Z]/.test(e)||e.includes(".")}function Gu(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 Jx(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 kt(e){return[...e].sort()}function sn(e,t,n={}){let r=ae(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 Kx={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function ge(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=Xx(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function lt(e){let t=ge(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 Xx(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||Xu(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&&!Xu(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=Kx[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function Xu(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function b(e){let t=ge(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=Qx(i);o&&r.push(o)}return r.join(":")}function Qx(e){let t=e.suffix==="namespace"?Yx(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function Yx(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 A(e){let t=ge(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 ee(e){let t=ge(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function Ce(e){return e.endsWith("().")||ee(e)==="method"}function ce(e){let t=ee(e);return t==="method"||t==="term"}function Ot(e){return ee(e)==="namespace"}var Zx=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function no(e){return Zx.test(e)}var eC=new Set(["test","tests","_tests"]);function nr(e){let t=ge(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&&eC.has(r.name))return!0}return!1}function Qu(e,t){let n=ge(e),r=ge(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 Yu(e,t){let n=ge(e),r=ge(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 rr(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
47
+ 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}
49
+ ORDER BY version DESC
50
+ 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
45
54
  FROM global_symbols gs
46
55
  JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
47
56
  JOIN documents d ON der.document_id = d.id
48
57
  WHERE ${t.where}
49
58
  ${e.pathExclusionsFor("d")}
50
- ${ed(t.orderBy)}
51
- ${td(t.limit)}`,...t.params??[])}function ir(e,t){return e.all(`SELECT
59
+ ${ld(t.orderBy)}
60
+ ${ud(t.limit)}`,...t.params??[])}function ur(e,t){return e.all(`SELECT
52
61
  gs.id,
53
62
  gs.symbol,
54
63
  c.document_id,
@@ -65,8 +74,8 @@ import{program as Gs}from"commander";import{realpathSync as Rb}from"fs";import{f
65
74
  AND ${t.where}
66
75
  ${e.pathExclusionsFor("d")}
67
76
  GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
68
- ${ed(t.orderBy)}
69
- ${td(t.limit)}`,...t.params??[])}function ed(e){return e?`ORDER BY ${e}`:""}function td(e){return typeof e=="number"?`LIMIT ${e}`:""}function an(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 cn(e){if(!e)return null;let t=Zu(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(Zu(r)??r).replace(/\n/g," ")}function Zu(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function tC(e){if(lt(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 or(e,t,n={}){let r=new Map;for(let o of t)e.length>0&&!tC(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 nC=U("file-definitions",{clearGroups:["definition-catalog"]}),nd=new WeakMap;function G(e,t){return nC.get(e,t,()=>{let n=or(rC(e,t),iC(e,t),{sort:!0});return sC(e,t,n.map(oC))})}function rC(e,t){return e.all(`SELECT
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
70
79
  gs.id,
71
80
  gs.symbol,
72
81
  der.document_id,
@@ -82,7 +91,7 @@ import{program as Gs}from"commander";import{realpathSync as Rb}from"fs";import{f
82
91
  JOIN documents d ON der.document_id = d.id
83
92
  WHERE d.relative_path = ?
84
93
  ${e.symbolNoiseFor("gs")}
85
- ORDER BY der.start_line, der.end_line`,t)}function iC(e,t){return e.all(`SELECT
94
+ ORDER BY der.start_line, der.end_line`,t)}function IC(e,t){return e.all(`SELECT
86
95
  gs.id,
87
96
  gs.symbol,
88
97
  c.document_id,
@@ -101,11 +110,51 @@ import{program as Gs}from"commander";import{realpathSync as Rb}from"fs";import{f
101
110
  AND m.role = 1
102
111
  ${e.symbolNoiseFor("gs")}
103
112
  GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
104
- ORDER BY start_line, end_line`,t)}function oC(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:A(e.symbol),parentTypeName:lt(e.symbol),isFunctionLike:ce(e.symbol),isTypeLike:ee(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function ut(e,t={}){return Ur(e,t.scope)}function Ur(e,t){return j(e,{scope:t,includeIgnored:!1}).flatMap(n=>G(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function ro(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:an(cn(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function sa(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 Be(e,t){let n=nd.get(e);return n||(n=sa(e),nd.set(e,n)),n.get(t)??null}function ln(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 sC(e,t,n){let r=F(e,t),i=na(e,t);return i?mC(n,i,r):r?aC(n,r):n}function aC(e,t){let n=t.split(/\r?\n/),r=cC(e,n),i=lC(e,r),o=uC(i,n);return dC(e,o)}function cC(e,t){let n=e.some(i=>io(i.symbol))?gC(t):null,r=new Map;for(let i of e)r.set(i.symbolId,fC(t,n,i));return r}function lC(e,t){return e.filter(n=>io(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 uC(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:hC(t,i.definition,i.startLine,s)})}return n}function dC(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function mC(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(!pC(i)||!i.leaf)return rd(i,n);let o=r.get(i.leaf);if(!o||o.length===0)return rd(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 pC(e){return io(e.symbol)?!0:ee(e.symbol)==="term"&&lt(e.symbol)===null}function rd(e,t){if(!t||!e.leaf||ee(e.symbol)!=="term"||lt(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 fC(e,t,n){if(!io(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 gC(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 hC(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=yC(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 yC(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 io(e){return e.includes("().")}function oo(e){let t=ge(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 EC}from"fs";import{basename as id,isAbsolute as TC,join as _C}from"path";function B(e,t){let n=ar(e,t.trim());if(n)return n;let r=RC(e,t);if(r)return r;let i=bC(e,t);return i||vC(e,t)}function bC(e,t){let n=ca(t),r=aa(n);if(!r)return null;let i=`%${r.path}%`,o=r.leaf,a=SC(e,i,o,n)[0];return a?ln(e,a):null}function SC(e,t,n,r){let i=or([],[...xC(e,t,n),...CC(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>sr(o,r)>1);return i.sort((o,s)=>sr(s,r)-sr(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 xC(e,t,n){return rr(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function CC(e,t,n){return ir(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function vC(e,t){let n=ca(t),r=PC(t),i=IC(e,r),o=NC(i,t,n);if(o&&!e.isIgnored(o.relative_path))return ln(e,o);let s=null;for(let a of i){if(e.isIgnored(a.relative_path))continue;let c=DC(a,t,n,r);c<=0||(!s||c>s.score)&&(s={row:a,score:c})}return s?ln(e,s.row):null}function RC(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=kC(e,r,s,a)??wC(e,r,s,a);return c&&!e.isIgnored(c.relative_path)?ln(e,c):null}function kC(e,t,n,r){return rr(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 wC(e,t,n,r){return ir(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 ar(e,t){let r=rr(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line",limit:1})[0]??ir(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line",limit:1})[0];return!r||e.isIgnored(r.relative_path)?null:ln(e,r)}function so(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=LC(e,t.symbolId)[0];return n?ln(e,n):null}function LC(e,t){let n=rr(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),r=ir(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return or(n,r)}function IC(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(`
105
- AND `),o=rr(e,{where:i,params:r,limit:200}),s=ir(e,{where:i,params:r,limit:200});return or(o,s)}function DC(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=A(e.symbol),f=e.display_name??"",h=e.symbol.toLowerCase(),g=d.toLowerCase(),y=m.toLowerCase(),S=f.toLowerCase(),v=e.relative_path.toLowerCase(),k=/[/:.]/.test(n),N=aa(n),w=N?.leaf.toLowerCase(),R=0;return(u===i||u===o)&&(R+=1150),(d===i||d===o)&&(R+=1100),f===s&&(R+=1180),m===s&&(R+=1160),(`${m}()`===i||`${m}()`===o)&&(R+=955),(h===a||h===c)&&(R+=1e3),(g===a||g===c)&&(R+=950),(v===a||v===c)&&(R+=925),(v.endsWith(`/${c}`)||v.endsWith(`/${a}`))&&(R+=875),S===l&&(R+=850),y===l&&(R+=825),(`${y}()`===a||`${y}()`===c)&&(R+=820),(g.endsWith(`:${c}`)||g.endsWith(`:${l}`)||g.endsWith(`:${l}()`))&&(R+=800),h.includes(c)&&(R+=120),g.includes(c)&&(R+=140),v.includes(c)&&(R+=140),S.includes(c)&&(R+=110),r.every($=>{let I=$.toLowerCase();return h.includes(I)||g.includes(I)||v.includes(I)||S.includes(I)})&&(R+=100+r.length*15),N&&v.includes(N.path.toLowerCase())&&(R+=360,w&&(y===w||`${y}()`===w||`${y}()`==`${w}()`)&&(R+=700),Ce(e.symbol)&&(R+=180)),ce(e.symbol)&&y===l&&(R+=60),!k&&Ot(e.symbol)&&(R-=160),R-=Math.min(50,Math.max(0,e.end_line-e.start_line)),R}function aa(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 ca(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function PC(e){let t=ca(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 NC(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||sr(o,n)>1||o.relative_path===r});return i.length===0?null:(i.sort((o,s)=>sr(s,n)-sr(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 sr(e,t){let n=aa(t);if(!n)return 0;let r=e.relative_path.toLowerCase(),i=A(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return r.includes(o)?i!==s?1:Ce(e.symbol)?lt(e.symbol)===null?5:4:lt(e.symbol)===null?3:2:0}function Ee(e,t){let n=od(e,t,{allowMultiple:!1})[0]?.relativePath;return n||FC(e,t)}function cr(e,t){return od(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function FC(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=TC(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=_C(e.config.projectRoot,r);return EC(i)?r:null}function od(e,t,n){let r=sd(t);if(!r)return[];let i=j(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:$C(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 $C(e,t){let n=sd(e),r=id(n),i=id(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 sd(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{basename as tw}from"path";import{existsSync as ao}from"fs";import{basename as AC,dirname as Bt,extname as wt,join as Ze,relative as Wr,resolve as He}from"path";var MC=Y("indexed-paths",{clearGroups:[]}),jC=Y("indexed-path-digest",{clearGroups:[]}),un=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],co=[".py",".pyi"],$e=[".java",".scala",".kt",".kts"],lo=[".rs"],uo=[".rb"],mo=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],Ht=[".cs",".vb"],po=[".dart"],dn=[".php"],OC=new Set(un),la=new Set(co),ad=new Set($e),ua=new Set(lo),da=new Set(uo),cd=new Set(mo),ld=new Set(Ht),ma=new Set(po),ud=new Set(dn),BC=[{extensions:un,lookup:OC},{extensions:co,lookup:la},{extensions:$e,lookup:ad},{extensions:lo,lookup:ua},{extensions:uo,lookup:da},{extensions:mo,lookup:cd},{extensions:Ht,lookup:ld},{extensions:po,lookup:ma},{extensions:dn,lookup:ud}];function Vt(e,t){return t.has(wt(e).toLowerCase())}function HC(e){return Vt(e,la)}function VC(e){return Vt(e,ad)}function qC(e){return Vt(e,ua)}function UC(e){return Vt(e,da)}function WC(e){return Vt(e,cd)}function GC(e){return Vt(e,ld)}function dd(e){return wt(e).toLowerCase()===".vb"}function zC(e){return Vt(e,ma)}function JC(e){return Vt(e,ud)}function pa(e){let t=wt(e).toLowerCase();for(let n of BC)if(n.lookup.has(t))return n.extensions;return un}function KC(e){return VC(e)||GC(e)||JC(e)}function tt(e,t,n){return HC(t)?lr(e,t,n):qC(t)?Lt(e,t,n):UC(t)?fo(e,t,n):WC(t)?go(e,t,n):KC(t)?te(e,n.replace(/\\/g,"."),pa(t)):zC(t)?ho(e,t,n):XC(e,t,n)}function XC(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let r=Bt(Ze(e.config.projectRoot,t)),i=He(r,n),o=ur(e);for(let s of tv(i)){let a=et(Wr(e.config.projectRoot,s));if(o.has(a)||ao(s))return a}return et(Wr(e.config.projectRoot,i))}function lr(e,t,n){let r=ur(e),i;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=Bt(Ze(e.config.projectRoot,t));for(let l=1;l<s;l++)c=Bt(c);i=a?He(c,a.replace(/\./g,"/")):c}else i=He(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of QC(i)){let s=et(Wr(e.config.projectRoot,o));if(r.has(s)||ao(o))return s}return null}function Lt(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=Bt(Ze(e.config.projectRoot,t)),o;return r.startsWith("crate::")?o=He(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?o=He(i,r.slice(6).replace(/::/g,"/")):o=He(Bt(i),r.slice(7).replace(/::/g,"/")),fa(e,YC(o))}function fo(e,t,n){let r=Bt(Ze(e.config.projectRoot,t)),i=He(r,n);return fa(e,ZC(i))}function go(e,t,n){let r=Bt(Ze(e.config.projectRoot,t)),i=[He(r,n),He(e.config.projectRoot,n),He(e.config.projectRoot,"include",n),He(e.config.projectRoot,"src",n)];return fa(e,i)}function te(e,t,n){let r=ur(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=>AC(u)===`${s}${c}`);if(l)return l}let a=[...r].filter(c=>n.includes(wt(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function ho(e,t,n){let r=ur(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=et(c.startsWith("lib/")?c:`lib/${c}`);return r.has(l)?l:null}let i=Bt(Ze(e.config.projectRoot,t)),o=He(i,n);for(let s of ev(o)){let a=et(Wr(e.config.projectRoot,s));if(r.has(a)||ao(s))return a}return null}function QC(e){let t=wt(e);return la.has(t)?[e]:[`${e}.py`,`${e}.pyi`,Ze(e,"__init__.py"),Ze(e,"__init__.pyi")]}function fa(e,t){let n=ur(e);for(let r of t){let i=et(Wr(e.config.projectRoot,r));if(n.has(i)||ao(r))return i}return null}function YC(e){let t=wt(e);return ua.has(t)?[e]:[`${e}.rs`,Ze(e,"mod.rs")]}function ZC(e){let t=wt(e);return da.has(t)?[e]:[`${e}.rb`,Ze(e,"index.rb")]}function ev(e){let t=wt(e);return ma.has(t)?[e]:[`${e}.dart`,e]}function tv(e){let t=wt(e),n=new Set;if(t){n.add(e);for(let r of un)n.add(e.slice(0,-t.length)+r)}else for(let r of un)n.add(`${e}${r}`),n.add(Ze(e,`index${r}`));return[...n]}function ur(e){return MC.get(e,()=>new Set(j(e,{includeIgnored:!1}).map(et)))}function md(e){return jC.get(e,()=>Jn([...ur(e)].sort().join(`
106
- `)))}function et(e){return e.replace(/\\/g,"/")}import{basename as fd}from"path";function mn(e){return e.replace(/'''[\s\S]*?'''/g,qt).replace(/"""[\s\S]*?"""/g,qt).replace(/#.*$/gm,qt).replace(/\/\/.*$/gm,qt).replace(/\/\*[\s\S]*?\*\//g,qt).replace(/`(?:\\[\s\S]|[^`])*`/g,qt).replace(/'(?:\\.|[^'\\\r\n])*'/g,qt).replace(/"(?:\\.|[^"\\\r\n])*"/g,qt)}function qt(e){return e.replace(/[^\r\n]/g," ")}var wV=rn("stripped-lines",{clearGroups:["whole-project","source-file"]});At({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{yo=null,Gr=""},clearFile:()=>{yo=null,Gr=""}});var yo=null,Gr="";function nv(e){return yo===e||(yo=e,Gr=mn(e)),Gr}function Ut(e,t,n){let r=nv(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function Te(e,t){return new RegExp(`\\b${pd(t)}\\b`,"m").test(e)}function dr(e,t){let n=new Set,r=new RegExp(`\\b${pd(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 pd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function zr(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var rv=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 Ae(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function ne(e,t){let n=new Set,r=(i,o)=>{let s=o||t.has(i.type);!s&&rv.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,s)};return r(e.rootNode,!1),n}function dt(e,t,n,r,i,o,s){return{importedName:i,localName:o,sourcePath:s??te(e,r,pa(t)),kind:"named",used:Te(n,o),usedMembers:[]}}function Z(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 mr(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 pn(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function fn(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 Ve(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=Ut(e,i.index,i.index+o.length);for(let a of n(i,s))r.push(a)}return r}function qe(e,t,n,r){let i=fe(e,t);if(i){let o=n(i);if(o)return o}return r()}function bo(e,t,n,r){let i=fe(e,t),o=W(t),s=o?n[o]:void 0;return i&&s?s(i):r()}function gd(e,t,n){return qe(e,t,r=>ov(e,t,r),()=>iv(e,t,n))}function iv(e,t,n){return Ve(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=fd(o).replace(/\.[^.]+$/,"");return[mr(o,s,go(e,t,o),Te(i,s))]})}function ov(e,t,n){let r=ne(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=fd(s).replace(/\.[^.]+$/,"");i.push(Z(s,a,go(e,t,s),r))}return i}function hd(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=Ut(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:ho(e,t,o),kind:s?"namespace":"side-effect",used:s?Te(c,s):!0,usedMembers:s?dr(c,s):[]})}return r}function yd(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:ho(e,t,o)})}return r}function bd(e,t,n){return bo(e,t,{csharp:r=>av(e,t,r),vb:r=>sv(e,t,r)},()=>{let r=dd(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return Ve(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[dt(e,t,o,u,d,m,te(e,u,Ht))]})})}function sv(e,t,n){let r=ne(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(Z(u,d,te(e,l,Ht),r,c?"namespace":"named"))}return i}function av(e,t,n){let r=ne(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(Z(u,d,te(e,l,Ht),r,a?"namespace":"named"))}return i}var cv=U("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function Sd(e,t){return cv.get(e,t,()=>{let n=new Set,r=F(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 ga(e,t,n){return qe(e,t,r=>uv(e,t,r),()=>lv(e,t,n))}function lv(e,t,n){return Cv(n).flatMap(r=>vv(e,t,r.clause,r.specifier,r.start,r.end,n))}function uv(e,t,n){let r=dv(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...mv(e,t,n,o,r));return i}function dv(e,t,n){let r=ne(n,new Set(["import_statement"]));if(Rt(t))for(let i of Sd(e,t))r.add(i);return r}function mv(e,t,n,r,i){let o=yv(r);if(!o)return[];let s=tt(e,t,o),a=Ae(r,"import_clause");return a?pv(n,a,s,i,bv(r.text)):[pn("*",s)]}function pv(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(fv(s.text,n,r,i));else if(s.type==="namespace_import"){let a=gv(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...hv(s,n,r,i));return o}function fv(e,t,n,r){return Z("default",e,t,n,"default",{isTypeOnly:r})}function gv(e,t,n,r,i){let s=Ae(t,"identifier")?.text??"";if(!s)return null;let a=xv(e,s);return fn("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function hv(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(Z(c,l,t,n,"named",{isTypeOnly:r||Sv(o.text)}))}return i}function yv(e){let t=Ae(e,"string");if(!t)return null;let n=Ae(t,"string_fragment");return n?n.text:null}function bv(e){return/^\s*import\s+type\b/.test(e)}function Sv(e){return/^\s*type\b/.test(e.trim())}function xv(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 Cv(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 vv(e,t,n,r,i,o,s){let a=tt(e,t,r),c=Ut(s,i,o);return n?Rv(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=dr(c,u.localName);return fn(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||Te(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?pn(u.importedName,u.sourcePath):mr(u.importedName,u.localName??"",u.sourcePath,u.localName?Te(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[pn("*",a)]}function Rv(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=kv(r),s=[];return i&&s.push(...xd(i,n)),o&&s.push(...xd(o,n)),s}function xd(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 kv(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 ha(e,t,n){let r=fe(e,t);return r?Nv(e,t,r):wv(e,t,n)}function wv(e,t,n){return[...Lv(e,t,n),...Iv(e,t,n),...Dv(e,t,n)]}function Lv(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=>Pv(d.trim())).filter(d=>!!d),l=pr(n,o.index),u=pr(n,o.index+o[0].length-1);r.push({kind:"named",sourcePath:tt(e,t,a),names:c,startLine:l,endLine:u})}return r}function Iv(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=pr(n,o.index),c=pr(n,o.index+o[0].length-1);r.push({kind:"star-as",sourcePath:tt(e,t,s),names:[],startLine:a,endLine:c})}return r}function Dv(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=pr(n,o.index),c=pr(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:tt(e,t,s),names:[],startLine:a,endLine:c})}return r}function Pv(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 pr(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Nv(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=Ev(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=Tv(i,o,s,a);r.push(c)}return r}function Ev(e,t,n){let r=Ae(n,"string");if(!r)return;let i=Ae(r,"string_fragment");if(i)return tt(e,t,i.text)}function Tv(e,t,n,r){let i=Ae(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 Ae(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function Cd(e,t,n){return bo(e,t,{java:r=>_v(e,t,r),kotlin:r=>Fv(e,t,r),scala:r=>$v(e,t,r)},()=>Ve(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?Av(e,t,o,i):[]}))}function _v(e,t,n){let r=ne(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(fn("*",te(e,l,$e)));continue}let u=l.split(".").pop()??l;i.push(Z(u,u,te(e,l,$e),r))}return i}function Fv(e,t,n){let r=ne(n,new Set(["import_header","import_list"])),i=[];for(let o of n.rootNode.descendantsOfType("import_header")){let s=o.namedChildren.find(f=>f.type==="identifier");if(!s)continue;let a=o.namedChildren.some(f=>f.type==="wildcard_import"),c=o.namedChildren.find(f=>f.type==="import_alias");if(a){i.push(fn("*",te(e,s.text,$e)));continue}let l=s.text,u=l.split(".").pop()??l,m=c?.namedChild(0)?.text??u;i.push(Z(u,m,te(e,l,$e),r))}return i}function $v(e,t,n){let r=ne(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(fn("*",te(e,c,$e)));continue}if(s?.type==="namespace_selectors"){for(let d of s.namedChildren)if(d.type==="arrow_renamed_identifier"){let[m,f]=d.namedChildren;if(!m)continue;let h=m.text,g=f?.text??h;if(h==="_")continue;i.push(Z(h,g,te(e,`${c}.${h}`,$e),r))}else if(d.type==="identifier"){let m=d.text;i.push(Z(m,m,te(e,`${c}.${m}`,$e),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;i.push(Z(l,l,te(e,u&&a.length>1?`${u}.${l}`:c,$e),r))}return i}function Av(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[dt(e,t,r,m,u,d)]})}return[dt(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Rd(e,t,n){return qe(e,t,r=>Mv(e,t,r),()=>Ve(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[dt(e,t,i,u,d,m,te(e,u.replace(/\\/g,"."),dn))]}):[]}))}function Mv(e,t,n){let r=ne(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(Z(a,c,te(e,s.replace(/\\/g,"."),dn),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}=vd(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}=vd(c,"");l&&o(d,l,u)}}return i}function vd(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 wd(e,t,n){return qe(e,t,r=>jv(e,t,r),()=>Bv(n).flatMap(r=>Vv(e,t,r,n)))}function jv(e,t,n){let r=ne(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=kd(s);if(!a)continue;let c=lr(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=Ov(s);if(a===null)continue;let c=lr(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=kd(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function kd(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 Ov(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=Ae(e,"import_prefix")?.text??"",n=Ae(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function Bv(e){let t=e.split(`
107
- `),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=zr(o);for(;i+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){i++;let m=t[i];c+=`
108
- ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,end:l})}return n}function Hv(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 Vv(e,t,n,r){let i=Ut(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(),f=(d??m.split(".")[0]??m).trim(),h=lr(e,t,m),g=dr(i,f);return[{importedName:m,localName:f,sourcePath:h,kind:"namespace",used:Te(i,f)||g.length>0,usedMembers:g}]});let s=n.module?lr(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:Te(i,m),usedMembers:[]})}return a}import{basename as qv}from"path";function Ld(e,t,n){return qe(e,t,r=>Wv(e,t,r),()=>Uv(e,t,n))}function Uv(e,t,n){return Ve(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"?fo(e,t,s):null;if(a){let c=Id(s);return[mr(c,c,a,Te(i,c))]}return[pn(s,a)]})}function Wv(e,t,n){let r=ne(n,new Set([])),i=[],o=new Set(["require","require_relative","load"]);for(let s of n.rootNode.descendantsOfType("call")){let a=s.namedChild(0);if(!a||a.type!=="identifier"||!o.has(a.text))continue;let l=s.namedChildren.find(f=>f.type==="argument_list")?.namedChild(0);if(!l||l.type!=="string")continue;let d=l.namedChildren.find(f=>f.type==="string_content")?.text;if(!d)continue;let m=a.text==="require_relative"?fo(e,t,d):null;if(m){let f=Id(d);i.push(Z(f,f,m,r))}else i.push(pn(d,m))}return i}function Id(e){return Yi(qv(e).replace(/\.[^.]+$/,""),/_/)}function Dd(e,t,n){return qe(e,t,r=>Gv(e,t,r),()=>Ve(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?zv(e,t,o,i):[]}))}function Gv(e,t,n){let r=ne(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 Jr(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=Lt(e,t,a.qualifiedName)??Lt(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push(Z(a.importedName,a.localName,c,r))}}return i}function Jr(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:So(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:So(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=So(t,n.text),o=[];for(let s of r.namedChildren)o.push(...Jr(s,i));return o}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...Jr(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=Jr(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:So(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function So(e,t){return e?t?`${e}::${t}`:e:t}function zv(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 f=m.trim();if(!f||f==="self")return[];let[h,g]=f.split(/\s+as\s+/),y=h?.trim();if(!y)return[];let S=(g??y.split("::").pop()??y).trim(),v=`${u}::${y}`.replace(/::::/g,"::");return[dt(e,t,r,v,y.split("::").pop()??y,S,Lt(e,t,u))]})}let[o,s]=i.split(/\s+as\s+/),a=o?.trim()??i,c=(s??a.split("::").pop()??a).trim(),l=Lt(e,t,a)??Lt(e,t,a.split("::").slice(0,-1).join("::"));return[dt(e,t,r,a,a.split("::").pop()??a,c,l)]}function Pd(e,t,n){let r=fe(e,t);if(r)return Jv(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(...Xv(e,t,s))}return i}function Jv(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!Kv(i))continue;let o=i.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of Jr(o,""))s.importedName&&r.push(ya(e,t,s.qualifiedName))}return r}function Kv(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function Xv(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[ya(e,t,l)]})}return[ya(e,t,r)]}function ya(e,t,n){return{specifier:n,sourcePath:Lt(e,t,n)??Lt(e,t,n.split("::").slice(0,-1).join("::"))}}function gn({language:e,extensions:t,imports:n,parseImports:r}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:r}}function Nd(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 Qv={language:"javascript",extensions:un,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:ga,parseReExports:ha},Yv=gn({language:"python",extensions:co,imports:"ast-with-regex-fallback",parseImports:wd}),Zv=gn({language:"jvm",extensions:$e,imports:"ast-dispatch-with-regex-fallback",parseImports:Cd}),eR={language:"rust",extensions:lo,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:Dd,parseExports:Pd},tR=gn({language:"ruby",extensions:uo,imports:"ast-with-regex-fallback",parseImports:Ld}),nR=gn({language:"c/cpp",extensions:mo,imports:"ast-with-regex-fallback",parseImports:gd}),rR=gn({language:"dotnet",extensions:Ht,imports:"ast-dispatch-with-regex-fallback",parseImports:bd}),iR={language:"dart",extensions:po,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:hd,parseExports:yd},oR=gn({language:"php",extensions:dn,imports:"ast-with-regex-fallback",parseImports:Rd}),sR=[Qv,Yv,Zv,eR,tR,nR,rR,iR,oR];function xo(e){return Nd(sR,e)}var ba={clearGroups:["whole-project","source-file"]},aR=U("source-imports",ba),cR=U("source-exports",ba),lR=U("source-reexports",ba);function Kr(e,t){let n=et(t);return lR.get(e,n,()=>{let r=xo(n);if(!r?.parseReExports)return[];let i=F(e,n);return i?r.parseReExports(e,n,i):[]})}function he(e,t){let n=et(t);return aR.get(e,n,()=>{let r=xo(n);if(!r)return[];let i=F(e,n);if(!i)return[];let o=Ye(e,n,i),s=md(e),a=Mt(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 jt(e,"source-imports",n,o,JSON.stringify({resolutionFingerprint:s,imports:c})),c})}function Co(e,t){let n=et(t);return cR.get(e,n,()=>{let r=xo(n);if(!r?.parseExports)return[];let i=F(e,n);return i?r.parseExports(e,n,i):[]})}var uR=U("file-dep-graph",{clearGroups:["whole-project"]});function re(e,t){return uR.get(e,t??"",()=>{let n=new Map,r=new Set(j(e,{includeIgnored:!1})),i=(o,s)=>mR(e,n,r,o,s);for(let o of dR(e,t))i(o.from_file,o.to_file);for(let o of r)if(!(t&&!o.includes(t)))for(let s of he(e,o))s.sourcePath&&i(o,s.sourcePath);return n})}function dR(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
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
114
+ gs.id,
115
+ gs.symbol,
116
+ der.document_id,
117
+ der.start_line,
118
+ der.end_line,
119
+ d.relative_path,
120
+ gs.display_name,
121
+ gs.kind,
122
+ gs.documentation,
123
+ gs.enclosing_symbol
124
+ FROM global_symbols gs
125
+ JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
126
+ JOIN documents d ON der.document_id = d.id
127
+ WHERE 1 = 1
128
+ ${e.pathExclusionsFor("d")}
129
+ ${r}
130
+ ${i}
131
+ ${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
133
+ gs.id,
134
+ gs.symbol,
135
+ c.document_id,
136
+ MIN(c.start_line) AS start_line,
137
+ MAX(c.end_line) AS end_line,
138
+ d.relative_path,
139
+ gs.display_name,
140
+ gs.kind,
141
+ gs.documentation,
142
+ gs.enclosing_symbol
143
+ FROM global_symbols gs
144
+ JOIN mentions m ON m.symbol_id = gs.id
145
+ JOIN chunks c ON m.chunk_id = c.id
146
+ JOIN documents d ON c.document_id = d.id
147
+ WHERE m.role = 1
148
+ ${e.pathExclusionsFor("d")}
149
+ ${r}
150
+ ${i}
151
+ ${e.symbolNoiseFor("gs")}
152
+ 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
109
158
  d1.relative_path AS from_file,
110
159
  d2.relative_path AS to_file
111
160
  FROM mentions m
@@ -123,11 +172,11 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
123
172
  WHERE d1.id != d2.id
124
173
  AND m.role != 1
125
174
  ${e.pathExclusionsFor("d1","d2")}
126
- ${n}`)}function mR(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 vo,readFileSync as pR,readdirSync as Td}from"fs";import{join as Xr}from"path";var fR={files:new Set,pathPrefixes:[]},Sa=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,gR=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,_d=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],hR=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),yR=4,bR=Y("package-surface",{clearGroups:["whole-project"]});function SR(e){return bR.get(e,()=>xR(e.config.projectRoot))}function gr(e,t){let n=SR(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function xR(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of CR(e))for(let o of vR(r))RR(e,i,o,t,n);return t.size===0&&n.length===0?fR:{files:t,pathPrefixes:n}}function CR(e){let t=[],n=$d(e,"");return n&&t.push({manifest:n,packageRoot:""}),Fd(e,"",t,0),t}function Fd(e,t,n,r){if(r>=yR)return;let i=Xr(e,t);if(vo(i))for(let o of Td(i,{withFileTypes:!0})){if(!o.isDirectory()||hR.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=$d(e,s);a&&n.push({manifest:a,packageRoot:s}),Fd(e,s,n,r+1)}}function $d(e,t){try{let n=pR(Xr(e,t,"package.json"),"utf-8"),r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function vR(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 Ad(e.exports,t),t}function Ad(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))Ad(n,t)}function RR(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 Ed(c))l!==""&&i.push(fr(t,l));return}let a=o.replace(gR,"");for(let c of Ed(a)){c===a&&c===o&&r.add(fr(t,o));for(let l of _d)kR(e,r,t,c+l)}r.add(fr(t,o))}function Ed(e){let t=[e];return Sa.test(e)&&(t.push(e.replace(Sa,"src/")),t.push(e.replace(Sa,""))),t}function kR(e,t,n,r){let i=fr(n,r);if(t.add(i),!r.startsWith("src/")||vo(Xr(e,i)))return;let o=_d.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);wR(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 Md(e,n,c,`${l}${o}`))t.add(u)}function wR(e,t,n,r,i){let o=fr(n,`${r}/index${i}`);vo(Xr(e,o))&&t.add(o)}function Md(e,t,n,r){let i=Xr(e,t,n);if(!vo(i))return[];let o=[];for(let s of Td(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...Md(e,t,a,r)):s.isFile()&&s.name===r&&o.push(fr(t,a))}return o}function fr(e,t){return e?`${e}/${t}`:t}function J(e){let t=hr(e);return BR(t)?"test":HR(t)?"worker":VR(t)?"entry":qR(t)?"barrel":"source"}function Ro(e){return J(e)==="barrel"}function Od(e){return LR.get(e,()=>{let t=re(e),n=Ie(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 LR=Y("live-barrels",{clearGroups:["whole-project"]});function xa(e,t){return Od(e).has(hr(t))}function Bd(e){let t=Od(e);return Ie(e).filter(n=>Ro(n)&&!t.has(n)&&!IR(e,n))}function IR(e,t){let n=hr(t),r=ae(e,n)?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
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
127
176
  FROM defn_enclosing_ranges der
128
177
  JOIN documents d ON d.id = der.document_id
129
178
  WHERE d.relative_path = ?
130
- AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function De(e,t){let n=J(t);return n==="entry"||n==="worker"||xa(e,t)}function ie(e,t,n){let r=hr(n);if(gr(e,r)||_R(t,r))return!0;let i=e.config.entryRoots;return i?!!(i.files?.some(o=>hr(o)===r)||i.pathPrefixes?.some(o=>r.startsWith(hr(o)))||i.qualifiedVars?.some(o=>UR(t,o))||i.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}var Hd=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),DR=new Set(["default","generateMetadata","generateStaticParams"]),PR=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),NR=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),ER=new Set(["load","actions","entries",...Hd]),TR=new Set(["default"]);function _R(e,t){let n=A(e);return n===""?!1:FR(t)?Hd.has(n):$R(t)?DR.has(n):AR(t)?PR.has(n):MR(t)?NR.has(n):jR(t)?ER.has(n):OR(t)?TR.has(n):!1}function FR(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function $R(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function AR(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function MR(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function jR(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function OR(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function BR(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 HR(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function VR(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 qR(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 hr(e){return e.replace(/\\/g,"/")}function UR(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(jd(r)+"/")&&e.includes(jd(i)+".")}function jd(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function ko(e,t,n,r={}){if(!n)return[];let i=F(e,t);return i?i.indexOf(n)===-1?[]:(It(e,t).get(n)??[]).filter(s=>!WR(s,r)):[]}function WR(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var GR=U("file-identifiers",{clearGroups:["whole-project","source-file"]});function Vd(e,t){let n=ae(e,t);return n?n.fileIdentifiers:GR.get(e,t,()=>new Set(It(e,t).keys()))}var zR=U("file-ident-lines",{clearGroups:["whole-project","source-file"]});function It(e,t){let n=ae(e,t);return n?n.identifierLineMap:zR.get(e,t,()=>KR(e,t))}var JR=U("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function qd(e,t){let n=ae(e,t);return n?n.identifiersByLine:JR.get(e,t,()=>{let r=It(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 KR(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=F(e,t);if(!i)return n;let o=mn(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 Ud(e,t){return Ca(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
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
131
180
  m.symbol_id,
132
181
  d.relative_path,
133
182
  COUNT(*) AS ref_count
@@ -137,13 +186,13 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
137
186
  WHERE m.role != 1
138
187
  ${r}
139
188
  ${e.pathExclusionsFor("d")}
140
- GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function Wd(e,t){return Ca(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
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
141
190
  FROM mentions m
142
191
  JOIN chunks c ON m.chunk_id = c.id
143
192
  JOIN documents d ON c.document_id = d.id
144
193
  WHERE m.role != 1
145
194
  ${r}
146
- ${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function wo(e,t){return Ca(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,
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,
147
196
  c.start_line AS chunk_start, c.end_line AS chunk_end
148
197
  FROM mentions m
149
198
  JOIN chunks c ON m.chunk_id = c.id
@@ -151,7 +200,7 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
151
200
  WHERE m.role != 1
152
201
  ${r}
153
202
  ${e.pathExclusionsFor("d")}
154
- ORDER BY d.relative_path, c.start_line`,...n??[])})}function Ca(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 Gd(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Wt(e,t){return Gd(e)===Gd(t)}function Lo(e,t){let n=zd(e);return n?t.filter(r=>zd(r.file)===n):t}function Io(e,t,n,r){let i=n.find(o=>o.file===t);if(i)return i;if(r){let o=new Set(he(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(Wt(a,s.file))return s;return null}return n.length===1?n[0]:null}function zd(e){let t=W(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var XR=Y("global-leaf-index",{clearGroups:["whole-project"]});function hn(e){return XR.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
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,
155
204
  COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
156
205
  FROM global_symbols gs
157
206
  LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
@@ -165,8 +214,8 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
165
214
  GROUP BY m.symbol_id
166
215
  ) mention_doc ON mention_doc.symbol_id = gs.id
167
216
  WHERE 1 = 1
168
- ${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=A(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 Jd=/[A-Za-z_$][A-Za-z0-9_$]*/g,QR=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function Do(e,t){if(t.size===0)return!0;let n=[],r=!1;for(let o of t)o&&(r=!0,QR.test(o)||n.push(o));if(!r)return!0;Jd.lastIndex=0;let i;for(;(i=Jd.exec(e))!==null;)if(t.has(i[0]))return!0;for(let o of n)if(e.includes(o))return!0;return!1}function nt(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import Kd from"path";function YR(e,t){return e.getReferences().map(n=>{let r=n.getNode();return Yd(r,t)})}function ZR(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function Xd(e,t,n,r){let i=[];for(let o of ZR(e))for(let s of YR(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 Po(i)}function Qd(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();Qr(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:Yd(a,r),node:a}))}return i}function Yd(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:Qr(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function Zd(e,t,n){let r=e.getSourceFile(),i=yr(r,e),o=e.getText(),s=new RegExp(`\\b${ek(o)}\\b`,"g"),a=r.getFullText().split(`
169
- `),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 Po(c.filter(l=>Qr(n,Kd.join(n,l.file))===t))}function va(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 yr(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Po(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 Qr(e,t){let n=Kd.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function ek(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function em(e,t,n,r){let i=tk(t,r);return i.size===0?new Map:nk(e,n,i)}function tk(e,t){let n=new Map;for(let r of G(e,t)){let i=A(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function nk(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of rk(e,o)){let a=n.get(s);if(!a)continue;let c=yr(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 rk(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 ik=U("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function nm(e,t,n,r){let i=im(e,t),o=tm(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||A(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return tm(s,n)}function rm(e,t){let n=new Map;for(let[r,i]of im(e,t)){let o=i[0];o&&n.set(r,o)}return n}function im(e,t){return ik.get(e,t,()=>{let n=new Map;for(let r of G(e,t)){let i=r.leaf||A(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 tm(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 ok from"path";var Yr=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function yn(e){let t=e.toLowerCase();return Yr.some(n=>t.endsWith(n))}function om(e,t){let n=new Map,r=i=>yn(i)?nt(n,i,()=>{let o=ok.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:()=>j(e,{extensions:Yr})}}import Gt from"path";import{existsSync as No,readdirSync as sk,readFileSync as sm}from"fs";function am(e){let t=Gt.join(e,"package.json");if(!No(t))return[];let n;try{n=JSON.parse(sm(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>ak(e,i)).flatMap(i=>ck(e,i))}function ak(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=Gt.join(e,t);return No(Gt.join(s,"package.json"))?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=Gt.join(e,r||".");if(!No(o))return[];try{return sk(o).map(s=>Gt.join(o,s,i)).filter(s=>No(Gt.join(s,"package.json")))}catch{return[]}}function ck(e,t){try{let n=JSON.parse(sm(Gt.join(t,"package.json"),"utf8"));if(!n.name)return[];let r=Gt.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:r,sourceRootRelative:`${r}/src`}]}catch{return[]}}function cm(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function lm(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as Zr,readFileSync as lk,readdirSync as uk,statSync as dk}from"fs";import oe from"path";var ka=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function wa(e,t){let r=t?oe.dirname(oe.join(e,t)):e,i=oe.resolve(e);for(;r.startsWith(i);){for(let s of ka){let a=oe.join(r,s);if(Zr(a))return a}let o=oe.dirname(r);if(o===r)break;r=o}for(let o of ka){let s=oe.join(e,o);if(Zr(s))return s}return null}function um(e){let t=e.config.projectRoot,n=new Set(La(t,e.config.semantic?.typescript?.tsconfigs)),r=j(e,{includeIgnored:!1,extensions:Yr});for(let i of r){let o=wa(t,i);o&&n.add(oe.resolve(o))}if(n.size===0){let i=wa(t);i&&n.add(oe.resolve(i))}return[...n].filter(i=>!dm(t,i)).sort((i,o)=>i.localeCompare(o))}function La(e,t=[]){let n=new Set;for(let r of t){let i=oe.isAbsolute(r)?r:oe.join(e,r);Zr(i)&&n.add(oe.resolve(i))}for(let r of mk(e))for(let i of ka){let o=oe.join(r,i);Zr(o)&&n.add(oe.resolve(o))}if(n.size===0){let r=wa(e);r&&n.add(oe.resolve(r))}return[...n].filter(r=>!dm(e,r)).sort((r,i)=>r.localeCompare(i))}function mk(e){let t=oe.join(e,"package.json");if(!Zr(t))return[];let n;try{n=JSON.parse(lk(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>pk(e,i))}function pk(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=oe.join(e,t);return Ra(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=oe.join(e,r||".");return Ra(o)?uk(o).map(s=>oe.join(o,s,i)).filter(Ra):[]}function Ra(e){try{return dk(e).isDirectory()}catch{return!1}}function dm(e,t){let n=oe.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 fk}from"module";var gk=fk(import.meta.url),ei;function mm(){if(ei!==void 0)return ei;try{ei=gk("ts-morph")}catch{ei=null}return ei}function pm(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!1})}))}function Eo(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function hm(e,t){let n=mm();if(!n)return Eo("ts-morph is not installed");let r=um(e);if(r.length===0)return Eo("no tsconfig found");try{let i=pm(n,r);return new Ia(e,n,i)}catch(i){return Eo(i instanceof Error?i.message:String(i),r[0],r)}}var Ia=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=am(t.config.projectRoot),this.sourceFiles=om(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 nt(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 nt(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),r=this.packageImportReferencesForDefinition(t);return n?Xd(n,t,r,this.db.config.projectRoot):r})}calleesFor(t){return nt(this.calleesCache,t.symbolId,()=>nt(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return nt(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 gm(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${gm(o)}`})}importUsageForDeclaration(t,n){let r=tt(this.db,t,n.getModuleSpecifierValue()),i=fm(n);return n.getImportClause()?.isTypeOnly()?i.map(o=>hk(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 Qd(l,t,r.identifier,this.db.config.projectRoot))o.push(u);let s=o.some(l=>!va(l.node)),a=o.some(l=>va(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,Po(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=cm(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of fm(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=Zd(a.identifier,r,this.db.config.projectRoot);l.length>0&&Sk(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 lm(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?tt(this.db,n,a):n;if(!c||!c.startsWith(`${t.sourceRootRelative}/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,c,r,i);continue}for(let u of l){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,f=this.indexedDefinitionByLeaf(c,d);if(!f)continue;let h=r.get(m);h||(h=new Set,r.set(m,h)),h.add(f.symbolId)}}}indexedDefinitionByLeaf(t,n){return nt(this.indexedDefinitionLeafCache,t,()=>rm(this.db,t)).get(n)??null}nodeForDefinition(t){return nt(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return nt(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?em(this.tsMorph,this.db,n,t):new Map})}definitionFromSymbol(t){let n=t.getDeclarations();for(let r of n){let i=r.getSourceFile(),o=Qr(this.db.config.projectRoot,i.getFilePath());if(!o||this.db.isIgnored(o))continue;let s=yr(i,r),a=nm(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&&yk(i,s.callerId,s.target)});for(let[o,s]of i)i.set(o,xk(s));return i}semanticCalleeForCallNode(t,n,r){let i=bk(n,yr(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 fm(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 hk(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 yk(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function bk(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 Sk(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function xk(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 gm(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Da=new WeakMap;At({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>Da.delete(e)});function zt(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,r=Da.get(e);r||(r=new Map,Da.set(e,r));let i=r.get(n);if(i)return i;let o=hm(e,t);return r.set(n,o),o}function ti(e,t){let n=_o(e,t);return n?n.importUsage(t):[]}function Jt(e,t){let n=_o(e,t.relativePath);return n?n.referencesFor(t):[]}function mt(e,t){let n=new Map,r=pu(e),i=[];for(let o of t){let s=Ck(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&&zt(e).availability().available&&yu(e,i),n}function Ck(e,t,n,r){if(!n||!yn(t.relativePath))return Jt(e,t);let i=gu(e,t.relativePath,t.symbol,n);if(i!==null){let s=vk(i);if(s)return s}let o=Jt(e,t);return r.push({relativePath:t.relativePath,symbol:t.symbol,projectFingerprint:n,payload:JSON.stringify(o)}),o}function vk(e){try{return JSON.parse(e)}catch{return null}}function To(e,t){let n=new Map;for(let r of t){let i=_o(e,r.relativePath);if(!i)continue;let o=i.calleesFor(r);o.length>0&&n.set(r.symbolId,o)}return n}function ym(e,t){let n=_o(e,t.relativePath);return n?n.signatureFor(t):null}function _o(e,t){if(!yn(t))return null;let n=zt(e,t);return n.availability().available?n:null}function Fo(e,t){let n=new Map;for(let r of he(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i&&bm(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)bm(n,o,r.sourcePath)}return n}function bm(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function br(e,t,n){let r=hn(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[ni(r[0])];let i=r.filter(c=>c.file===t);if(i.length>0)return i.map(ni);let o=Fo(e,t),s=o.get(n);if(s)for(let c of s){let l=r.filter(u=>Wt(c,u.file));if(l.length>0)return l.map(ni)}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=>Wt(c,u.file));if(l.length>0&&l.length===r.length)return l.map(ni)}return[]}function xm(e,t,n){let r=br(e,t,n);if(r.length>0)return r;let i=hn(e).get(n);return!i||i.length===0?[]:i.map(ni)}function Cm(e,t,n={}){let r=so(e,t);if(!r)return[];let i=A(r.symbol);if(!i)return[];if(n.semantic!==!1){let s=Jt(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 Sm(e,a)}}let o=new Map;for(let s of Ie(e)){let a=F(e,s);if(!a||a.indexOf(i)===-1||s!==r.relativePath&&!br(e,s,i).some(u=>u.symbolId===r.symbolId))continue;let c=ko(e,s,i,s===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});c.length>0&&o.set(s,c)}return Sm(e,o)}function vm(e,t){let n=new Map;for(let s of t){if(!s.leaf)continue;let a=n.get(s.leaf)??[];a.push(s),n.set(s.leaf,a)}if(n.size===0)return new Map;let r=new Set(t.map(s=>s.symbolId)),i=new Set(n.keys()),o=new Map;for(let s of Ie(e)){if(!Do(F(e,s),i))continue;let a=Vd(e,s);if(a.size!==0){for(let c of a)if(n.has(c))for(let l of br(e,s,c)){if(!r.has(l.symbolId)||s===l.relativePath)continue;let u=o.get(l.symbolId);u||(u=new Set,o.set(l.symbolId,u)),u.add(s)}}}return o}function ni(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function Sm(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=Be(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 bn(e,t){let n=Dk(e,t);return n?Pk(e,kk(e,n.match,n.identifier)):[]}function Kt(e,t,n={}){return Rk(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function Rk(e,t,n={}){let r=Cm(e,t,{semantic:n.semantic}),i=r.length>0?Rm(r,"source-attribution"):Rm(bn(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function Rm(e,t){return e.map(n=>({...n,provenance:t}))}function kk(e,t,n){let r=new Map;for(let[i,o]of wk(e,t.symbolId))r.set(i,Lk(e,i,o,t,n));return r}function wk(e,t){let n=new Map;for(let r of wo(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 Lk(e,t,n,r,i){let o=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},s=i?ko(e,t,i,o):[];return n.flatMap(a=>Ik(s,a))}function Ik(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function Dk(e,t){let n=so(e,t);return n?{match:n,identifier:A(n.symbol)||null}:null}function Pk(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=Be(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 Me(e,t,n={}){let r=$o(e,[t],{additive:n.additive,semantic:n.semantic}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>Ce(o.symbol)):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function wm(e,t,n={}){let r=Tk(e)?Fk(e,t,{semantic:n.semantic!==!1}):_k(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var Nk=Y("caller-rows",{clearGroups:["whole-project"]}),Ek=2e4;function Tk(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>Ek}function _k(e){return Nk.get(e,()=>{let t=ut(e),n=$o(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 Fk(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 bn(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?$k(e,t):null;if(s)for(let a of Jt(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=Be(G(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return r}function $k(e,t){return e.get(`SELECT
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
170
219
  d.id AS documentId,
171
220
  gs.id AS symbolId,
172
221
  gs.symbol,
@@ -185,11 +234,11 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
185
234
  LEFT JOIN chunks c ON c.document_id = der.document_id
186
235
  JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
187
236
  WHERE gs.id = ?
188
- LIMIT 1`,t.symbolId)??null}function $o(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)&&Qn(e,u.relativePath)!==null?i.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[d,m]of u){let f=s.get(d);f||(f=[],s.set(d,f));let h=a.get(d);h||(h=new Set,a.set(d,h));for(let g of m){let y=`${g.symbol}|${g.chunkId}`;h.has(y)||(h.add(y),f.push(g))}}};i.length>0&&c(Bk(e,i)),n.semantic!==!1&&c(Uk(Ak(e,t)));let l=r?t:o;return l.length>0&&c(qk(e,l)),s}function Ak(e,t){let n=new Map,r=[],i=[];for(let s of t){if(!yn(s.relativePath))continue;let a=F(e,s.relativePath);if(!a){i.push(s);continue}let c=Ye(e,s.relativePath,a),l=Ok(e,s.relativePath),u=fu(e,s.relativePath,s.symbol,c,l);if(u!==null){let d=Mk(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=To(e,[...i,...r.map(s=>s.def)]);for(let[s,a]of o)n.set(s,a);return zt(e).availability().available&&hu(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 Mk(e){try{return JSON.parse(e)}catch{return null}}var jk=U("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function Ok(e,t){return jk.get(e,t,()=>{let r=[...re(e).get(t)??[]].sort().map(i=>`${i}:${Ye(e,i,F(e,i))}`);return Jn(r.join("|"))})}function Bk(e,t){let n=new Map,r=Hk(t,n),i=hn(e);for(let[o,s]of r){let a=Qn(e,o);if(!a)continue;let c=sa(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=Vk(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 Hk(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 Vk(e,t,n,r,i){let o=Lo(t,n.get(r)??[]);return o.length===0?null:Io(e,t,o,i)}function qk(e,t){if(t.length===0)return new Map;let r=Pa(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
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
189
238
  FROM mentions m
190
239
  JOIN chunks c ON m.chunk_id = c.id
191
240
  WHERE m.role != 1
192
- 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=Pa(r.map(m=>m.symbol_id)).flatMap(m=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
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,
193
242
  COALESCE(der.document_id, def_chunk.document_id) AS document_id
194
243
  FROM global_symbols gs
195
244
  LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
@@ -201,11 +250,11 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
201
250
  AND m.symbol_id IN (${m.map(()=>"?").join(",")})
202
251
  GROUP BY m.symbol_id
203
252
  ) def_chunk ON def_chunk.symbol_id = gs.id
204
- WHERE gs.id IN (${m.map(()=>"?").join(",")})`,...m,...m)),a=Pa([...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
205
- WHERE id IN (${m.map(()=>"?").join(",")})`,...m).map(f=>[f.id,f.relative_path]))),l=new Map;for(let m of s)l.has(m.symbol_id)||l.set(m.symbol_id,{symbol:m.symbol,file:m.document_id!==null?c.get(m.document_id)??"":""});let u=new Map,d=c;for(let m of t){let f=i.get(m.documentId)??[],h=new Set,g=[],y=null,S=()=>{if(y)return y;let v=d.get(m.documentId)??"",k=new Set;if(v){let N=qd(e,v),w=Math.max(0,m.startLine),R=Math.min(N.length-1,m.endLine);for(let $=w;$<=R;$+=1)for(let I of N[$])k.add(I)}return y=k,k};for(let v of f){if(v.symbol_id===m.symbolId)continue;let k=l.get(v.symbol_id);if(!k)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 $=A(k.symbol);if(!$||!S().has($))continue}let w=`${k.symbol}|${v.chunk_id}`;h.has(w)||(h.add(w),g.push({...k,chunkId:v.chunk_id,source:"scip-chunk"}))}u.set(m.symbolId,g)}return u}var km=500;function Pa(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=km)n.push(t.slice(r,r+km));return n}function Uk(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 Lm(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=j(e,{includeIgnored:!1}),o=hn(e),s=t??ut(e),a=new Set(s.map(c=>c.symbolId));return Wk(e,r,i,o,a),Gk(e,r,s,a),Xk(e,r,i,o,a),n.semantic!==!1&&Yk(r,mt(e,Qk(s))),r}function Wk(e,t,n,r,i){for(let o of n){if(!W(o))continue;let s=Qn(e,o);if(s)for(let a of s){let c=Lo(o,r.get(a.calleeLeaf)??[]);if(!c||c.length===0)continue;let l=Io(e,o,c,a.memberAccess);l&&i.has(l.symbolId)&&l.file!==o&&Na(t,l.symbolId,o)}}}function Gk(e,t,n,r){let i=Jk(n);for(let o of zk(e,r))e.isIgnored(o.relative_path)||Kk(o,i.get(o.symbol_id))||Na(t,o.symbol_id,o.relative_path)}function zk(e,t){return wo(e,t?[...t]:void 0)}function Jk(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 Kk(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function Xk(e,t,n,r,i){for(let o of n){if(W(o)!=="rust")continue;let s=sn(e,o,{includeRustAttributeNames:!0});if(s.length!==0)for(let{name:a}of s){let c=r.get(a);if(c)for(let l of c)i.has(l.symbolId)&&l.file!==o&&Na(t,l.symbolId,o)}}}function Na(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Qk(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function Yk(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 Ue(e,t,n={}){return wm(e,t,n)}function Ea(e,t,n={}){return Lm(e,t,n)}function Ta(e,t){return vm(e,t)}function Im(e,t,n={}){let r=Ea(e,t,{semantic:n.semantic});return n.sourceFallback===!1?r:Ao(r,Ta(e,t))}function Ao(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 Dm(e,t,n){let r=t.identifierResolution==="strict"?br:xm;for(let i of t.paths)if(!(!W(i)&&!(t.includeVueSfc&&Rt(i)))&&!e.isIgnored(i)&&!t.skipPath?.(i))try{if(t.candidateNames&&!Do(F(e,i),t.candidateNames))continue;let s=(c,l,u,d)=>{if(t.candidateNames&&!t.candidateNames.has(c))return;let m=t.resolveTargets?t.resolveTargets({sourceFile:i,name:c,kind:l,defaultTargets:d}):d();for(let f of m)n({sourceFile:i,name:c,target:f,occurrences:u,kind:l})},a=It(e,i);for(let[c,l]of a)s(c,"identifier",l.length,()=>r(e,i,c));for(let c of sn(e,i,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let l=c.kind==="cross-language-dispatch"?()=>br(e,i,c.name):()=>r(e,i,c.name);s(c.name,c.kind,c.occurrences,l)}}finally{t.afterPath?.(i)}}function q(e){return e.endLine-e.startLine+1}function Pm(e,t={}){let{scope:n,minLoc:r=1,maxLoc:i=Number.POSITIVE_INFINITY,excludeSymbol:o,excludeEntrySurfaces:s=!1,excludeTypesFiles:a=!1,excludeRootedSymbols:c=!1,requireFunctionLikeSymbol:l=!1,requireCallableSymbol:u=!1,excludeRustTraitImplMembers:d=!1,includeSuppressed:m=!1,sortByLocDesc:f=!1}=t,h=[];for(let g of Ur(e,n)){let y=g.relativePath;if(e.isIgnored(y)||s&&De(e,y)||!Zk(g,{requireFunctionLikeSymbol:l,requireCallableSymbol:u})||o!==void 0&&g.symbol===o)continue;let S=q(g);S<r||S>i||a&&ew(y)||c&&ie(e,g.symbol,y)||d&&no(g.symbol)||J(y)!=="test"&&(nr(g.symbol)||!m&&Gi(e,y,g.startLine)||h.push(g))}return f?h.sort((g,y)=>q(y)-q(g)):h}function Zk(e,t){return t.requireCallableSymbol?Ce(e.symbol):t.requireFunctionLikeSymbol?ce(e.symbol):e.isFunctionLike}function ew(e){return(e.split("/").pop()??"").includes("types")}var T=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Ur(this.db,t)}definitionsForFile(t){return G(this.db,t)}productionCallableDefinitions(t={}){return Pm(this.db,t)}calleeMap(t,n={}){return $o(this.db,t,n)}crossFileCallerMap(t,n={}){return Ea(this.db,t,n)}sourceFallbackCallerFiles(t){return Ta(this.db,t)}callerFileMap(t,n={}){return Im(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 j(this.db,{includeIgnored:!1}))if(W(i)==="rust")for(let{name:o}of sn(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 re(this.db,t)}fileKind(t){return J(t)}hasSuppressionComment(t){return Gi(this.db,t.relativePath,t.startLine)}sourceFiles(){return Ie(this.db)}scanSourceReferences(t,n){Dm(this.db,t,n)}callableSignature(t){let n=ae(this.db,t.relativePath)?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};function _a(e,t){let n=B(e,t);if(!n)return[];let r=A(n.symbol),o=new T(e).definitionsForFile(n.relativePath).filter(c=>Ce(c.symbol)),s=o.filter(c=>c.parentTypeName===r||c.symbol.includes(r));return(s.length>0?s:nw(tw(n.relativePath))===r?o.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:A(c.symbol)}))}function nw(e){return e.replace(/\.[^.]+$/,"")}function Fa(e,t,n={}){let r=B(e,t);if(!r)return[];let o=!ce(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=Kt(e,r,{semantic:n.semantic}).map(u=>({relativePath:u.file,line:u.line})),a=rw(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 rw(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=iw(t.symbol);if(n.length===0)return[];let r=[];for(let i of j(e,{extensions:[".rb"],includeIgnored:!1})){let o=F(e,i);if(!o)continue;let s=o.split(`
206
- `);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 iw(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 ri(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=cn(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:sw(o,i?.display_name??null,r.symbol),source:ow(e,r.relativePath,r.startLine,r.endLine)}],a=Kt(e,r,{semantic:n.semantic}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?b(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function ow(e,t,n,r){let i=F(e,t);if(!i)return null;let s=i.split(`
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(`
207
256
  `).slice(n,r+1).join(`
208
- `).trimEnd();return s.length>0?s:null}function sw(e,t,n){let r=an(e);if(r&&!aw(r))return r;let i=(t??"").trim();return i?ce(n)&&!i.endsWith("()")?`${i}()`:i:b(n)}function aw(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function ii(e,t){let n=Ee(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
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
209
258
  FROM mentions m
210
259
  JOIN chunks c ON m.chunk_id = c.id
211
260
  JOIN documents d1 ON c.document_id = d1.id
@@ -221,7 +270,7 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
221
270
  WHERE d1.relative_path = ?
222
271
  AND d2.relative_path <> d1.relative_path
223
272
  AND ${e.localSymbolPredicate}
224
- ORDER BY d2.relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function oi(e,t){let n=Ee(e,t);return n?e.all(`SELECT DISTINCT d1.relative_path
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
225
274
  FROM mentions m
226
275
  JOIN chunks c ON m.chunk_id = c.id
227
276
  JOIN documents d1 ON c.document_id = d1.id
@@ -236,9 +285,9 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
236
285
  JOIN documents d2 ON sym_def.document_id = d2.id
237
286
  WHERE d2.relative_path = ?
238
287
  AND d1.relative_path != ?
239
- ORDER BY d1.relative_path`,n,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function si(e,t){let n=cr(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
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
240
289
  WHERE relative_path IN (${r})
241
- ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),s=ro(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:d,...m})=>m),c=e.all(`SELECT DISTINCT d2.relative_path
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
242
291
  FROM mentions m
243
292
  JOIN chunks c ON m.chunk_id = c.id
244
293
  JOIN documents d1 ON c.document_id = d1.id
@@ -269,7 +318,7 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
269
318
  JOIN documents d2 ON sym_def.document_id = d2.id
270
319
  WHERE d2.relative_path IN (${r})
271
320
  AND d1.relative_path NOT IN (${r})
272
- 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 ai(e,t){let n=cr(e,t);return n.length===0?[]:uw([...cw(e,n),...lw(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(dw)}function cw(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
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
273
322
  FROM mentions m
274
323
  JOIN chunks c ON m.chunk_id = c.id
275
324
  JOIN documents d1 ON c.document_id = d1.id
@@ -296,7 +345,7 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
296
345
  AND m.role != 1
297
346
  AND ${e.localSymbolPredicate}
298
347
  ${e.pathExclusionsFor("d1")}
299
- ORDER BY d1.relative_path`,...t,...t,...t)}function lw(e,t){let n=new T(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>Ce(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function uw(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 dw(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:b(e.symbol)}}var ci=new WeakMap;function Em(e,t){let n=W(t);return n==="rust"?Sw(e,t):n==="typescript"||n==="tsx"||n==="javascript"?gw(e,t):[]}var mw=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),pw=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,fw=/\buse[A-Z][A-Za-z0-9_$]*/;function gw(e,t){let n=F(e,t);if(!n||!hw(n))return[];let r=fe(e,t);if(!r)return[];let i=ci.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&&mw.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,f=d.namedChild(1);m&&(f?.type==="arrow_function"||f?.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(...Tm(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),ci.set(r,a),a}function hw(e){return e.includes("scip-query")||pw.test(e)||fw.test(e)}var yw=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function bw(e){return yw.test(e)}function Tm(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(bw(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 Sw(e,t){let n=fe(e,t);if(!n)return[];let r=ci.get(n);if(r)return r;let i=[],o=xw(n);return o?(ci.set(n,o),o):(_m(n.rootNode,i,!1,!1),i.push(...Tm(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(...Dw(n.rootNode)),ci.set(n,i),i)}function xw(e){return Pw(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function _m(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"?Cw(e,t,n,r):r&&Iw(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"?vw(e,t,n):e.type==="mod_item"&&$a(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)_m(s,t,i,o)}function Cw(e,t,n,r){let i=$a(e),o=null;r?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of i){let a=kw(s);if(a){o=a;break}if(Fm(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function vw(e,t,n){let r=$a(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(Lw)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:i}),r.some(Fm)&&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 $a(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 Rw=[{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 kw(e){return Rw.find(({re:t})=>t.test(e))?.reason??null}var ww=[/\bSerialize\b/,/\bDeserialize\b/,/\bFromRow\b/,/\bsqlx::FromRow\b/,/\bDeriveEntityModel\b/,/\bIntoSchema\b/,/\bToSchema\b/,/\bDeriveValueType\b/,/\bError\b/,/\bthiserror::Error\b/];function Lw(e){return/#\[\s*derive\s*\(/.test(e)?ww.some(t=>t.test(e)):!1}function Fm(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function Iw(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function Dw(e){let t=Ew(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 Pw(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 Nw=/^#!?\[\s*serde\s*\(/,Nm=/\bwith\s*=\s*"([^"]+)"/g;function Ew(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!Nw.test(n.text))continue;Nm.lastIndex=0;let r;for(;(r=Nm.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function $m(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=Em(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 oo(o))if(a.containers.has(c))return!0;return!1}}function Aa(e,t={}){Ks(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function Ma(e,t,n={}){Ks(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function Mm(e,t){return t.isIgnoredPath(e.relativePath)?pt("ignored-file"):Ot(e.symbol)?pt("module-like-symbol"):Am(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&Am(e.enclosingSymbol)?pt("nested-non-callable-value"):!t.includeTests&&!ja(e.relativePath)?pt("test-file"):!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName)?pt("excluded-file-region"):no(e.symbol)?pt("rust-trait-impl-member"):nr(e.symbol)?pt("rust-test-module"):!t.includeMembers&&!Tw(e)?pt("member"):e.endLine-e.startLine+1<t.minLoc?pt("below-min-loc"):{accepted:!0}:pt("non-value-symbol")}function ja(e){return J(e)!=="test"}function pt(e){return{accepted:!1,rejectionReason:e}}function Am(e){return ce(e)||e.endsWith("().")||e.endsWith(".")}function Tw(e){return Ce(e.symbol)||oo(e.symbol).length===0}function Mo(e,t){return q(e)-q(t)||e.relativePath.localeCompare(t.relativePath)}function We(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Sr(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 jm(){return new Map}function Om(e,t,n){let r=new Map;for(let i of Ud(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||jo(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function Bm(e,t,n){let r=new Set;for(let i of Wd(e,t))e.isIgnored(i.relative_path)||n.has(i.relative_path)||r.add(i.symbol_id);return r}function Oa(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 Ba(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 Hm(e){return e?.occurrences??0}function jo(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=qm(e,t,n);o.occurrences+=r,o.sources.add(i)}function Vm(e,t,n,r,i){if(r<=0)return;let o=qm(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function qm(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 _w=3e3,Fw=1e3;function Dt(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=We($w(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c),d=o?new Set(Bd(e)):new Set,m=a?jm():Om(e,d,u.map(S=>S.symbolId)),f=a?Bm(e,u.map(S=>S.symbolId),d):new Set,h=a?u.filter(S=>!f.has(S.symbolId)):u.filter(S=>!Ba(m,S.symbolId,S.relativePath));a?Bw(e,h,m,d):Ow(e,h,m,d);let g=a?h.filter(S=>!Oa(m,S.symbolId)):h.filter(S=>!Ba(m,S.symbolId,S.relativePath));Ww(e,g,m,{includeTests:i,inactiveBarrelPaths:d,includeSemantic:!a&&l});let y=a?h.filter(S=>!Oa(m,S.symbolId)):u;return jw(e,Aw(y,m))}function $w(e,t){let n=$m(e),r=[];for(let i of j(e,{scope:t.scope}))try{for(let o of G(e,i))Mm(o,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:a=>e.isIgnored(a),isExcludedRegion:n}).accepted&&r.push(o)}finally{Ma(e,i,{definitions:!0})}return r}function Aw(e,t){return e.map(n=>Mw(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 Mw(e,t){let n=t.get(e.symbolId)??new Map,r=Hm(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 jw(e,t){let n=[],r=0,i=0,o=0;for(let s of t){if(e.isIgnored(s.relative_path)||De(e,s.relative_path)||ie(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 Ow(e,t,n,r){if(t.length===0)return;let i=new T(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 j(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)&&(qw(e,c)||jo(n,c.target.symbolId,c.sourceFile,Uw(c),"source-fallback"))})}function Bw(e,t,n,r){if(t.length===0)return;let i=new T(e),o=Hw(t),s=new Set(i.sourceFiles());for(let u of j(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=Fo(e,u),c.set(u,d)),d};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let f=o.get(d);return f?Vw(u,d,f,l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),Ma(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&Um(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||jo(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function Hw(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 Vw(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=>Wt(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=>Wt(c,u.relativePath));if(l.length>0&&l.length===n.length)return l}return i.permissive?[...n]:[]}function qw(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&Um(e,t)}function Uw(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function Um(e,t){return t.occurrences>1?!1:he(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function Ww(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=_w&&j(e).length>=Fw,s=(c,l)=>{l===c.relativePath||e.isIgnored(l)||r.inactiveBarrelPaths.has(l)||!r.includeTests&&!ja(l)||Vm(n,c.symbolId,l,1,"caller-map")};for(let c of t){let l=Ue(e,c,{semantic:i&&!o});if(l.length!==0)for(let u of l)s(c,u.file)}if(!o)return;let a=mt(e,t);for(let c of t){let l=a.get(c.symbolId);if(l)for(let u of l)s(c,u)}}function Ha(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"",s=e.all(`SELECT
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
300
349
  gs.symbol,
301
350
  COUNT(*) AS ref_count,
302
351
  COUNT(DISTINCT ref_d.id) AS file_count,
@@ -319,14 +368,14 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
319
368
  ${i}
320
369
  GROUP BY gs.id
321
370
  ORDER BY ref_count DESC
322
- 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:Gw(e,r,n)}function Gw(e,t,n){return ut(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>zw(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function zw(e,t){let n=Ue(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 Va(e,t,n={}){return Gm(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function qa(e,t){let n=Jw(e,t);return n.length>0?n:Kw(e,t)}function Ua(e,t,n={}){return Gm(e,t,n)?.filter(r=>!r.used).map(r=>({symbol:r.symbol,shortName:r.shortName,importedIn:r.importer}))??[]}function Jw(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
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
323
372
  FROM mentions m
324
373
  JOIN chunks c ON m.chunk_id = c.id
325
374
  JOIN documents d ON c.document_id = d.id
326
375
  JOIN global_symbols gs ON m.symbol_id = gs.id
327
376
  WHERE gs.symbol LIKE ?
328
377
  AND m.role = 2
329
- 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 Kw(e,t){let n=B(e,t),r=n?.relativePath??null,i=n?A(n.symbol):t.replace(/\(\)$/,""),o=n?Ot(n.symbol):!1,s=new Set;for(let a of j(e,{includeIgnored:!1}))for(let c of he(e,a))Xw(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 Xw(e,t,n){return!e.sourcePath||n.targetFile&&Wm(e.sourcePath)!==Wm(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&eL(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function Gm(e,t,n={}){let r=Ee(e,t);return r?Qw(e,r,n)??(n.semantic===!1?null:Yw(e,r))??Zw(e,r):null}function Qw(e,t,n){let i=e.all(`SELECT DISTINCT
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
330
379
  gs.symbol,
331
380
  def_d.relative_path AS from_file,
332
381
  imp_d.relative_path AS importer,
@@ -352,11 +401,11 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
352
401
  LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
353
402
  WHERE imp_d.relative_path = ?
354
403
  AND m.role = 2
355
- ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:ti(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 Yw(e,t){let n=ti(e,t);return n.length>0?n.map(r=>{let i=zm(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 Zw(e,t){return he(e,t).map(n=>{let r=zm(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 zm(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 Wm(e){return e.replace(/\\/g,"/")}function eL(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function Wa(e,t){let n=cr(e,t),r=ro(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&&!Yu(m.symbol,l.symbol))continue;let h=m.endLine-m.startLine;h<d&&(d=h,u=m)}u?u.children.push(l):s.push(l)}return s}function Ga(e,t){let n=B(e,t);return n?new T(e).definitionsForFile(n.relativePath).filter(i=>i.symbol!==n.symbol).filter(i=>Qu(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:ee(i.symbol)??"unknown"})):[]}function za(e,t){let n=B(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
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
356
405
  FROM mentions m
357
406
  JOIN chunks c ON m.chunk_id = c.id
358
407
  WHERE m.symbol_id = ?
359
- AND m.role != 1`,n.symbolId);return[{name:b(n.symbol),count:r?.file_count??0}]}function Ja(e,t){let n=Ee(e,t);if(!n)return[];let i=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
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
360
409
  FROM mentions m
361
410
  JOIN chunks c ON m.chunk_id = c.id
362
411
  JOIN documents d ON c.document_id = d.id
@@ -373,7 +422,7 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
373
422
  AND m.role != 1
374
423
  AND def_d.id != d.id
375
424
  GROUP BY d.id
376
- 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=re(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function Ka(e,t={}){return tL(e,t).map(n=>({name:b(n.symbol),count:n.file_count}))}function tL(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
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
377
426
  FROM mentions m
378
427
  JOIN chunks c ON m.chunk_id = c.id
379
428
  JOIN global_symbols gs ON m.symbol_id = gs.id
@@ -392,7 +441,7 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
392
441
  GROUP BY gs.id
393
442
  HAVING file_count > 1
394
443
  ORDER BY file_count DESC
395
- LIMIT ?`,n)}function Xa(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
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
396
445
  FROM mentions m
397
446
  JOIN chunks c ON m.chunk_id = c.id
398
447
  JOIN documents d ON c.document_id = d.id
@@ -412,7 +461,7 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
412
461
  ${i}
413
462
  GROUP BY d.id
414
463
  ORDER BY symbol_count DESC
415
- LIMIT ?`,n).filter(s=>!e.isIgnored(s.relative_path)).map(s=>({name:s.relative_path,count:s.symbol_count}))}function Qa(e,t,n){let r=Ee(e,t)??t,i=Ee(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
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
416
465
  FROM global_symbols gs
417
466
  WHERE (
418
467
  -- Defined in file1, referenced in file2
@@ -444,7 +493,7 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
444
493
  JOIN documents d ON c.document_id = d.id
445
494
  WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
446
495
  )
447
- )`,r,i,i,r);return{...Jm(r,i,o?.shared??0)}}function Ya(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
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
448
497
  def_d.relative_path AS file1,
449
498
  ref_d.relative_path AS file2,
450
499
  COUNT(DISTINCT gs.id) AS shared
@@ -466,7 +515,7 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
466
515
  ${i}
467
516
  GROUP BY def_d.id, ref_d.id
468
517
  ORDER BY shared DESC
469
- LIMIT ?`,n).filter(s=>!e.isIgnored(s.file1)&&!e.isIgnored(s.file2)).map(s=>Jm(s.file1,s.file2,s.shared))}function Jm(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 Sn(e,t={}){let{scope:n,maxDepth:r=10}=t,i=re(e,n),o=[],s=new Set,a=new Set,c=[];function l(d,m){if(m>r)return;if(a.has(d)){let h=c.indexOf(d);if(h!==-1){let g=c.slice(h).concat(d),y=g.indexOf(g.reduce((k,N)=>k<N?k:N)),S=[...g.slice(y,-1),...g.slice(0,y),g[y]],v=S.join(" -> ");u.has(v)||(u.add(v),o.push({path:S,kind:nL(S)}))}return}if(s.has(d))return;s.add(d),a.add(d),c.push(d);let f=i.get(d);if(f)for(let h of f)l(h,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 nL(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":Ro(t)||Ro(n)||Km(t,n)||Km(n,t)||Xm(t,n)||Xm(n,t)||J(t)==="entry"||J(n)==="entry"?"module-hierarchy":"real"}function Km(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 Xm(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 Za(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new T(e);return We(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>rL(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 rL(e,t,n){let r=new Set(Ue(e,t,{limit:500,semantic:n}).map(s=>s.file)).size,i=new Set(Me(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 xn(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new T(e),s=t.semantic!==!1,a=We(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,sortByLocDesc:typeof i=="number"&&i>0}),i),c=o.crossFileCallerMap(a,{semantic:!1}),l=new Set(c.keys());for(let g of o.frameworkReferencedSymbolIds(a))l.add(g);let u=o.symbolsWithNonSelfCallees(a,{additive:!1,semantic:!1}),d=a.filter(g=>!l.has(g.symbolId)).filter(g=>!u.has(g.symbolId));if(s&&d.length>0){for(let g of o.crossFileCallerMap(d,{semantic:!0}).keys())l.add(g);for(let g of o.symbolsWithNonSelfCallees(d,{additive:!1,semantic:!0}))u.add(g);d=d.filter(g=>!l.has(g.symbolId)).filter(g=>!u.has(g.symbolId))}let m=o.sourceFallbackCallerFiles(d);for(let g of m.keys())l.add(g);let f=d.filter(g=>!l.has(g.symbolId)),h=o.symbolsWithNonSelfCallees(f,{additive:!0,semantic:s});for(let g of h)u.add(g);return f.filter(g=>!u.has(g.symbolId)).sort((g,y)=>q(y)-q(g)||g.relativePath.localeCompare(y.relativePath)||g.startLine-y.startLine).map(g=>({symbol:g.symbol,shortName:b(g.symbol),relativePath:g.relativePath,startLine:g.startLine,endLine:g.endLine,loc:q(g)}))}var tc={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"},ec=new Map;for(let[e,t]of Object.entries(tc))ec.set(t.toLowerCase(),Number(e));var Qm=500;function iL(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=ec.get(n);if(r!==void 0)return r;for(let[i,o]of ec)if(i.includes(n))return o;return null}function nc(e,t,n={}){let{scope:r,limit:i=100}=n,o=iL(t);return o===null?[]:oL(e,r).map(a=>({row:a,resolvedKind:Zm(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:b(a.symbol),kind:c,kindName:tc[c]??"Unknown",relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function rc(e,t={}){let n=sL(e,t.scope);for(let r of aL(e,t.scope)){let i=Zm(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:tc[r]??"Unknown",count:i}))}function oL(e,t){return ut(e,{scope:t}).map(cL)}function sL(e,t){let n=new Map;for(let r of Ym(j(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
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
470
519
  FROM defn_enclosing_ranges der
471
520
  JOIN global_symbols gs ON der.symbol_id = gs.id
472
521
  JOIN documents d ON der.document_id = d.id
@@ -474,7 +523,7 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
474
523
  AND gs.kind != 0
475
524
  AND gs.symbol NOT LIKE '%#'
476
525
  AND d.relative_path IN (${i})
477
- GROUP BY gs.kind`,...r);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function aL(e,t){let n=[];for(let r of Ym(j(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
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,
478
527
  gs.kind,
479
528
  gs.documentation,
480
529
  gs.enclosing_symbol,
@@ -487,11 +536,11 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
487
536
  WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
488
537
  ${e.symbolNoiseFor("gs")}
489
538
  AND d.relative_path IN (${i})
490
- ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...r))}return n}function Ym(e){let t=[];for(let n=0;n<e.length;n+=Qm)t.push(e.slice(n,n+Qm));return t}function cL(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 Zm(e){return e.kind!==null&&e.kind!==0?lL(e.kind,e.symbol,e.documentation):uL(e.symbol,e.documentation,e.enclosing_symbol)}function lL(e,t,n){let r=(n??"").toLowerCase();if(ee(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 uL(e,t,n){let r=ge(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=ee(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?ee(n):o?.suffix??null)==="type"?21:83}function ic(e,t={}){let{limit:n=10,scope:r,minDepth:i=3}=t,o=re(e,r),s=new Map,a=[],c=new Map,l=new Map,u=new Set,d=[],m=0;for(let w of o.keys()){if(c.has(w))continue;let R=[],$=(o.get(w)??new Set).values();for(c.set(w,m),l.set(w,m),m+=1,d.push(w),u.add(w),R.push({node:w,iter:$,pendingChild:null});R.length>0;){let I=R[R.length-1];if(I.pendingChild!==null){let Oe=I.pendingChild;I.pendingChild=null,l.set(I.node,Math.min(l.get(I.node),l.get(Oe)))}let z=I.iter.next();if(z.done){if(l.get(I.node)===c.get(I.node)){let Oe=[];for(;;){let Ne=d.pop();if(u.delete(Ne),Oe.push(Ne),s.set(Ne,a.length),Ne===I.node)break}a.push(Oe)}R.pop();continue}let xe=z.value;if(c.has(xe))u.has(xe)&&l.set(I.node,Math.min(l.get(I.node),c.get(xe)));else{c.set(xe,m),l.set(xe,m),m+=1,d.push(xe),u.add(xe);let Oe=(o.get(xe)??new Set).values();I.pendingChild=xe,R.push({node:xe,iter:Oe,pendingChild:null})}}}let f=new Map,h=new Array(a.length);for(let w=0;w<a.length;w++)h[w]=a[w].length,f.set(w,new Set);for(let[w,R]of o){let $=s.get(w);for(let I of R){let z=s.get(I);z!==$&&f.get($).add(z)}}let g=new Array(a.length),y=new Array(a.length);for(let w=0;w<a.length;w++){let R=[],$=0;for(let I of f.get(w)){let z=y[I];z>$&&($=z,R=g[I])}g[w]=[w,...R],y[w]=h[w]+$}function S(w){return g[w]}let v=a.map(w=>[...w].sort()),k=new Set,N=[];for(let w=0;w<a.length;w++){let R=S(w),$=[];for(let z of R)$.push(...v[z]);if($.length<i)continue;let I=$.join(" ");k.has(I)||(k.add(I),N.push(dL($)))}return N.sort((w,R)=>R.depth-w.depth),mL(N).slice(0,n)}function dL(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 mL(e){let t=[];for(let n of e)t.some(r=>pL(n.chain,r.chain))||t.push(n);return t}function pL(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 oc(e,t){let n=B(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
491
- WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:b(r.symbol),depth:0}],o=r.enclosing_symbol,s=1,a=new Set([r.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let 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=ge(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 h=l.slice(0,d+1).map(g=>g.suffix==="method"?`${g.name}()`:g.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:h,shortName:h,depth:m})}return u}function li(e,t,n={}){let r=B(e,t);if(!r)return null;let i=n.semantic!==!1,o=Ue(e,r,{limit:50,semantic:i}),s=Sr(Me(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 Ge(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function ye(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function Xt(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 ep(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 tp(e){let t=e.length;if(t===0)return new Map;let n=new Map;for(let r of e)for(let i of r)n.set(i,(n.get(i)??0)+1);return sc(n,t)}function sc(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 Oo(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 np(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??Oo(n),c=[],l=[];for(let m of e){let f=n.get(m)??0;o+=f*f,t.has(m)&&(i+=f*f,f>=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 f=n.get(m)??0;s+=f*f}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?i/u:0;return c.sort((m,f)=>(n.get(f)??0)-(n.get(m)??0)),{similarity:d,significantShared:c,trivialShared:l}}function di(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=yL(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!ce(o.symbol))return[];let s=fL(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):RL(e,t,{minSimilarity:r,limit:i})}function fL(e,t,n,r){let i=sp(e,{minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=xL(t,i),s=tp([t,...i.corpus].map(l=>l.callees)),a=Oo(s),c=[];for(let l of o){if(l.callees.size<3)continue;let u=op(t,l,s,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:a});u&&c.push(u)}return c.sort((l,u)=>u.similarity-l.similarity),c}function op(e,t,n,r){let{similarity:i,significantShared:o,trivialShared:s}=np(e.callees,t.callees,n,{medianIdf:r.medianIdf});if(i<r.minSimilarity)return null;let a=o.length+s.length;if(o.length<r.requireSignificantShared&&a<r.requireSharedCount)return null;let c=o.length>0?o:s,l=ap(c,"callees");return{symbolA:e.symbol,shortNameA:b(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:b(t.symbol),fileB:t.file,similarity:i,similarityBasis:"callees",sharedCallees:c.map(b),uniqueToA:[...ye(e.callees,t.callees)].map(b),uniqueToB:[...ye(t.callees,e.callees)].map(b),...l}}function Pt(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=sp(e,{minCallees:o,scope:i,scanLimit:a,semantic:t.semantic!==!1}),l=c.corpus,u=[],d=0;for(let m=0;m<l.length;m+=1){let f=l[m],h=new Set;for(let g of f.callees){let y=c.candidateIndexesByCallee.get(g);if(y)for(let S of y)S>m&&h.add(S)}for(let g of h){let y=l[g];if(s&&f.file===y.file)continue;if(f.paramCount>=0&&y.paramCount>=0){let v=Math.abs(f.paramCount-y.paramCount),k=Math.max(2,Math.ceil(Math.max(f.paramCount,y.paramCount)*.5));if(v>k)continue}let S=op(f,y,c.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:c.medianIdf});S&&(gL(u,S,r,d),d+=1)}}return u.sort((m,f)=>f.result.similarity-m.result.similarity||m.order-f.order),u.map(m=>m.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 hL=["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 yL(e,t,n){let r=B(e,t),i=new T(e);if(!r)return null;let o=Me(e,r,{semantic:n.semantic});return{symbol:r.symbol,file:r.relativePath,callees:Bo(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var bL=Y("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),SL=Y("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function uc(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=bL.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=a.get(c);return l||(l=CL(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,l)),i===void 0?l:l.filter(u=>u.symbol!==i)}function sp(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=SL.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=s.get(a);return c||(c=dc(uc(e,{minCallees:n,scope:r,scanLimit:i,semantic:o})),s.set(a,c)),c}function dc(e){let t=new Map;for(let o of e)for(let s of o.callees)t.set(s,(t.get(s)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),r=sc(t,e.length),i=new Map;for(let o=0;o<e.length;o+=1){let s=e[o];for(let a of s.callees){if((t.get(a)??0)>n)continue;let c=i.get(a);c||(c=[],i.set(a,c)),c.push(o)}}return{corpus:e,candidateIndexesByCallee:i,docFreq:t,idfWeights:r,medianIdf:Oo(r),ubiquityThreshold:n}}function xL(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 CL(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=new T(e),a=We(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:Bo((c.get(l.symbolId)??[]).map(u=>u.symbol)),paramCount:s.callableSignature(l)?.paramCount??-1})).filter(l=>l.callees.size>=n)}function Bo(e){return new Set([...e].filter(t=>!vL(t)))}function vL(e){return hL.some(t=>e.includes(t))}function RL(e,t,n){let r=IL(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=FL(r,TL(e));for(let a of s){if(a.symbol===r.symbol||a.tokens.size<3)continue;let c=Ge(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:[...ye(r.tokens,a.tokens)].sort(),uniqueToB:[...ye(a.tokens,r.tokens)].sort(),...ap([...c],"source-tokens")})}return o.sort((a,c)=>c.similarity-a.similarity||a.shortNameB.localeCompare(c.shortNameB)),o.slice(0,n.limit)}function ap(e,t){let n=e.flatMap(cc),r=e.flatMap(y=>rp(y,t)),i=ac(n,cp),o=ac(n,lp),s=ac(r,lc),a=[...new Set(r.filter(ip))],c=e.filter(y=>{let S=rp(y,t);return S.some(v=>lc.has(v))&&S.some(ip)}).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(y=>up.has(y));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=i.length+o.length>0,f=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,h=f?"domain-behavior":d?m?"mixed":"domain-behavior":i.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";h==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=h==="domain-behavior"&&(e.length>=3||f)?"direct":"signal";return{evidenceClass:h,actionTier:g,evidenceClassReasons:l,recommendation:kL(h,g)}}function kL(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 ac(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function cc(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function rp(e,t){if(t==="source-tokens")return cc(e);let n=A(e);return cc(n.length>0?n:wL(e))}function wL(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 ip(e){return e.length>3&&!lc.has(e)&&!cp.has(e)&&!lp.has(e)&&!up.has(e)&&!LL.has(e)}var lc=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),cp=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),lp=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"]),up=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),LL=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 IL(e,t){let n=B(e,t);if(!n||!ce(n.symbol))return null;let r=DL(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function DL(e,t){let n=A(t.symbol),r=dp(e,t.relativePath,t.startLine,t.endLine,n),i=mp(r,n);return i.size>0?i:null}var PL=Y("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),NL=Y("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function EL(e){return PL.get(e,()=>$L(e))}function TL(e){return NL.get(e,()=>_L(EL(e)))}function _L(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 FL(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 $L(e){return new T(e).productionCallableDefinitions().map(n=>({symbol:n.symbol,file:n.relativePath,tokens:mp(dp(e,n.relativePath,n.startLine,n.endLine,n.leaf),n.leaf)})).filter(n=>n.tokens.size>0)}function dp(e,t,n,r,i){let o=Qe(e,t);if(o.length===0)return"";if(r>=n&&r-n<=12)return o.slice(n,r+1).join(`
492
- `);let s=[new RegExp(`\\bdef\\s+${ui(i)}\\b`),new RegExp(`\\bfun\\s+${ui(i)}\\b`),new RegExp(`\\bfn\\s+${ui(i)}\\b`),new RegExp(`\\bfunction\\s+${ui(i)}\\b`),new RegExp(`\\b${ui(i)}\\s*\\(`)],a=o.findIndex(c=>s.some(l=>l.test(c)));if(a>=0){let c=a;for(let l=a+1;l<o.length&&l<=a+8;l++){let u=o[l]??"";if(l>a&&ML(u)||(c=l,u.trim()===""&&l>a+1))break}return o.slice(a,c+1).join(`
493
- `)}return o.slice(n,Math.min(o.length,n+8)).join(`
494
- `)}function mp(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=AL(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 AL(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 ML(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function ui(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ft(e){let t=[];if(e.filePattern){let n=e.profiles.find(r=>r.file.includes(e.filePattern));if(!n)return[];for(let r of e.profiles){if(r.file===n.file)continue;let i=e.compare(n,r);i&&t.push(i)}}else{let n=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let r=0;r<e.profiles.length;r+=1){for(let i=r+1;i<e.profiles.length;i+=1){let o=e.compare(e.profiles[r],e.profiles[i]);o&&t.push(o)}if(t.length>n)break}}return t.sort(e.sort??((n,r)=>r.similarity-n.similarity)),t.slice(0,e.limit)}function mc(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=jL(e,{scope:i,minDeps:s});return ft({profiles:a,limit:r,filePattern:o,overrunFactor:5,compare:(l,u)=>BL(l,u,n,c)})}function jL(e,t){let{scope:n,minDeps:r}=t,i=re(e,n),{universalDeps:o,distinctiveDeps:s}=OL(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 OL(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 BL(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=Xt(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 Ho(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&pp(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)HL(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,pp(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 Vo(e,t){if(e.size===0||t.size===0)return 0;let r=Ge(e,t).size/Math.min(e.size,t.size);return Math.max(Xt(e,t),r)}function V(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function ve(e){return[...e].sort()}function HL(e,t,n,r,i,o){let s=[],a=[];for(let c of e)VL(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 VL(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 pp(e,t,n){return e==="generic"?t:n}function Cn(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=tr(e,{scope:o,minJsxTokens:r,scanLimit:s}).filter(l=>l.kind==="component").map(l=>({file:l.file,component:l.name,tokens:l.jsxTokens,profile:l}));return ft({profiles:c,limit:i,filePattern:a,compare:(l,u)=>qL(l,u,n),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.componentA.localeCompare(u.componentA)||l.fileB.localeCompare(u.fileB)||l.componentB.localeCompare(u.componentB)})}function qL(e,t,n){let r=Ge(e.tokens,t.tokens);if(r.size<6||!UL(r))return null;let i=Xt(e.tokens,t.tokens);return i<n?null:{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:i,sharedTokens:ve(r),sharedComponents:V(r,"component:"),sharedNativeTags:V(r,"native:"),sharedProps:V(r,"prop:"),sharedEvents:V(r,"event:"),sharedBindings:V(r,"binding:"),uniqueToA:ve(ye(e.tokens,t.tokens)).slice(0,25),uniqueToB:ve(ye(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function UL(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 vn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=tr(e,{scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(l=>({file:l.file,component:l.name,tokens:l.behaviorTokens,profile:l}));return ft({profiles:c,limit:i,filePattern:a,compare:(l,u)=>WL(l,u,n,r),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.componentA.localeCompare(u.componentA)||l.fileB.localeCompare(u.fileB)||l.componentB.localeCompare(u.componentB)})}function WL(e,t,n,r){let i=Ge(e.tokens,t.tokens);if(i.size<r||!JL(i))return null;let o=Vo(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:"),f=GL({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:ve(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:f.evidenceClass,actionTier:f.actionTier,evidenceClassReasons:f.reasons,recommendation:f.recommendation,uniqueToA:ve(ye(e.tokens,t.tokens)).slice(0,25),uniqueToB:ve(ye(t.tokens,e.tokens)).slice(0,25),reason:KL({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function GL(e){return Ho({genericWords:XL,stripPrefixes:QL,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:zL})}function zL(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 JL(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 KL(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 XL=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"]),QL=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function mi(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 tr(e,{scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>YL(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 YL(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=ZL(e),o=eI(e,t,i),s=tI(e),a=nI(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:rI(a,s),reasons:n,loc:e.loc}}function ZL(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 eI(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 tI(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=>oI.has(l)),s=o>=0&&n.slice(o+1).some(l=>iI.has(l)),a=fp(r)||fp(e.name);return/(?:Page|Route|Screen|View)$/.test(r)||/(?:Page|Route|Screen|View)$/.test(e.name)||i.some(l=>sI.has(l))||o>=0&&!s&&!a?"route-page":"component"}function fp(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&gp.has(t.at(-1))?!0:[...gp].some(n=>e.endsWith(aI(n)))}function nI(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 rI(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 iI=new Set(["component","components","panel","panels","partial","partials"]),gp=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"]),oI=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),sI=new Set(["landing","page","route","screen","view"]);function aI(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Rn(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=cI(e,{scope:o,minTokens:r,scanLimit:s});return ft({profiles:c,limit:i,filePattern:a,compare:(l,u)=>uI(l,u,n),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.fileB.localeCompare(u.fileB)})}function cI(e,t){return er(e,{scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:lI(n)}))}function lI(e){return e.totalLines}function uI(e,t,n){let r=Ge(e.tokens,t.tokens);if(r.size<6||!dI(r))return null;let i=Xt(e.tokens,t.tokens);return i<n?null:{fileA:e.file,fileB:t.file,similarity:i,sharedTokens:ve(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:ve(ye(e.tokens,t.tokens)).slice(0,25),uniqueToB:ve(ye(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function dI(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 kn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=er(e,{scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(l=>({file:l.file,tokens:l.behaviorTokens,profile:l}));return ft({profiles:c,limit:i,filePattern:a,compare:(l,u)=>mI(l,u,n,r),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.fileB.localeCompare(u.fileB)})}function mI(e,t,n,r){let i=Ge(e.tokens,t.tokens);if(i.size<r||!gI(i))return null;let o=Vo(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:"),f=V(i,"template-binding:"),h=V(i,"template-event:"),g=pI({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:h});return{fileA:e.file,fileB:t.file,similarity:o,sharedTokens:ve(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:h,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:ve(ye(e.tokens,t.tokens)).slice(0,25),uniqueToB:ve(ye(t.tokens,e.tokens)).slice(0,25),reason:hI({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function pI(e){return Ho({genericWords:yI,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:fI})}function fI(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 gI(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 hI(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 yI=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 pi(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 er(e,{scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>bI(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 bI(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=SI(e),i=xI(e,t,r),o=CI(e.file),s=vI(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:RI(s,o),reasons:n,loc:e.totalLines}}function SI(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 xI(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 CI(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>kI.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function vI(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 RI(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 kI=new Set(["landing","page","pages","route","routes","view","views"]);function pc(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=re(e,i),c=TI(a,o,s);if(c.length===0)return[];let l=wI(c);return l.length<2?[]:EI(DI(l,n,r),r)}function wI(e){let t=LI(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 LI(e){let{nodeFreq:t,tailFreq:n}=II(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 II(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 DI(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=PI(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 PI(e,t,n){if(!NI(e.filtered,t.filtered))return null;let{distance:r,ops:i}=_I(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:FI(e.original,t.original),commonSuffix:$I(e.original,t.original)}}function NI(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function EI(e,t){let n=[];for(let r of e)if(n.some(o=>hp(r.chainA,o.chainA)&&hp(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function TI(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;yp(e,o,[o],new Set([o]),t,n,r,500)}return r}function yp(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),yp(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 _I(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 FI(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 $I(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 hp(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=We(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 wn(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new T(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)=>AI(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function AI(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=HI(r,t),o=VI(r,i);if(o.length<2)return null;let s=qI(o,i);if(s.length===0)return null;let a=b(e.symbol),c=MI(a,r.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:q(e),totalCallees:r.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function MI(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=jI(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 jI(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=OI(e);return BI.has(r)?`caller verb suggests orchestration: ${r}`:null}function OI(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 BI=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function HI(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 VI(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 qI(e,t){return e.filter(n=>n.size>=3).map(n=>UI(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function UI(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 xr}from"path";var WI=U("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]});function Ln(e,t,n){return e.callerFileMap(t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function qo(e,t,n){let r=[],i=0,o=0,s=A(t.symbol);for(let a of n)QI(e,a,t.relativePath,s)?i++:fc(e,a,s)?o++:r.push(a);return{realConsumers:r,barrelConsumers:i,importOnlyConsumers:o}}function fc(e,t,n){if(!n)return!1;let r=W(t);if(!r)return!1;let i=WI.get(e,t,()=>GI(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function GI(e,t,n){let r=F(e,t);if(!r)return JI();let i=Ye(e,t,r),o=Mt(e,"consumer-file-usage",t,i);if(o){let a=XI(o);if(a)return a}let s=zI(e,t,n);return jt(e,"consumer-file-usage",t,i,KI(s)),s}function zI(e,t,n){let r=new Set,i=new Set,o=fe(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 JI(){return{importedLeaves:new Set,usedLeaves:new Set}}function KI(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function XI(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 QI(e,t,n,r){if(!r)return!1;let i=Qe(e,t);if(i.length===0)return!1;let o=Kr(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 YI=20,ZI=1,eD=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"]]),tD=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),nD=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 bc(e,t={}){let n=yc(t.limit,YI),r=yc(t.minConsumers,ZI),i=new T(e),o=i.fileDependencyGraph(t.scope),s=vD(j(e,{includeIgnored:!1})),a=wD(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?rD(e,i,t.target):iD(e,t.scope,t.scanLimit)).map(u=>oD(i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(CD).slice(0,n)}function rD(e,t,n){let r=cD(e,n);if(r)return[vp(r)];let i=B(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[lD(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:b(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function iD(e,t,n){let r=j(e,{scope:t,includeIgnored:!1}),i=yc(n,r.length);return r.slice(0,i).map(o=>vp(o))}function oD(e,t,n,r,i,o){let s=n.definition?sD(e,n.definition,r.semantic):aD(t,n.unit.file),a=n.definition?s.length>0?"exact":"none":s.length>0?"file-level":"none",c=n.unit.file,l=rt(xr.dirname(c)),u=dD(s),d=uD(l),m=Cc([...bp(l),...u?bp(u):[]]),f=mD(n.unit,l,u,s),h=pD(f,n.unit,l,u,s,i,o),g=bD(n.unit,a,u,s,l,h.whyNoSuggestedHome),y=SD(n.unit,l,u,s,h.suggestedHome,h.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:n.unit,candidatePath:c,currentDirectory:l,directoryAncestry:d,consumerFiles:s,consumerCoverage:a,nearestCommonOwner:u,boundaryMarkers:m,recommendedTier:f,suggestedHome:h.suggestedHome,destinationConfidence:h.confidence,whyNoSuggestedHome:h.whyNoSuggestedHome,counterevidence:g,reasons:y,recommendation:xD(f,h.suggestedHome,a)}}function sD(e,t,n){let r=Ln(e,[t],{semantic:n!==!1,sourceFallback:!0});return Ip(r.get(t.symbolId)??[])}function aD(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return Ip(n)}function cD(e,t){let n=xc(t),r=j(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 lD(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:b(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function vp(e){return{unit:{kind:"file",file:e,shortName:xr.basename(e)}}}function uD(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:Sc(i)})}return t}function bp(e){return e==="."?[]:Rp(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function Sc(e){return Cc(Rp(e).map(({marker:t})=>t))}function Rp(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=eD.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function dD(e){if(e.length===0)return null;let t=e.map(r=>rt(xr.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 mD(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":xp(n,"package")?"package-level-shared":xp(n,"app")?"app-level-shared":Cp(n,["feature","domain","module"])||Cp(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function pD(e,t,n,r,i,o,s){let a=fD(e,r);if(a)return Qt(a);let c=RD(t.file),l=gD(e,n,c,i,s);if(l)return l;let u=r;if(rt(n)===rt(u))return Qt(`${n} is already the nearest common owner for its consumers.`);let d=hD(u,n,c,s);return d||yD(u,n,c,o,s)}function fD(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 gD(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?gc(o):Qt("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=rt(xr.dirname(r[0])),s=Lp(t,n,o,i);return s?Qt(s):gc(o)}return null}function hD(e,t,n,r){return ID(e)?kp(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function yD(e,t,n,r,i){if(e===".")return Qt("The nearest common owner is the repository root.");let o=`${e}/shared`,s=kp(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:Qt(`${o} does not exist in the indexed project.`)}function kp(e,t,n,r,i){if(!wp(e,n))return Qt(i);let o=Lp(t,n,e,r);return o?Qt(o):gc(e)}function gc(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function Qt(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function bD(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 SD(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 xD(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 CD(e,t){return Sp(t)-Sp(e)||e.candidatePath.localeCompare(t.candidatePath)}function Sp(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 vD(e){let t=new Set(["."]);for(let n of e){let r=rt(xr.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=rt(xr.dirname(r))}return t}function RD(e){let t=hc(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function wp(e,t){let n=rt(e),r=rt(t);return r==="."||n===r||n.startsWith(`${r}/`)}function kD(e,t,n){let r=hc(e),i=hc(t);return(wp(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function Lp(e,t,n,r){return rt(e)===rt(n)||!kD(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function wD(...e){let t=new Set(nD);for(let n of e)for(let r of n??[]){let i=LD(r);i&&t.add(i)}return t}function LD(e){let t=e.trim().toLowerCase();return t===""?null:t}function xp(e,t){return Sc(e).includes(t)}function Cp(e,t){let n=Sc(e);return t.some(r=>n.includes(r))}function ID(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?tD.has(n):!1}function xc(e){return e.replaceAll("\\","/").replace(/^\.\//,"")}function rt(e){let t=xc(e);return t===""?".":t}function hc(e){let t=xc(e);return t==="."?[]:t.split("/").filter(Boolean)}function yc(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function Ip(e){return Cc([...e]).sort((t,n)=>t.localeCompare(n))}function Cc(e){return[...new Set(e)]}function fi(e,t,n={}){let{maxDepth:r=5,scope:i}=n,o=B(e,t);if(!o)return[];let s=[],a=new Set([o.symbolId]),c=new Set,l=[o];for(let u=1;u<=r&&l.length!==0;u++){let d=[];for(let m of l)for(let f of DD(e,m,i)){let h=`${f.file}|${f.shortName}`;if(f.symbolId!==null){if(a.has(f.symbolId))continue;a.add(f.symbolId)}else if(c.has(h))continue;c.add(h),s.push({symbol:f.symbol,shortName:f.shortName,file:f.file,depth:u}),f.symbolId!==null&&f.symbolMatch&&d.push(f.symbolMatch)}l=d}return s.sort((u,d)=>u.depth-d.depth||u.file.localeCompare(d.file)),s}function DD(e,t,n){let r=Ue(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 PD(e,t,n)){if(i.has(l))continue;let u=G(e,l),d=u.length>0?Be(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=ar(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)||!ND(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 PD(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
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(`
542
+ `)}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
495
544
  FROM mentions m
496
545
  JOIN chunks c ON m.chunk_id = c.id
497
546
  JOIN documents consumer_d ON consumer_d.id = c.document_id
@@ -499,48 +548,50 @@ ${m}`,l+=1+m.length,u+=zr(m),r+=m.length+1}let d=Hv(c);d&&n.push({...d,start:a,e
499
548
  AND m.role != 1
500
549
  AND c.document_id != ?
501
550
  ${e.pathExclusionsFor("consumer_d")}
502
- ${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function ND(e){let t=ee(e);return t==="method"||t==="type"||e.endsWith("().")}function gi(e,t,n={}){let r=Ee(e,t);if(!r)return null;let i=ED(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=TD(e,i.relative_path),c=n.semantic===!1?new Map:mt(e,a);for(let l of a){let u=_D(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:FD(u)})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s}}function ED(e,t){return e.get(`SELECT id, relative_path FROM documents
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
503
552
  WHERE relative_path = ?
504
553
  ${e.pathExclusionsFor("documents")}
505
- LIMIT 1`,t)??null}function TD(e,t){return new T(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function _D(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
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
506
555
  FROM mentions m
507
556
  JOIN chunks c ON m.chunk_id = c.id
508
557
  JOIN documents consumer_d ON consumer_d.id = c.document_id
509
558
  WHERE m.symbol_id = ?
510
559
  AND m.role != 1
511
- 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 FD(e){return e>10?"high":e>0?"medium":"low"}function Uo(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new T(e),a=$D(e,n,r,o),c=new vc;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(Dp(e,0,a,c));let d=a.map(g=>g.definition).filter(g=>g!==null),m=new Set(a.map(g=>g.symbol));for(let g=1;g<=i&&d.length>0;g++){let y=s.calleeMap(d,{semantic:!1}),S=new Set;for(let k of d)for(let N of y.get(k.symbolId)??[])m.has(N.symbol)||S.add(N.symbol);let v=[];for(let k of S){m.add(k);let N=Pp(e,k);if(!N||e.isIgnored(N.relativePath)||De(e,N.relativePath)||ie(e,N.symbol,N.relativePath)||s.fileKind(N.relativePath)==="test"||s.hasSuppressionComment(N))continue;let w=MD(e,N,c);w.removable?v.push(AD(N,"cascade")):w.blockingFiles.length>0&&u.push({shortName:b(N.symbol),file:N.relativePath,blockingFiles:w.blockingFiles.slice(0,3)})}if(v.length===0)break;for(let k of v)c.add(k);l.push(Dp(e,g,v,c)),d=v.map(k=>k.definition).filter(k=>k!==null)}let f=l.reduce((g,y)=>g+y.loc,0),h=l.reduce((g,y)=>g+y.entries.length,0);return{batches:l,totalSymbols:h,totalLoc:f,blocked:u}}function $D(e,t,n,r){let i=Dt(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(De(e,s.relativePath)||ie(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:Pp(e,s.symbol)}));return o}function AD(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 Pp(e,t){let n=e.get(`SELECT d.relative_path
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
512
561
  FROM global_symbols gs
513
562
  JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
514
563
  JOIN documents d ON d.id = der.document_id
515
564
  WHERE gs.symbol = ?
516
- LIMIT 1`,t);return n?G(e,n.relative_path).find(r=>r.symbol===t)??null:null}function MD(e,t,n){let r=bn(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 Dp(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 vc=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 KE}from"crypto";import{existsSync as yf}from"fs";import{execFileSync as jD}from"child_process";var Ep=2e3,Tp=50,OD=8,BD=3,HD=2160*60*60,VD=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,qD=3,UD=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,WD=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function Rc(e){let t=Y(e,{clearGroups:["whole-project"]});return(n,r)=>{let i=zD(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 GD=Rc("git-commit-history");function Yt(e){return GD(e,JD)}function zD(e){try{return Wo(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function Wo(e,t){return jD("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function JD(e,t){let n;try{n=Wo(e,["log","--no-merges","--name-only","-n",String(Ep),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let r=[],i=0;for(let o of n.split("")){if(o.trim()==="")continue;let s=o.indexOf(`
517
- `),a=s>=0?o.slice(0,s):o,[c,l,u]=a.split("\0");if(!c||!l)continue;let d=s>=0?o.slice(s+1).split(`
518
- `).map(m=>m.trim()).filter(m=>m!==""):[];if(d.length>Tp){i+=1;continue}r.push({hash:c,timestamp:Number(l)||0,subject:u??"",files:d})}return{head:t,commits:r,skippedBulkCommits:i}}function KD(e){return VD.test(e.subject)}function Go(e){let t=Yt(e);if(!t)return null;let n=new Map;for(let r of t.commits){let i=KD(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 _p(e){let t=Yt(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:Np(n,.5),p90FilesPerCommit:Np(n,.9),commitsAnalyzed:n.length}}function Np(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var XD=Rc("git-tracked-files");function kc(e){return XD(e,t=>{try{let n=Wo(t,["ls-files"]);return new Set(n.split(`
519
- `).map(r=>r.trim()).filter(r=>r!==""))}catch{return null}})}var QD=Rc("git-file-adds");function Fp(e){return QD(e,t=>YD(t))}function YD(e){let t;try{t=Wo(e,["log","--no-merges","--diff-filter=A","--name-only","-n",String(Ep),"--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(`
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(`
520
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(`
521
- `)){let u=l.trim();u!==""&&n.set(u,{commitsAgo:r,addedAt:c})}}return n}function $p(e,t={}){let n=Yt(e);return n?Mp(n,t):null}function Ap(e,t,n={}){let r=Yt(e);return r?t.size===0?[]:Mp(r,n,t):null}function Mp(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=Tp}=t,s=new Map,a=new Map,c=0;for(let d of e.commits){let m=[...new Set(d.files)].sort();if(m.length>o)continue;d.timestamp>c&&(c=d.timestamp);let f=ZD(m),h=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(h)for(let g=0;g<m.length;g++)for(let y=g+1;y<m.length;y++){if(n&&!n.has(m[g])&&!n.has(m[y]))continue;let S=`${m[g]}\0${m[y]}`,v=a.get(S)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};v.together+=1,f?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(S,v)}}let l=[],u=c-HD;for(let[d,m]of a){let f=m.together;if(f<r)continue;let[h,g]=d.split("\0"),y=s.get(h)??f,S=s.get(g)??f,v=Math.max(f/y,f/S);if(v<i)continue;let k=m.broadTogether/f,N=m.timestamps.filter(w=>w>=u).length;l.push({fileA:h,fileB:g,together:f,confidence:v,changesA:y,changesB:S,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:k,lastTogetherAt:m.lastTogetherAt,recentTogether:N,commitScope:tP(m.broadTogether,f),recency:N>0?"recent":"stale",subjectContext:nP(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function ZD(e){return e.length>=OD?!0:eP(e).size>=BD}function eP(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 tP(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function nP(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<qD&&r.push(i);for(let o of rP(i))t.add(o);for(let o of i.match(UD)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function rP(e){let t=new Set,n=WD.exec(e)?.[1]?.toLowerCase();return n&&t.add(iP(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 iP(e){return e==="feat"?"feature":e}import{existsSync as oP}from"fs";import{join as sP}from"path";function Lc(e){return wc.test(e)}var wc=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|CHANGELOG(?:\.[a-z]+)?|.*\.map)$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function In(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=Yt(e),c=t!==void 0,l=$p(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=re(e),d=Hp(e),m=Pc(e,u,d),f=n.includeLinked===!0||c,h=[];for(let g of l){if(wc.test(g.fileA)||wc.test(g.fileB)||!jp(e,g.fileA)||!jp(e,g.fileB)||c&&!g.fileA.includes(t)&&!g.fileB.includes(t)||!c&&(J(g.fileA)==="test"||J(g.fileB)==="test"||aP(g.fileA,g.fileB)))continue;let y=m(g.fileA,g.fileB);if(!f&&y)continue;let S=Ic(g.fileA,g.fileB),v=Dc(g,S,y);if(h.push({...g,structurallyLinked:y,partnerClass:S.partnerClass,partnerClassReasons:S.reasons,...v?{declaredCouplingSuggestion:v}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:a.commits.length,findings:h}}function jp(e,t){return oP(sP(e.config.projectRoot,t))}function Ic(e,t){let n=Op(e),r=Op(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=bP(n.tokens,r.tokens).filter(c=>!hP.has(c));return Bp(e,t)||a.length>=2?(o(Bp(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 Dc(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!gP.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${SP(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 Pc(e,t=re(e),n=Hp(e)){return(r,i)=>cP(t,n,r,i)}function aP(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 Hp(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function cP(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 lP=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,uP=/(?:^|\/)(?:\.[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,dP=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,mP=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,pP=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,fP=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,gP=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),hP=new Set(["src","lib","app","test","tests","spec","index","main","utils","util","types","type","config","docs","doc"]);function Op(e){let t=e.replace(/\\/g,"/"),n=new Set;return lP.test(t)&&n.add("doc"),uP.test(t)&&n.add("config"),dP.test(t)&&n.add("schema"),mP.test(t)&&n.add("script"),pP.test(t)&&n.add("model"),fP.test(t)&&n.add("view"),J(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:yP(t)}}function Bp(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 yP(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 bP(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function SP(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as it}from"child_process";import{existsSync as xP,readFileSync as CP}from"fs";import{basename as Vp}from"path";function zo(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 Nc="Unable to compute git diff.";function Cr(e,t={}){let n=t.plan??gt(e,t);return n.note?vP(n.note,n.changedFileLines):n.changedFiles.length===0?RP(n.changedFileLines):Ko(n.changedFiles,[Jo(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function gt(e,t={}){let{base:n="HEAD"}=t;try{let r=kP(e.config.projectRoot,n),i=TP(e,r),o=_P(e,wP(e.config.projectRoot,n));return{changedFileLines:r,changedFiles:i,changedRanges:o,renamedFiles:DP(e.config.projectRoot,n,i),note:r.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Nc}}}function Jo(e,t,n,r=[]){let i=new T(e),o=new Set(n),s=zo(r),a=[],c=new Map,l=t.flatMap(h=>i.definitionsForFile(h)).filter(HP).filter(h=>$P(h,s)).sort((h,g)=>h.relativePath.localeCompare(g.relativePath)||h.startLine-g.startLine),u=l.map(h=>h.symbolId),d=jP(e,u),m=OP(e,u,n),f=mt(e,l.filter(h=>d.get(h.symbolId)===0));for(let h of l)MP(e,h,o,a,c,f.get(h.symbolId)??new Set,d.get(h.symbolId)??0,m.get(h.symbolId)??new Set);return{changedSymbols:a,consumerEntries:[...c.entries()].map(([h,g])=>({file:h,symbols:[...g].sort()}))}}function Ko(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=BP(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:i.length}}}function vP(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function RP(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 kP(e,t){let n=it("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=it("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=it("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,r,i].flatMap(o=>o.split(`
522
- `)).map(o=>o.trim()).filter(o=>o.length>0))]}function wP(e,t){let n=it("git",["diff","--unified=0",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=it("git",["diff","--unified=0","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return Jp([...Wp(n),...Wp(r)])}function Ec(e,t,n){try{return it("git",["show",`${t}:./${n}`],{encoding:"utf-8",cwd:e,timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return null}}function hi(e,t,n=[]){let r=LP(e,t,n);return i=>(r.has(i)||r.set(i,Ec(e,t,i)),r.get(i)??null)}function yi(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 LP(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}
523
- `).join(""),s=it("git",["cat-file","--batch"],{cwd:e,input:o,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]});return IP(s,r)}catch{for(let o of r)i.set(o,Ec(e,t,o));return i}}function IP(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 DP(e,t,n){if(n.length===0)return[];let r=new Map,i=new Set;for(let s of NP(e,t))n.includes(s.to)&&(r.set(s.to,s),i.add(s.from));let o=PP(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)||!xP(`${e}/${s}`))continue;let a=o.filter(u=>!i.has(u)).filter(u=>Vp(u)===Vp(s));if(a.length===0)continue;let c=CP(`${e}/${s}`,"utf-8"),l=a.map(u=>({from:u,to:s,similarity:EP(Ec(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 PP(e,t){let n=it("git",["diff","--name-only","--diff-filter=D",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=it("git",["diff","--name-only","--diff-filter=D","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([...Up(n),...Up(r)])]}function NP(e,t){let n=it("git",["diff","--name-status","--find-renames",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=it("git",["diff","--name-status","--find-renames","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...n.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(`
524
575
  `),...r.split(`
525
- `)].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 EP(e,t){let n=new Set(qp(e)),r=new Set(qp(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 qp(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function Up(e){return e.split(`
526
- `).map(t=>t.trim()).filter(t=>t.length>0)}function TP(e,t){let n=zp(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function _P(e,t){let n=zp(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return Jp(r)}function zp(e){let t=e.all(`SELECT relative_path FROM documents
527
- 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 Wp(e){let t=[],n=null;for(let r of e.split(`
528
- `)){if(r.startsWith("+++ ")){n=FP(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 FP(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function Jp(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 $P(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>AP(e.startLine,e.endLine,r.startLine,r.endLine))}function AP(e,t,n,r){return e<=r&&n<=t}function MP(e,t,n,r,i,o,s,a){let c=Math.max(s,o.size);if(!VP(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)Gp(e,n,i,u,l);for(let u of o)Gp(e,n,i,u,l)}function jP(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
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
529
580
  FROM mentions m
530
581
  JOIN chunks c ON m.chunk_id = c.id
531
582
  WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
532
583
  AND m.role != 1
533
- GROUP BY m.symbol_id`,...t);return new Map(n.map(r=>[r.symbol_id,r.fan_in]))}function OP(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
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
534
585
  FROM mentions m
535
586
  JOIN chunks c ON m.chunk_id = c.id
536
587
  JOIN documents ref_d ON c.document_id = ref_d.id
537
588
  WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
538
589
  AND m.role != 1
539
590
  AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
540
- ${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 Gp(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 BP(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function HP(e){return!(Ot(e.symbol)||e.parentTypeName!==null&&!Ce(e.symbol))}function VP(e,t){return Ce(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}function Kp(e){let[t,n]=Xo(e,":"),r=t||"unknown",i=(o={})=>{let s=o.actionTier??qP(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??UP(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]=Xo(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]=Xo(n,":"),[a,c]=Xo(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 qP(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 UP(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 Xo(e,t){let n=e.indexOf(t);return n<0?[e,""]:[e.slice(0,n),e.slice(n+t.length)]}import{existsSync as XP,readFileSync as Yp}from"fs";function Zo(e,t){let n=WP(e,t)??GP(e,t)??zP(e,t)??JP(e,t);return KP(e,n,t)}function WP(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=Tc(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(Tc(e[i]??"")===r)return{start:n,end:i+1};return{start:n,end:e.length}}function Tc(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function GP(e,t){if(!Qo(e[t]??""))return null;let n=t;for(;n>0&&Qo(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&Qo(e[r]??"");)r+=1;return{start:n,end:r}}function Qo(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function zP(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(Yo(o)!==null)break;if(_c(o)!==null)return null;n-=1}if(n<0)return null;let r=Yo(e[n]??"");if(r===null)return null;let i=n+1;for(;i<e.length;){let o=e[i]??"",s=Yo(o);if(s!==null){if(s<=r)break;i+=1;continue}if(_c(o)!==null)break;i+=1}return{start:n,end:i}}function Yo(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function JP(e,t){let n=e[t]??"";if(Qp(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&Xp(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&Xp(e[i]??"");)i+=1;return{start:r,end:i}}function Xp(e){return _c(e)===null}function _c(e){return e.trim().length===0?"blank":Qp(e)?"heading":Tc(e)?"fence":Qo(e)?"table":Yo(e)!==null?"list":null}function Qp(e){return/^#{1,6}\s+/.test(e.trim())}function KP(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(`
541
- `).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function Dn(e,t){return t.filter(n=>e.includes(n))}var vr={classifyCitation:QP,citationContexts:YP,citationKindLabel:eN,citationRemediation:tN,referenceTargets:nN};function QP(e){let t=e.join(`
542
- `).toLowerCase(),n=[],r=Dn(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=Dn(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=Dn(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 YP(e,t,n){let r;try{r=Yp(`${e.config.projectRoot}/${t}`,"utf-8").split(/\r?\n/)}catch{return[]}let i=n.flatMap(ZP),o=[];for(let s=0;s<r.length;s+=1){let a=r[s]??"";i.some(c=>a.includes(c))&&o.push(Zo(r,s))}return o}function ZP(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 eN(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 tN(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 nN(e,t,n){let r=zo(n),i=new Set;for(let o of t)rN(e,o,r.get(o)??[])&&i.add(o);return i}function rN(e,t,n){if(n.length===0)return!1;if(!iN.test(t))return!0;let r=`${e.config.projectRoot}/${t}`;if(!XP(r))return!0;let i=Yp(r,"utf-8").split(/\r?\n/),o=oN(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 iN=/\.(?:[cm]?[jt]sx?)$/i;function oN(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&sN(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function sN(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}import{existsSync as Zp,readFileSync as $c}from"fs";import{join as Si}from"path";var bi=/\.(?:md|mdx|rst|txt)$/i;function aN(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var cN=3,ef=/[A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6}\b/g;function Ac(e,t={}){let{doc:n,limit:r=20,minCoupling:i=cN}=t,o=dN(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&&!nf(e,a)||n!==void 0&&!Zp(Si(e.config.projectRoot,a)))continue;let c=Math.max(0,...o.changeTimes.get(a)??[]),l=lN(e,a),u=new Map,{resolved:d,broken:m,citations:f}=fN(e,a,o.tracked,o.trackedBySuffix,o.everSeenInHistory),h=new Map(f.map(y=>[y.file,y.contexts]));for(let y of d){if(y===a||bi.test(y))continue;let S=(o.changeTimes.get(y)??[]).filter(v=>v>c).length;S!==0&&u.set(y,{file:y,evidence:"reference",coChanges:0,changesSinceDocUpdate:S,...Fc("reference",l),citationContexts:h.get(y)})}for(let[y,S]of o.coupling.get(a)??[]){if(S<i||!o.tracked.has(y))continue;let v=(o.changeTimes.get(y)??[]).filter(N=>N>c).length;if(v===0)continue;let k=u.get(y);k?(k.evidence="both",k.coChanges=S,Object.assign(k,Fc("both",l))):u.set(y,{file:y,evidence:"co-change",coChanges:S,changesSinceDocUpdate:v,...Fc("co-change",l)})}if(u.size===0&&m.length===0)continue;let g=[...u.values()].sort((y,S)=>S.changesSinceDocUpdate-y.changesSinceDocUpdate);s.push({doc:a,docLastChangedAt:c,staleness:g.reduce((y,S)=>y+S.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,r)}}function lN(e,t){let n;try{n=$c(Si(e.config.projectRoot,t),"utf8").slice(0,6e3)}catch{return{docIntent:"unknown",reasons:["doc text unavailable"]}}let r=`${t}
543
- ${n}`.toLowerCase(),i=Dn(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=Dn(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 Fc(e,t){return{actionTier:uN(e,t.docIntent),docIntent:t.docIntent,docIntentReasons:t.reasons}}function uN(e,t){return t==="historical-note"?"support":e==="co-change"?"signal":"direct"}function dN(e){let t=Yt(e);if(!t)return null;let n=kc(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=>bi.test(u)),l=a.filter(u=>!bi.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=>bi.test(s)),everSeenInHistory:o,historyCommitCount:t.commits.length,tracked:n,trackedBySuffix:rf(n)}}function tf(e,t){if(t.size===0)return[];let n=kc(e)??new Set,r=rf(n),i=mN(t,r),o=[];for(let s of n){if(!nf(e,s))continue;let a=sf(e,s);if(!a)continue;let c=pN(a,t,i,n,r);if(c.size===0)continue;let l=[...new Set([...c.values()].flatMap(f=>[...f]))],u=of(e,s,l),d=[...c].map(([f,h])=>({file:f,contexts:es([...h].flatMap(g=>u.get(g)??[])).slice(0,3)})).filter(f=>f.contexts.length>0),m=[...c.keys()];if(m.length>0){let f=m.sort();o.push({doc:s,cited:f,citations:d,citedClaims:es(d.flatMap(h=>h.contexts)).slice(0,3)})}}return o}function nf(e,t){return bi.test(t)&&!aN(t)&&Zp(Si(e.config.projectRoot,t))}function rf(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 mN(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 pN(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 fN(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=of(e,t,a),l=new Map,u=(d,m)=>{let f=c.get(m);if(!f||f.length===0)return;let h=l.get(d)??[];h.push(...f),l.set(d,es(h).slice(0,3))};for(let d of a){if(n.has(d)){o.add(d),u(d,d);continue}let m=r.get(d);if(m&&m.length===1){o.add(m[0]),u(m[0],d);continue}m&&m.length>1||i.has(d)&&s.add(d)}return{resolved:o,broken:[...s],citations:[...l].map(([d,m])=>({file:d,contexts:m}))}}function of(e,t,n){let r;try{r=$c(Si(e.config.projectRoot,t),"utf-8").split(/\r?\n/)}catch{return new Map}let i=new Set(n),o=new Map;for(let s=0;s<r.length;s+=1){let a=r[s]??"";for(let c of a.matchAll(ef)){let l=c[0].replace(/^\.?\//,"");if(!i.has(l))continue;let u=Zo(r,s);if(u.length===0)continue;let d=o.get(l)??[];d.push(u),o.set(l,es(d).slice(0,3))}}return o}function es(e){let t=[];for(let n of new Set(e))t.some(r=>gN(r,n))||t.push(n);return t}function gN(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}function sf(e,t){let n;try{n=$c(Si(e.config.projectRoot,t),"utf-8")}catch{return null}let r=Ye(e,t,n),i=Mt(e,"doc-path-tokens",t,r);if(i!==null)try{return JSON.parse(i)}catch{}let o=[...new Set([...n.matchAll(ef)].map(s=>s[0].replace(/^\.?\//,"")))];return jt(e,"doc-path-tokens",t,r,JSON.stringify(o)),o}import{existsSync as IE,readFileSync as DE,writeFileSync as PE}from"fs";import{isAbsolute as NE,join as EE}from"path";var le={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 xi from"path";function Pn(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 Mc(e,t){if(e===t)return"ok";let n=ts(e),r=ts(t);return n&&r?hN(n,r)?"ok":"violation":yN(e,t)}function af(e,t){let n=ts(Pn(e)),r=ts(Pn(t));return!!n&&!!r}function ts(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function hN(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 yN(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 Nn(e,t){let{scope:n,minDeviation:r=5}=t??{},i=t?.semantic!==!1,s=new T(e).fileDependencyGraph(n),a=kN(e,n);return CN([...bN(e,s,a,{semantic:i}),...SN(s),...xN(s,r)])}function bN(e,t,n,r){let i=[];for(let[o,s]of t){if(Nt(o))continue;let a=n.get(o)??new Set;for(let c of s)if(!Nt(c)&&!a.has(c)){if(r.semantic&&NN(e,o,c)||EN(e,o,c)||TN(e,o,c)||PN(c)||FN(e,o,c)||_N(c))continue;i.push({file:o,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${o} 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 i}function SN(e){let t=[],n=DN(e);for(let[r,i]of e){if(Nt(r))continue;let o=Pn(r);for(let s of i){if(Nt(s))continue;let a=Pn(s);if(o===a)continue;let c=Mc(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 xN(e,t){let n=[];for(let[r,i]of vN(e)){let o=i.filter(a=>!Nt(a));if(o.length<t)continue;let s=RN(e,o);for(let a of o)for(let c of e.get(a)??[])Nt(c)||(s.get(c)??0)===1&&xi.dirname(c)!==r&&xi.dirname(c)!==xi.dirname(r)&&(af(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 CN(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 vN(e){let t=new Map;for(let n of e.keys()){let r=xi.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function RN(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Nt(i)||n.set(i,(n.get(i)??0)+1);return n}function kN(e,t){let n=new Map;return wN(e,n,t),IN(e,n),n}function wN(e,t,n){for(let r of LN(e,n))cf(e,t,r.from_file,r.to_file)}function LN(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
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
544
595
  FROM mentions m
545
596
  JOIN chunks c ON m.chunk_id = c.id
546
597
  JOIN documents d1 ON c.document_id = d1.id
@@ -556,31 +607,31 @@ ${n}`.toLowerCase(),i=Dn(r,["historical note","historical record","history note"
556
607
  WHERE d1.id != d2.id
557
608
  AND m.role != 1
558
609
  ${e.pathExclusionsFor("d1","d2")}
559
- ${n}`)}function IN(e,t){new T(e).scanSourceReferences({paths:j(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},r=>{r.target.relativePath!==r.sourceFile&&(e.isIgnored(r.target.relativePath)||cf(e,t,r.sourceFile,r.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 DN(e){let t=new Map;for(let[r,i]of e){if(Nt(r))continue;let o=Pn(r);for(let s of i){if(Nt(s))continue;let a=Pn(s);if(o===a||Mc(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 PN(e){return e.includes("types")||e.endsWith(".d.ts")}function NN(e,t,n){let r=ti(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function EN(e,t,n){let r=he(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function TN(e,t,n){let r=he(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function _N(e){return e.endsWith(".vue")}function FN(e,t,n){let r=he(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 Nt(e){let t=J(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||$N(xi.basename(e)))}function $N(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 lf,extname as uf}from"path";function ns(e,t,n,r,i,o){let s=new Set;MN(e,t,n,r)&&s.add(i);for(let a of o)a.value&&AN(s,a.label,a.value);return[...s].slice(0,6)}function AN(e,t,n){let r=jN(n);t.endsWith("name")&&ON(r)&&e.add(`${t} has type-guard boundary shape`);for(let i of r){let o=BN.get(i);o&&e.add(`${t} has ${o} term: ${i}`)}}function MN(e,t,n,r){if(n<=0)return!1;let i=Qe(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(Hr(s)===r)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function jN(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 ON(e){return e.some(t=>HN.has(t))&&e.some(t=>VN.has(t))}var BN=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"]]),HN=new Set(["can","has","is","should"]),VN=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function En(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new T(e);return ze({candidates:()=>YN(s,n,r),orderCandidates:Mo,scanLimit:o,prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>qN(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function qN(e,t,n){let r=QN(n);if(r.size!==1||!ta(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=UN(e,t,i),s=GN(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:q(t),forwardsTo:i.symbol,forwardsToShort:b(i.symbol),forwardsToFile:i.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:WN(a,o,s)}}function UN(e,t,n){return ns(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:lf(t.relativePath,uf(t.relativePath))},{label:"callee module",value:lf(n.file,uf(n.file))}])}function WN(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(KN);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 GN(e,t){return zN(e,t)?gr(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:ie(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function zN(e,t){let n=Qe(e,t.relativePath);if(n.length===0)return!1;let r=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
560
- `);return ZN.test(r)?!0:JN(n,A(t.symbol))}function JN(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${XN(t)}\\b`);return e.some(r=>n.test(r))}function KN(e){return e.includes("public surface")}function XN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function QN(e){let t=e.some(r=>ce(r.symbol))?e.filter(r=>ce(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function YN(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:3,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0})}var ZN=/^\s*export\s+(?:default\s+)?(?:(?:async\s+)?function\b|(?:const|let|var)\b)/m;function Tn(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 T(e),u=l.scopedDefinitions(n),d=mE(l,n),m={high:0,medium:1,low:2};return ze({candidates:()=>eE(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(f,h)=>q(h)-q(f)||f.relativePath.localeCompare(h.relativePath),scanLimit:a,prepare:f=>{let h=rE(f),g=nE(e,l,f,h,{semantic:c}),y=f.filter(S=>{let v=rs(e,S,g,h);return v.realConsumers.length<=1&&!v.transitivelyReachable&&df(S,v.realConsumers.length,d)});return{consumerFileMap:g,singletonBackedClassIds:sE(e,l,u,y,{semantic:c}),candidateIndex:h}},evaluate:(f,h)=>{if(h.singletonBackedClassIds.has(f.symbolId))return null;let g=rs(e,f,h.consumerFileMap,h.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!df(g.definition,g.realConsumers.length,d))return null;let y=iE(e,g);return!s&&y.confidence==="low"?null:y},orderResults:(f,h)=>m[f.confidence]-m[h.confidence]||h.loc-f.loc||f.file.localeCompare(h.file)||f.startLine-h.startLine,limit:o})}function eE(e,t,n,r){return n.filter(i=>i.isTypeLike&&q(i)>=r.minLoc).filter(i=>q(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>J(i.relativePath)!=="test").filter(i=>!ie(e,i.symbol,i.relativePath)).filter(i=>!pE(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function tE(e,t,n){return Ln(e,t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function nE(e,t,n,r,i){let o=tE(t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(l=>{let u=rs(e,l,o,r);return u.realConsumers.length<=1&&!(u.realConsumers.length>0&&jc(l.relativePath))}),a=i.semantic&&s.length>0?Ao(o,mt(e,s)):o,c=s.filter(l=>rs(e,l,a,r).realConsumers.length<=1);return Ao(a,t.sourceFallbackCallerFiles(c))}function rE(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=A(n.symbol);i&&r.set(i,n)}return t}function rs(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}=qo(e,t,o),l=fE(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function iE(e,t){let n=pf(e,t.definition.relativePath,t.definition.startLine),r=jc(t.definition.relativePath)?!0:gE(e,t.definition),{confidence:i,reason:o}=hE(t.realConsumers.length,n,r),s=oE(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:q(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 oE(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 sE(e,t,n,r,i){let o=cE(e,aE(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=Ln(t,s,{semantic:i.semantic}),c=new Set;for(let{singleton:l,classId:u}of o)uE(e,l,a)&&c.add(u);return c}function aE(e){let t=new Map;for(let n of e){let r=A(n.symbol);r&&t.set(mf(n.relativePath,r),n)}return t}function cE(e,t,n){let r=[];for(let i of n){let o=lE(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function lE(e,t,n){if(pf(e,n.relativePath,n.startLine)!=="class")return null;let r=A(n.symbol);if(!r)return null;let i=dE(e,n.relativePath,r);return i?t.get(mf(n.relativePath,i))??null:null}function uE(e,t,n){let r=A(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!fc(e,o,r))}function mf(e,t){return`${e}\0${t}`}function dE(e,t,n){let r=F(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 mE(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function pE(e){let t=ge(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 jc(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 df(e,t,n){return!(jc(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function fE(e,t,n,r){let i=ra(e,t.relativePath),o=A(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 pf(e,t,n){let r=F(e,t);if(!r)return"other";let i=r.split(`
561
- `),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 gE(e,t){let n=F(e,t.relativePath);if(!n)return!1;let r=A(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
562
- `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function hE(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 Rr,extname as is}from"path";function _n(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new T(e),a=kE(s.fileDependencyGraph(n));return ze({candidates:()=>bE(s,n,r),orderCandidates:Mo,scanLimit:o,prepare:c=>({callerFileMap:Ln(s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>yE(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function yE(e,t,n,r){let i=SE(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=xE(e,n.symbolId,o);if(!s)return null;let a=CE(t,e,o,n.symbol,s);if(a&&nr(a.symbol))return null;let{fanIn:c,source:l}=vE(r.callerFileMap,r.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=LE(e,n,o,a);return{symbol:n.symbol,shortName:b(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:q(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?b(a.symbol):Rr(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function bE(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:2,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0})}function SE(e,t,n,r){let i=Rr(n.relativePath,is(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>Rr(s,is(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return qo(e,n,o).realConsumers}function xE(e,t,n){return e.get(`SELECT c.start_line, c.end_line
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
563
614
  FROM mentions m
564
615
  JOIN chunks c ON m.chunk_id = c.id
565
616
  JOIN documents d ON c.document_id = d.id
566
617
  WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
567
- LIMIT 1`,t,n)}function CE(e,t,n,r,i){let o=e.definitionsForFile(n),s=RE(t,n,r,i.start_line,i.end_line);return Be(o,s)}function vE(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:wE(t,n),source:"file"}}function RE(e,t,n,r,i){let o=A(n);if(!o)return r;let s=It(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 kE(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 wE(e,t){let n=e.get(t)??0;if(n>0)return n;let r=Rr(t,is(t)),i=0;for(let[o,s]of e)o!==t&&Rr(o,is(o))===r&&s>i&&(i=s);return i}function LE(e,t,n,r){return ns(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):Rr(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var TE=75e3,_E=5e3,FE=2500;function $E(e){let t=Fe(e);return t.symbols>=TE||t.documents>=_E?FE:void 0}var AE=".scipquery-baseline.json";function os(e,t){return t&&NE(t)?t:EE(e.config.projectRoot,t??AE)}function Oc(e,t={}){let{scope:n}=t,r=$E(e),i=[],o=Dt(e,{scope:n,...le.dead,scanLimit:r});for(let s of o.symbols)De(e,s.relativePath)||ie(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of xn(e,{scope:n,...le.isolated,scanLimit:r}))De(e,s.relativePath)||ie(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of Sn(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${ME(s.path)}`);for(let s of Pt(e,{scope:n,...le.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of wn(e,{scope:n,...le.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of _n(e,{scope:n,...le.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of En(e,{scope:n,...le.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of Tn(e,{scope:n,...le.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of Nn(e,{scope:n,...le.drift}).results)s.kind!=="pattern-deviation"&&i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return[...new Set(i)].sort()}function ME(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 Bc(e,t={}){let n=Oc(e,{scope:t.scope}),r=os(e,t.path);return PE(r,JSON.stringify({version:1,findings:n},null,2)+`
568
- `),{path:r,findingCount:n.length}}function Ci(e,t={}){let n=os(e,t.path);if(!IE(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let r=JSON.parse(DE(n,"utf-8")),i=new Set(r.findings??[]),o=Oc(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 jE=5;function vi(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??gt(e,{base:n}),d={available:u.note!==Nc,base:n,changedFiles:u.changedFiles,helpersChecked:0,skipped:[],findings:[]};if(!d.available||u.changedFiles.length===0)return d;let m=new T(e),f=new Set(u.changedFiles),h=new Map(u.renamedFiles.map(R=>[R.to,R.from])),g=t.baseContentAt??hi(e.config.projectRoot,n,yi(u)),y=UE(m,f,h,g);if(y.length===0)return d;let S=y.slice(0,s);y.length>s&&(d.note=`helper scoring capped at ${s} of ${y.length} new symbols`);let v=uc(e,{minCallees:Math.min(3,i),scanLimit:c,semantic:l}),k=dc(v),N=m.calleeMap(S,{semantic:l}),w=S.map(R=>({def:R,callees:Bo((N.get(R.symbolId)??[]).map($=>$.symbol))}));for(let{def:R,callees:$}of w){let I=b(R.symbol);if($.size<i){d.skipped.push({helperShortName:I,helperFile:R.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let z=qE($,k);if(z===0){d.skipped.push({helperShortName:I,helperFile:R.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let xe=WE(e,R.symbolId);if(xe.length===0){d.skipped.push({helperShortName:I,helperFile:R.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let Oe=OE({candidateIndex:k,changed:f,helperCallees:$,helperFile:R.relativePath,helperSymbol:R.symbol,minContainment:r,minSiteCoverage:o,migratedFiles:xe});Oe.length!==0&&(Oe.sort((Ne,$t)=>ff($t.migrationScope)-ff(Ne.migrationScope)||$t.containment-Ne.containment||$t.siteCoverage-Ne.siteCoverage||Ne.file.localeCompare($t.file)),d.findings.push({helperSymbol:R.symbol,helperShortName:I,helperFile:R.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:$.size,specificHelperCalleeCount:z,migratedFiles:xe.sort(),leftovers:Oe.slice(0,jE)}))}return d.findings.sort((R,$)=>($.leftovers[0]?.containment??0)-(R.leftovers[0]?.containment??0)||R.helperFile.localeCompare($.helperFile)),d.findings=d.findings.slice(0,a),d}function OE(e){let t=[],n=BE(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=ep(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=HE(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 ff(e){return e==="same-scope"?2:e==="unknown"?1:0}function BE(e,t,n){let r=new Set([...Hc(t),...Vc(A(e))]);for(let i of n)for(let o of Hc(i))r.add(o);return r}function HE(e,t,n){let r=new Set([...Hc(n),...Vc(A(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 VE=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 Hc(e){return Vc(e.replace(/\.[^.]+$/,""))}function Vc(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!VE.has(t))}function qE(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function UE(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${GE(i.leaf)}\\b`).test(s)})}function WE(e,t){return e.all(`SELECT DISTINCT ref_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
569
620
  FROM mentions m
570
621
  JOIN chunks c ON m.chunk_id = c.id
571
622
  JOIN documents ref_d ON c.document_id = ref_d.id
572
623
  WHERE m.symbol_id = ?
573
624
  AND m.role != 1
574
- ${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}function GE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ri(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=t.files===void 0?null:new Set(t.files),s=new T(e);return ze({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}).filter(a=>zE(a.relativePath)&&(o===null||o.has(a.relativePath))),scanLimit:i,evaluate:a=>{let c=ae(e,a.relativePath)?.callables.find(d=>d.startLine===a.startLine&&d.endLine===a.endLine);if(!c||c.params.length===0||c.params.some(d=>!d.simple)||c.paramsEndLine>=c.endLine)return null;let l=It(e,a.relativePath),u=[];for(let d=c.params.length-1;d>=0;d--){let m=c.params[d];if(m.name===""||m.name.startsWith("_")||JE(l.get(m.name),c.paramsEndLine,c.endLine))break;u.unshift(m.name)}return u.length===0?null:{symbol:a.symbol,shortName:b(a.symbol),file:a.relativePath,startLine:a.startLine,endLine:a.endLine,paramCount:c.paramCount,unusedTrailing:u}},orderResults:(a,c)=>c.unusedTrailing.length-a.unusedTrailing.length||a.file.localeCompare(c.file)||a.startLine-c.startLine,limit:r})}function zE(e){let t=W(e);return t==="typescript"||t==="tsx"||t==="javascript"}function JE(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}var as=["echo","incomplete-migration","co-change-partner","doc-reference","unused-params","new-dead","baseline"];function ki(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=gt(e,{base:n}),f=Cr(e,{base:n,plan:m}),h=f.changedFiles,g=new Set(h),y=new Set(m.changedFileLines),S=hi(e.config.projectRoot,n,yi(m,h)),v=xT(e.config.projectRoot,n,m,S),k={base:n,changedFiles:h,changedSymbols:f.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],rootCauseGroups:[],note:f.summary.note};if(h.length===0)return k;let N=(w,R)=>{if(d.has(w)){k.skipped.push({check:w,reason:"skipped via --skip"});return}R()};return N("echo",()=>tT(e,f.changedSymbols,g,v,o,a,l,u,k)),N("incomplete-migration",()=>uT(e,n,m,s,l,u,S,k)),N("co-change-partner",()=>dT(e,g,r,i,k)),N("doc-reference",()=>hT(e,g,y,m.changedRanges,k)),N("unused-params",()=>yT(e,h,k)),N("new-dead",()=>bT(e,f.changedSymbols,v,k)),c&&N("baseline",()=>RT(e,k)),ZE(k,e.config.suppressions??[]),k.rootCauseGroups=XE(k.findings),k}function XE(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=QE(i.severity,n.severity),i.actionTier=YE(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||ss(r.severity)-ss(n.severity)||n.groupKey.localeCompare(r.groupKey))}function QE(e,t){return ss(t)>ss(e)?t:e}function ss(e){return e==="error"?2:e==="warning"?1:0}function YE(e,t){return e?t&&gf(t)>gf(e)?t:e:t}function gf(e){return e==="direct"?2:e==="signal"?1:0}function ZE(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let r of e.findings){let i=t.find(o=>eT(o,r));i?e.suppressed.push({finding:r,suppression:i}):n.push(r)}e.findings=n}function eT(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 kr(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function tT(e,t,n,r,i,o,s,a,c){c.checksRun.push("echo");for(let l of t.slice(0,i)){if(r(l))continue;let u=di(e,l.symbol,{minSimilarity:o,limit:5,scanLimit:s,semantic:a}),d=[];for(let g of u){let y=g.fileA===l.file?g.fileB:g.fileA,S=g.fileA===l.file?g.shortNameB:g.shortNameA,v=g.fileA===l.file?g.symbolB:g.symbolA;n.has(y)||d.push({otherFile:y,otherShort:S,otherSymbol:v,similarity:g.similarity,similarityBasis:g.similarityBasis??"callees",sharedEvidence:g.sharedCallees})}if(d.length===0)continue;let m=d[0],f=Fn("echo",l.symbol,l.file,...d.map(g=>`${g.otherSymbol}|${g.otherFile}`).sort()),h=nT(l,d);kr(c,{id:f,groupKey:f,actionTier:h,check:"echo",severity:"warning",evidence:"heuristic",confidence:m.similarity,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(d.map(g=>g.otherFile))].sort(),message:aT(l,d),why:cT(l,d),remediation:lT(h,l.shortName,m.otherShort)})}t.length>i&&c.skipped.push({check:"echo",reason:`echo check capped at ${i} of ${t.length} changed symbols`})}function nT(e,t){return t.some(r=>rT(e.symbol,r))?"direct":"signal"}function rT(e,t){if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let n=A(e),r=A(t.otherSymbol);return!n||!r?!1:n===r?!0:sT(t.sharedEvidence)?!1:iT(n,r)}function iT(e,t){let n=hf(e),r=hf(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 hf(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 oT=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function sT(e){return e.length>=3&&e.every(t=>oT.has(t.toLowerCase()))}function aT(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 cT(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 lT(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 uT(e,t,n,r,i,o,s,a){let c=vi(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(y=>`${y.shortName} (${y.file}, ${Math.round(y.containment*100)}% helper / ${Math.round(y.siteCoverage*100)}% site, ${y.migrationScope})`).join(", "),d=l.leftovers.map(y=>`${y.shortName}: ${y.migrationScope} (${y.migrationScopeReasons[0]})`).join("; "),m=[...l.migratedFiles,...l.leftovers.map(y=>y.file)],f=l.leftovers.length===0?void 0:Math.max(...l.leftovers.map(y=>Math.min(y.containment,y.siteCoverage))),h=l.leftovers.some(y=>y.migrationScope==="possible-subtype"),g=Fn("incomplete-migration",l.helperSymbol,l.helperFile,m.join("|"));kr(a,{id:g,check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:f,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:h?`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 dT(e,t,n,r,i){let o=Ap(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,f=l?c.changesA:c.changesB,h=f>0?c.together/f:0;if(h<r||Lc(m)||Lc(d)||!yf(`${e.config.projectRoot}/${m}`))continue;let g=`${d}|${m}`;if(s.has(g))continue;s.add(g);let y=Fn("co-change-partner",d,m,String(c.together)),S=Ic(d,m),v=Dc({fileA:d,fileB:m,together:c.together,confidence:h,commitScope:c.commitScope,recency:c.recency,subjectContext:c.subjectContext},S,(a??=Pc(e))(d,m)),k=[d,m].sort().join("|");i.findings.push({id:y,check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${k}`,confidence:h,file:d,relatedFiles:[m],sourceAnalyzer:"co-change",rootCauseKey:k,partnerClass:S.partnerClass,partnerClassReasons:S.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(h*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(h*100)}% of changes to the edited side.`,`History context: ${mT(c)}.`,`Subject context: ${pT(c.subjectContext)}.`,...fT(c),`Partner class: ${S.partnerClass} (${S.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 mT(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${gT(e.lastTogetherAt)}`}function pT(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 fT(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 gT(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function hT(e,t,n,r,i){i.checksRun.push("doc-reference");let o=vr.referenceTargets(e,t,r);if(o.size!==0)for(let s of tf(e,o)){if(n.has(s.doc))continue;let a=s.citedClaims.length>0?s.citedClaims:vr.citationContexts(e,s.doc,s.cited),c=vr.classifyCitation(a),l=Fn("doc-reference",s.doc,s.cited.join("|"));kr(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 ${vr.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:vr.citationRemediation(c.citationKind,s.doc)})}}function yT(e,t,n){n.checksRun.push("unused-params");for(let r of Ri(e,{files:t,limit:50})){let i=Fn("unused-params",r.symbol,r.file,r.unusedTrailing.join("|"));kr(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 bT(e,t,n,r){r.checksRun.push("new-dead");let i=new T(e);for(let o of t){if(n(o)||o.fanIn>0||i.fileKind(o.file)==="test"||De(e,o.file)||ie(e,o.symbol,o.file)||ST(o.symbol))continue;let s=Fn("new-dead",o.symbol,o.file);kr(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 ST(e){if(ee(e)!=="type")return!1;let t=A(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function xT(e,t,n,r){let i=new Map(n.renamedFiles.map(s=>[s.to,s.from])),o=r??hi(e,t,yi(n));return s=>{let a=i.get(s.file)??s.file,c=A(s.symbol);if(!c)return!1;let l=o(a);return l!==null&&CT(l,c)}}function CT(e,t){return new RegExp(`\\b${vT(t)}\\b`).test(e)}function vT(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function RT(e,t){if(!yf(os(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=Ci(e);for(let r of n.newFindings){let i=Kp(r),o=Fn("baseline",r);kr(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 Fn(e,...t){return`SQ${KE("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}var kT=.7,bf=.62,Sf=.45;function qc(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=Fp(e);if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let c=wT(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic}).map(u=>ET(u,s,n)).filter(u=>u!==null);c.sort((u,d)=>(u.kind===d.kind?0:u.kind==="echo"?-1:1)||d.similarity-u.similarity||u.echoFile.localeCompare(d.echoFile)||u.echoSymbol.localeCompare(d.echoSymbol)||u.domain.localeCompare(d.domain));let l=c.slice(0,r).map(TT);return{available:!0,windowCommits:n,findings:l,rootCauseGroups:_T(l)}}function wT(e,t){let n=$T(t.limit),r=[...LT(e,{scope:t.scope,minSimilarity:t.minSimilarity??kT,limit:n,scanLimit:t.scanLimit,semantic:t.semantic})],i=eo(e,{scope:t.scope});return i.react&&r.push(...IT(e,{scope:t.scope,minSimilarity:t.minSimilarity??bf,limit:n,scanLimit:t.scanLimit}),...DT(e,{scope:t.scope,minSimilarity:t.minSimilarity??Sf,limit:n,scanLimit:t.scanLimit})),i.vue&&r.push(...PT(e,{scope:t.scope,minSimilarity:t.minSimilarity??bf,limit:n,scanLimit:t.scanLimit}),...NT(e,{scope:t.scope,minSimilarity:t.minSimilarity??Sf,limit:n,scanLimit:t.scanLimit})),r}function LT(e,t){return Pt(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic}).map(n=>({domain:"callable",basis:n.similarityBasis??"callees",symbolA:n.shortNameA,fileA:n.fileA,symbolB:n.shortNameB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:n.sharedCallees,sharedCallees:n.sharedCallees}))}function IT(e,t){return ls(e,t,{query:Cn,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 ls(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:AT(...n.evidenceBuckets(r)),sharedCallees:[]}))}function DT(e,t){return ls(e,t,{query:vn,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 PT(e,t){return ls(e,t,{query:Rn,domain:"vue-component",basis:"vue-template",symbolA:n=>cs(n.fileA),symbolB:n=>cs(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function NT(e,t){return ls(e,t,{query:kn,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>cs(n.fileA),symbolB:n=>cs(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 ET(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 TT(e){let t=xf(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function xf(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 _T(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??xf(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:FT(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 FT(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 $T(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function AT(...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 cs(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var MT=Y("suppression-inventory",{clearGroups:["whole-project"]});function us(e){return MT.get(e,()=>jT(e))}function jT(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 Ie(e)){let o=F(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=Hr(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=OT(a);t[c]+=1}}return{total:r,byCategory:t,byFile:n}}function OT(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as BT}from"fs";import{join as HT}from"path";function wi(e,t,n={}){let r=B(e,t);if(!r)return null;let i=new T(e),o=GT(qT(e,r.relativePath,r.startLine,r.endLine),VT(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:UT(e,r.symbolId),fanOut:WT(c,r.relativePath)}}function VT(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function qT(e,t,n,r){try{return BT(HT(e.config.projectRoot,t),"utf-8").split(`
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(`
575
626
  `).slice(n,r+1).join(`
576
- `)}catch{return""}}function UT(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
627
+ `)}catch{return""}}function B_(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
577
628
  FROM mentions m
578
629
  JOIN chunks c ON m.chunk_id = c.id
579
- WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function WT(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function GT(e,t){let n=mn(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 Li(e,t,n={}){let r=B(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=Kt(e,r,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?b(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=zT(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 zT(e,t,n,r){let i=Sr(Me(e,t,{limit:30,semantic:r.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=Sr(Ue(e,t,{limit:30,semantic:r.semantic})),s=o.length>0?o:Sr(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function wr(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=B(e,t);return o?r==="backward"?JT(e,o,i,{semantic:n.semantic!==!1}):KT(e,o,{semantic:n.semantic!==!1}):null}function JT(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=Me(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=ar(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 KT(e,t,n){let r=new Set,i=[],o=new T(e);for(let s of Kt(e,t,{semantic:n.semantic})){if(i.length>=30)break;let a=s.enclosingSymbol??Be(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=ar(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 Uc(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=!QT(t),a=s?ri(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?li(e,t,{semantic:o}):null,l=s?wi(e,t,{semantic:o}):null,u=s?Li(e,t,{semantic:o}):null,d=s?wr(e,t,{direction:"backward",maxDepth:i,semantic:o}):null,m=s?wr(e,t,{direction:"forward",maxDepth:i,semantic:o}):null,f=s?fi(e,t,{maxDepth:r,scope:n.scope}):[],h=gi(e,t,{semantic:o}),g=ii(e,t),y=oi(e,t),S=si(e,t),v=ai(e,t),k={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||d!==null||m!==null||f.length>0,file:h!==null||g.length>0||y.length>0,module:S.files.length>0||S.symbols.length>0||v.length>0},N=[];!k.symbol&&!k.file&&!k.module&&N.push("No symbol, file, or module matched target.");let w=h?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:k,history:XT(e,w),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:d,forwardSlice:m,affected:f,changeSurface:h,deps:g,rdeps:y,system:S,surface:v,warnings:N}}function XT(e,t){let n={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return n;let r=Go(e);if(!r)return n;let i=In(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:us(e).byFile.get(t)??0}}function QT(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}function Ii(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new T(e);return ze({candidates:()=>s.productionCallableDefinitions({scope:n,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,prepare:a=>({callerMap:s.crossFileCallerMap(a,{semantic:t?.semantic!==!1}),calleeMap:s.calleeMap(a,{semantic:t?.semantic!==!1})}),evaluate:(a,c)=>YT(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function YT(e,t,n){let r=e.endLine-e.startLine+1;if(r<n)return null;let i=t.callerMap.get(e.symbolId)?.size??0,o=t.calleeMap.get(e.symbolId)??[],s=o.filter(l=>l.file!==e.relativePath),a=new Set(s.map(l=>`${l.symbol}|${l.file}`)).size,c=new Set(o.map(l=>`${l.symbol}|${l.file}`)).size;return{symbol:e.symbol,shortName:b(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:a,calleeCount:c,score:Math.round(r/50*(i/5)*Math.max(a/5,1)*100)/100}}function Et(e){return e.scoreCount??e.count}function Rf(e){let t=n_(e),{breakdown:n,pressure:r}=r_(e),i=vf(n,"risk"),o=vf(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:Et(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Et(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:Et(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:ZT(e),validation:t_(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function ZT(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:e_(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 e_(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:ht(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function t_(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?ht(i/r.size):0,c=s>0?ht(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let f=0;for(let g of m)f+=t[g]?.fixChanges??0;let h=ht(f/m.size);l[u]={flaggedFiles:m.size,fixDensity:h,lift:c>0?ht(h/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?ht(a/c):null,byCategory:l}}function ht(e){return Math.round(e*100)/100}function kf(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function ds(e,t="existing shared infrastructure discount"){let n=Et(e);return Math.abs(n-e.count)<.01?"":` (${kf(n)} score-weighted after ${t})`}function Di(e,t){let n=Et(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${kf(n)} score-weighted)`}function n_(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${ds(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${ds(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${ds(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`+ds({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 Cf={"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 vf(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 r_(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(w,R,$)=>{R>0&&r.push({axis:w,points:R,detail:$,kind:Cf[w]??"hygiene"})},s=(w,R,$,I,z,xe,Oe)=>{let Ne=Math.max(I,1);if($<=Ne)return;let $t=$/Ne,zs=Math.min(z,Math.ceil(Math.log2($t)*xe));if(zs<=0)return;let kb=Cf[w]??"hygiene";i.push({axis:w,category:R,kind:kb,count:$,threshold:ht(Ne),ratio:ht($t),extraPenalty:zs}),o(w,zs,`${$} ${Oe} exceed pressure threshold ${ht(Ne)} (${ht($t)}x)`)},a=e.dead.count/n;o("dead-code",Math.min(20,Math.round(a*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let c=e.isolated.count/n;o("isolated",Math.min(10,Math.round(c*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),o("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let l=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(l)),`${e.similarCount} similar function pair(s)`);let u=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(u)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let d=Et(e.reactHookCandidates),m=d/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(m)),Di(e.reactHookCandidates,"duplicated React behavior pair(s)"));let f=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(f/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let h=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(h)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let g=Et(e.vueComposableCandidates),y=g/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(y)),Di(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let S=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(S/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let v=Et(e.wrappers);o("wrappers",Math.min(3,v),Di(e.wrappers,"wrapper candidate(s)"));let k=Et(e.passthroughs);o("passthroughs",Math.min(3,k),Di(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 N=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(N*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 w=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(w/10)),Di({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:w},"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 w=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",w,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",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",v,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",k,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 i_}from"v8";var o_=64*1024*1024;function Wc(){let e=globalThis.gc;if(!e)return;let t=i_();t.heap_size_limit-t.used_heap_size<o_||e()}var s_=50,a_=75e3,c_=5e3,wf=2500,Lf=50,l_=10,Lr=["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"],u_={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:p_(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:f_(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:g_(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:h_(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:b_(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:S_(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:x_(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:C_(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:v_(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:R_(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:y_(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:k_(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:w_(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:L_(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:P_(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:N_(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:I_(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:D_(e,n)})};function Gc(e,t,n={}){return zc(e,[t],n)[0]}function zc(e,t,n={}){return d_(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>u_[s](e,n.scope,o,r))})}function d_(e,t,n){let r=Fe(e),i=E_(r,t);try{return n(r,i)}finally{Aa(e,{semanticProvider:!0}),Wc()}}function Jc(e){return Rf(m_(e))}function m_(e){let t=be(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:be(e,"dead").dead,isolated:be(e,"isolated").isolated,realCycleCount:be(e,"cycles").realCycleCount,similarCount:be(e,"similar").similarCount,reactComponentDuplicates:be(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:be(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:be(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:be(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:be(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:be(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:be(e,"extract-candidates").extractCount,wrappers:be(e,"wrapper-candidates").wrappers,passthroughs:be(e,"passthrough-candidates").passthroughs,stale:be(e,"stale-abstractions").stale,drift:be(e,"drift").drift,complexity:be(e,"complexity-hotspots").complexity,gitEvidence:If(e,"git-evidence")?.gitEvidence??null,suppressions:If(e,"suppressions")?.suppressions??null}}function If(e,t){return e.find(n=>n.phase===t)}function be(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function p_(e,t,n){return ue(e,n,"dead",()=>{let r=Dt(e,{scope:t,...le.dead,scanLimit:n.candidateScanLimit});return ms(F_(e,r.symbols))})}function f_(e,t,n){return ue(e,n,"isolated",()=>{let r=xn(e,{scope:t,...le.isolated,scanLimit:n.candidateScanLimit});return ms($_(e,r))})}function g_(e,t,n){return ue(e,n,"cycles",()=>Sn(e,{scope:t}).filter(i=>i.kind==="real").length)}function h_(e,t,n){return ue(e,n,"similar",()=>Pt(e,{scope:t,...le.similar,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function y_(e,t,n){return ue(e,n,"extract-candidates",()=>wn(e,{scope:t,...le.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function b_(e,t,n){return ue(e,n,"react-component-duplicates",()=>{let r=Cn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Kc(r)})}function S_(e,t,n){return ue(e,n,"react-hook-candidates",()=>{let r=vn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Nf(r,M_)})}function x_(e,t,n){return ue(e,n,"react-large-component-pressure",()=>{let r=mi(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return A_(r)})}function C_(e,t,n){return ue(e,n,"vue-component-duplicates",()=>{let r=Rn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Kc(r)})}function v_(e,t,n){return ue(e,n,"vue-composable-candidates",()=>{let r=kn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Nf(r,j_)})}function R_(e,t,n){return ue(e,n,"vue-large-view-pressure",()=>{let r=pi(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return ms(r)})}function k_(e,t,n){return ue(e,n,"wrapper-candidates",()=>{let r=_n(e,{scope:t,...le.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Pf(r,O_)})}function w_(e,t,n){return ue(e,n,"passthrough-candidates",()=>{let r=En(e,{scope:t,...le.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Pf(r,B_)})}function L_(e,t,n){return ue(e,n,"stale-abstractions",()=>{let r=Tn(e,{scope:t,...le.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 I_(e,t){return ue(e,t,"git-evidence",()=>{let n=Go(e);if(!n)return null;let r=In(e,void 0,{limit:t.candidateResultLimit}),i={};for(let[o,s]of n)i[o]={changes:s.changes,fixChanges:s.fixChanges};return{amplification:_p(e),hiddenCoupling:{pairCount:r.findings.length,scoreCount:Xc(r.findings.reduce((o,s)=>o+Df(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:Df(o),subjectContext:o.subjectContext}))},fileStats:i}})}function D_(e,t){return ue(e,t,"suppressions",()=>{let n=us(e);return{total:n.total,byCategory:{...n.byCategory}}})}function P_(e,t,n){return ue(e,n,"drift",()=>{let r=Nn(e,{scope:t,...le.drift}),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 N_(e,t,n){return ue(e,n,"complexity-hotspots",()=>{let r=Ii(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>s_).length}})}function E_(e,t){let n=e.symbols>=a_||e.documents>=c_,r=t?Number.POSITIVE_INFINITY:Lf,i=t?Number.POSITIVE_INFINITY:l_;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:wf,candidateResultLimit:r,complexityResultLimit:i,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${wf} symbols and reported their top ${Lf} findings. Enable full mode for unbounded candidate counts.`]}}function T_(e,t){t.releaseCachesBetweenPhases&&(Aa(e),Wc())}function ue(e,t,n,r){__(n);try{return r()}finally{T_(e,t)}}function __(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function F_(e,t){return t.filter(n=>!De(e,n.relativePath)&&!ie(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function $_(e,t){return t.filter(n=>!De(e,n.relativePath)&&!ie(e,n.symbol,n.relativePath))}function ms(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 Pf(e,t){return{...ms(e),scoreCount:Xc(e.reduce((r,i)=>r+t(i),0))}}function A_(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 Kc(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 Nf(e,t){return{...Kc(e),scoreCount:Xc(e.reduce((r,i)=>r+t(i),0))}}function M_(e){let t=e.sharedHooks.length>0,n=Ef({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:Tf(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function j_(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=Ef({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:Tf(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function Ef(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!Ff.has(_f(t))).length+Math.min(e.functions.length,3)}function Tf(e,t,n){let r=[...e,...t,...n].map(_f);return r.length>0&&r.every(i=>Ff.has(i))}function _f(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function O_(e){return e.actionTier==="signal"?.25:1}function B_(e){return e.actionTier==="signal"?.25:1}function Df(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 Xc(e){return Math.round(e*100)/100}var Ff=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 Qc(e,t,n,r={}){let i=B(e,t),o=B(e,n);if(!i||!o)return null;let s=new Set(Me(e,i,{semantic:r.semantic}).map(y=>y.symbol)),a=new Set(Me(e,o,{semantic:r.semantic}).map(y=>y.symbol)),c=[];for(let y of s)a.has(y)&&c.push(y);let l=[];for(let y of s)a.has(y)||l.push(y);let u=[];for(let y of a)s.has(y)||u.push(y);let d=new Set([...s,...a]),m=d.size>0?c.length/d.size:0,f;d.size===0?f="Neither function calls other tracked symbols. There is no callee-pattern evidence for consolidation; inspect the source bodies directly.":c.length===0?f="These functions do not share any callees. They are not a callee-based consolidation candidate.":l.length===0&&u.length===0?f="These functions have identical tracked callee sets. They are a strong structural match, but identical callees do not prove interchangeable semantics; inspect signatures, control flow, and return values before consolidating.":l.length===0?f="A's tracked callees are a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic before replacing A with B.":u.length===0?f="B's tracked callees are a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic before replacing B with A.":l.length<=2&&u.length<=2?f=`Create a shared function with the ${c.length} common callees. Pass the ${l.length+u.length} divergent callees as parameters or strategy callbacks.`:f=`Extract the ${c.length} shared callees into a common helper. Each function calls the helper plus its own unique logic (${l.length} callees in A, ${u.length} in B).`;let h=i.endLine-i.startLine+1,g=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:b(i.symbol),file:i.relativePath,loc:h},symbolB:{symbol:o.symbol,shortName:b(o.symbol),file:o.relativePath,loc:g},similarity:m,sharedCallees:c.map(b),uniqueToA:l.map(b),uniqueToB:u.map(b),consolidationStrategy:f}}import{readFileSync as $f}from"fs";import{extname as H_,join as Af}from"path";function Yc(e,t,n={}){let{context:r=0}=n,i=V_(t);if(i)return U_(e,i.filePath,i.startLine,i.endLine,r);let o=B(e,t);return o?q_(e,o,r):null}function V_(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 q_(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=Af(e.config.projectRoot,t.relativePath),o;try{o=$f(i,"utf-8")}catch{return null}let s=o.split(`
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(`
580
631
  `),a=Math.max(0,t.startLine-n),c=Math.min(s.length-1,t.endLine+n),l=s.slice(a,c+1).join(`
581
- `);return{symbol:t.symbol,shortName:b(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:r?.language??Mf(t.relativePath),source:l}}function U_(e,t,n,r,i){let o=Ee(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=Af(e.config.projectRoot,s.relative_path),c;try{c=$f(a,"utf-8")}catch{return null}let l=c.split(`
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(`
582
633
  `),u=Math.max(0,n-1-i),d=Math.min(l.length-1,r-1+i),m=l.slice(u,d+1).join(`
583
- `);return{symbol:`${s.relative_path}:${n}-${r}`,shortName:`${s.relative_path}:${n}-${r}`,relativePath:s.relative_path,startLine:u,endLine:d,language:s.language??Mf(s.relative_path),source:m}}function Mf(e){switch(H_(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 Zc(e,t={}){let{scope:n,limit:r}=t,i=new T(e),o=Y_([...W_(e,n),...J_(e,i,n)]);return Z_(o),r?o.slice(0,r):o}function W_(e,t){let n=[];for(let r of G_(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||xa(e,r.barrel_path)||F(e,r.barrel_path)&&Co(e,r.barrel_path).length===0)continue;let i=z_(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,...Of(e,r.barrel_path)})}return n}function G_(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
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
584
635
  barrel_d.id AS barrel_doc_id,
585
636
  barrel_d.relative_path AS barrel_path,
586
637
  gs.id AS symbol_id,
@@ -610,7 +661,7 @@ ${n}`.toLowerCase(),i=Dn(r,["historical note","historical record","history note"
610
661
  -- Only function-level symbols (ending with ().), not module-level
611
662
  AND gs.symbol LIKE '%().'
612
663
  ${n}
613
- ORDER BY barrel_d.relative_path, gs.symbol`)}function z_(e,t){return e.get(`SELECT
664
+ ORDER BY barrel_d.relative_path, gs.symbol`)}function q0(e,t){return e.get(`SELECT
614
665
  SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
615
666
  SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
616
667
  FROM (
@@ -639,7 +690,7 @@ ${n}`.toLowerCase(),i=Dn(r,["historical note","historical record","history note"
639
690
  AND consumer_d.id != ?
640
691
  ${e.pathExclusionsFor("consumer_d")}
641
692
  GROUP BY consumer_d.id
642
- )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function J_(e,t,n){let r=[];for(let i of K_(e,n))Bf(e,i,i)>0||r.push(...X_(e,t,i));return r}function K_(e,t){return j(e,{scope:t,includeIgnored:!1}).filter(n=>Co(e,n).length>0||Kr(e,n).length>0)}function X_(e,t,n){let r=Co(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>jf(e,t,n,o.sourcePath)),i=Kr(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>jf(e,t,n,o.sourcePath));return[...r,...i]}function jf(e,t,n,r){let i=Q_(t,r);return i?[{barrelFile:n,symbol:i.symbol,shortName:b(i.symbol),originalFile:r,barrelConsumers:0,directConsumers:Bf(e,r,n),...Of(e,n)}]:[]}function Of(e,t){return gr(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 Bf(e,t,n){let r=new Set;for(let i of j(e,{includeIgnored:!1}))if(i!==n)for(let o of he(e,i))o.sourcePath===t&&r.add(i);return r.size}function Q_(e,t){let n=e.definitionsForFile(t);return n.find(r=>ee(r.symbol)==="method")??n[0]??null}function Y_(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 Z_(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function tl(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new T(e),s=e0(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n);if(s.length===0||!t0(e,s))return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let a={references:Hf(),callees:Hf()},c=[],l=0,u=To(e,s);for(let d of s){let m=ps(d,Jt(e,d).map(y=>y.file)),f=ps(d,(u.get(d.symbolId)??[]).map(y=>y.file));if(m.size===0&&f.size===0)continue;l+=1;let h=ps(d,bn(e,d).map(y=>y.file)),g=ps(d,(o.calleeMap([d],{semantic:!1}).get(d.symbolId)??[]).map(y=>y.file));Vf(a.references,d,"references",h,m,c),Vf(a.callees,d,"callees",g,f,c)}return c.sort((d,m)=>m.cheapOnly.length+m.oracleOnly.length-(d.cheapOnly.length+d.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?el(l/s.length):0,scores:["references","callees"].map(d=>r0(d,a[d])),topDisagreements:c.slice(0,i)}}function Hf(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0}}function e0(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 t0(e,t){let n=t[0];if(!n)return!1;try{return zt(e,n.relativePath).availability().available}catch{return!1}}function ps(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function Vf(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 n0={references:!0,callees:!1};function r0(e,t){let n=t.oracleTotal>0?t.agreed/t.oracleTotal:1,r=t.cheapTotal-t.agreed;return{question:e,comparedSymbols:t.comparedSymbols,precision:n0[e]&&t.cheapTotal>0?el(t.agreed/t.cheapTotal):null,recall:el(n),unverified:r}}function el(e){return Math.round(e*1e3)/1e3}function nl(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o}=t,s=t.semantic!==!1,a=o0(e,i0(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:s}),c=a0(a);return i?c.slice(0,i):c}function i0(e,t){let n=ut(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>q(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>q(i)-q(r)||r.relativePath.localeCompare(i.relativePath)),We(n,t.scanLimit)}function o0(e,t,n){let r=new Map;for(let i of t){let o=c0(e,i,n);if(!o)continue;let s=r.get(o)??[];s.push(s0(i)),r.set(o,s)}return r}function s0(e){return{symbol:e.symbol,shortName:b(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:q(e)}}function a0(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 c0(e,t,n){if(n.semantic){let o=ym(e,t);if(o)return o}let r=l0(t.documentation),i=r?m0(r):null;return i||p0(u0(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function l0(e){return an(cn(e))}function u0(e,t,n,r,i){let o=F(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=g0(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,d0(u)))return u}if(u&&u.includes("("))return u}return null}function d0(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||zr(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function m0(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 p0(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${qf(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=f0(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 f0(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 g0(e,t,n,r){let i=qf(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 qf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{existsSync as Kf}from"fs";import{join as $0}from"path";import h0 from"better-sqlite3";var y0=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".scipquery-cache","__pycache__",".venv","venv"],Ir=class{db;config;pathFilter;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new h0(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`(
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`(
643
694
  EXISTS (
644
695
  SELECT 1
645
696
  FROM defn_enclosing_ranges local_der
@@ -656,8 +707,8 @@ ${n}`.toLowerCase(),i=Dn(r,["historical note","historical record","history note"
656
707
  AND local_m.role = 1
657
708
  ${this.pathExclusionsFor("local_d").trimStart()}
658
709
  )
659
- )`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>y0.flatMap(r=>[`AND ${n}.relative_path NOT LIKE '${r}/%'`,`AND ${n}.relative_path NOT LIKE '%/${r}/%'`])).join(`
660
- `)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.db.prepare(t).all(...n)}get(t,...n){return this.db.prepare(t).get(...n)}close(){this.db.close()}};import b0 from"ignore";import{readFileSync as S0,existsSync as rl}from"fs";import{dirname as il,isAbsolute as Uf,join as ol,relative as x0,resolve as C0}from"path";function Zt(e){let t=b0(),n=!1,r=v0(e);for(let i of r)try{let o=S0(i,"utf-8");t.add(o),n=!0}catch{}return n||t.add(R0),{isIgnored:i=>Wf(t,e,i),filter:i=>i.filter(o=>!Wf(t,e,o))}}function v0(e){let t=[],n=ol(e,".gitignore");rl(n)&&t.push(n);let r=il(e),i=0;for(;r!==il(r)&&i<5;){let o=ol(r,".gitignore");if(rl(o)&&t.push(o),rl(ol(r,".git")))break;r=il(r),i++}return t}var R0=`
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=`
661
712
  # Dependencies
662
713
  node_modules/
663
714
  vendor/
@@ -714,30 +765,30 @@ Thumbs.db
714
765
 
715
766
  # Type definitions (often noise in queries)
716
767
  *.d.ts
717
- `;function Wf(e,t,n){let r=k0(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function k0(e,t){if(!t||t===".")return null;if(!Uf(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=Uf(t)?t:C0(e,t),r=x0(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readFileSync as w0,writeFileSync as Gf,existsSync as Pi,mkdirSync as L0}from"fs";import{isAbsolute as I0,join as yt,relative as D0,resolve as al}from"path";import{createHash as P0}from"crypto";import{homedir as N0}from"os";var Ni=".scipquery.json",E0={enabled:!1,debounceMs:3e4,cooldownMs:6e4,gitPollMs:2e3,autoRefresh:!0,ignore:[]},T0=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"];function Pe(e){let t=yt(e,Ni);if(!Pi(t))return{};try{let n=w0(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 ${Ni} at ${t}: ${r}`,{cause:n}):new Error(`unable to read ${Ni} at ${t}: ${r}`,{cause:n})}}function Dr(e,t={}){let n=[],r=new Set(T0);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=al(t.projectRoot,a),u=D0(t.projectRoot,l);u.startsWith("..")||I0(u)?n.push({level:"error",path:c,message:"Project path must stay inside the project root."}):Pi(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(!F0(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&&!Pi(yt(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&&!Pi(yt(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 Pr(e){return{...E0,...e.watch}}function _0(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return sl(n);if(t?.dbPath)return sl(al(e,t.dbPath));let i=process.env.XDG_CACHE_HOME||yt(N0(),".cache"),o=P0("sha256").update(al(e)).digest("hex").slice(0,12),s=yt(i,"scip-query","projects",o);return sl(s)}function bt(e,t){let n=_0(e,t);return{cacheDir:n,dbPath:yt(n,"index.db"),indexPath:yt(n,"index.scip"),metaPath:yt(n,"meta.json")}}function zf(e,t){let n=yt(e,Ni);return Pi(n)||Gf(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4,gitPollMs:2e3,autoRefresh:!0}},null,2)+`
718
- `),n}function Jf(e,t){let n=yt(e,Ni),r=Pe(e),i={...r,suppressions:[...r.suppressions??[],t]},o=Dr(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 Gf(n,JSON.stringify(i,null,2)+`
719
- `),{path:n,suppressionCount:i.suppressions?.length??0}}function sl(e){return L0(e,{recursive:!0}),e}function F0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function de(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function Nr(e=de()){let t=Pe(e),n=bt(e,t),r=process.env.SCIP_QUERY_INDEX_DB??(Kf(n.dbPath)?n.dbPath:$0(e,"index.db"));return{projectRoot:e,config:t,paths:n,dbPath:r}}function Er(e){return Nr(e).dbPath}function A0(){let{projectRoot:e,config:t,paths:n,dbPath:r}=Nr();Kf(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=Zt(e);return new Ir(i,o)}function Je(e){let t=A0();try{return e(t)}finally{t.close()}}function cl(e,t){return t.concat([e])}function $n(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 Xf(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 M0(e)}}function M0(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}import{spawnSync as zY}from"child_process";function Qf(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function je(e){return e+1}function Re(e,t){return`${je(e)}-${je(t)}`}function Se(e,t,n){return`${e}:${Re(t,n)}`}function fs(e,t=180){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var D={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 H0=O0(import.meta.url),{version:gs}=X0(),Ei="__health-phase",hs="__diff-impact-batch",V0=10,q0=4,U0=8,W0=75e3,G0=5e3,Yf=2500,z0=4,J0=10,K0=10*1024*1024,Zf=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),eg=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]);function X0(){for(let e of["../package.json","../../package.json"])try{return H0(e)}catch{}return{version:"0.0.0"}}function Tr(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
720
- `)}function Q0(e){let t=Fe(e);return t.symbols>=W0||t.documents>=G0}function ys(e,t,n,r={}){return Q0(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 ${Yf} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:Yf,semantic:!1}):{semantic:!0}}async function bs(e){let t=Je(s=>Y0(s,e)),n=new Map,r=Lr.filter(s=>Z0(s,t)?!0:(n.set(s,tF(s)),!1)),i=eF(r);return(await tg(i,iF(i.length),s=>nF(s,e))).flat().forEach(s=>n.set(s.phase,s)),Jc(Lr.map(s=>n.get(s)))}function Y0(e,t){return eo(e,{scope:t.scope})}function Z0(e,t){return Zf.has(e)?t.react:eg.has(e)?t.vue:!0}function eF(e){let t=[Zf,eg],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 tF(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 nF(e,t){if(e.length===1)return rF(e[0],t).then(o=>[o]);let n=e.join(","),r=process.argv[1]??ul(import.meta.url),i=[n];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),dl({cliPath:r,command:Ei,args:i,label:`Health phases "${n}"`})}function rF(e,t){let n=process.argv[1]??ul(import.meta.url),r=[e];return t.scope&&r.push("--scope",t.scope),t.full&&r.push("--full"),dl({cliPath:n,command:Ei,args:r,label:`Health phase "${e}"`})}function dl(e){return new Promise((t,n)=>{let r=e.maxBuffer??K0,i=j0(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?`:
721
- ${m}`:""}`));return}try{t(JSON.parse(Buffer.concat(o).toString("utf8")))}catch(f){n(new Error(`${e.label} returned invalid JSON: ${f instanceof Error?f.message:f}`))}})})}async function tg(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 iF=ig({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:z0,defaultMaximum:J0});function ng(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
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(`
722
773
  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)
723
- `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${$n(e.overview.indexSizeBytes)}
724
- `),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: ${ll(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: ${ll(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: ${ll(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(`
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(`
725
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(`
726
- Top Complexity Hotspots:`);for(let r of e.topComplexity)console.log(` ${r.score.toFixed(1).padStart(6)} ${r.symbol}`)}if(aF(e),sF(e),e.scoreBreakdown.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(`
727
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(`
728
- No issues found. Codebase is clean.`)}function ll(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${oF(t)} score-weighted)`}function oF(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function sF(e){if(e.pressure.length!==0){console.log(`
729
- 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 aF(e){let t=e.axes;if(console.log(`
730
- 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 rg(e){let t=Je(i=>{let o=gt(i,{base:e.base});return o.note?{kind:"complete",result:Cr(i,{base:e.base})}:o.changedFiles.length===0?{kind:"complete",result:Cr(i,{base:e.base})}:{kind:"batched",plan:o}});if(t.kind==="complete")return t.result;let n=Qf(t.plan.changedFiles,V0),r=await tg(n,cF(n.length),i=>dF(i,e));return Ko(t.plan.changedFiles,r)}var cF=ig({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:q0,defaultMaximum:U0});function ig(e){return(t,n=process.env,r=B0)=>lF(t,n,r,e)}function lF(e,t,n,r){let i=t[r.envKey],o=uF(n,r),s=i?parseInt(i,10):o;return!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e)}function uF(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 dF(e,t){let n=process.argv[1]??ul(import.meta.url),r=[];return t.base&&r.push("--base",t.base),dl({cliPath:n,command:hs,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function og(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:"),D.list(e.changedSymbols,t=>` ${t.file} ${t.shortName} (fan-in: ${t.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
731
- Affected consumer files:`),D.list(e.affectedConsumers,t=>` ${t.file} (${t.consumedSymbols} symbol(s))`))}var Ti=cl,x=(e=>parseInt(e,10)),_i=(e=>{let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}),st=parseFloat,Ss=parseInt;function p(e,t,n,...r){return r.length>0?{flags:e,description:t,parser:n,defaultValue:r[0]}:{flags:e,description:t,parser:n}}function ml(){return p("--json","Output as JSON for programmatic consumption")}function _(e=[]){return e.some(t=>t.flags==="--json")?e:[...e,ml()]}function L(e,t=[]){return{category:e,examples:t}}import{execFileSync as rj}from"child_process";import{existsSync as Vi,mkdirSync as ij,readFileSync as oj,writeFileSync as _h}from"fs";import{homedir as sj}from"os";import{dirname as aj,join as Ar}from"path";import{execFileSync as KA}from"child_process";import{closeSync as XA,copyFileSync as QA,existsSync as Ps,mkdirSync as _l,mkdtempSync as YA,openSync as ZA,readFileSync as Ns,renameSync as Ai,rmSync as Mi,writeFileSync as sh}from"fs";import{basename as Ds,dirname as at,extname as eM,join as xt}from"path";import{execFileSync as sg}from"child_process";import{existsSync as cg,readFileSync as gF}from"fs";import{platform as Fi,arch as lg}from"os";import{dirname as ag,join as xs}from"path";import{fileURLToPath as hF}from"url";import{execFileSync as mF}from"child_process";import{platform as pF}from"os";var fF=pF()==="win32";function St(e){let t=fF?"where":"which";try{return mF(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var ug="v0.8.1",pl="https://github.com/scip-code/scip",yF={win32:{x64:xs("vendor","scip","win32-x64","scip.exe"),arm64:xs("vendor","scip","win32-arm64","scip.exe")}};function bF(){let e=ag(hF(import.meta.url));for(;;){let t=xs(e,"package.json");if(cg(t))try{if(JSON.parse(gF(t,"utf-8")).name==="scip-query")return e}catch{}let n=ag(e);if(n===e)return null;e=n}}function dg(){let e=yF[Fi()]?.[lg()];if(!e)return null;let t=bF();if(!t)return null;let n=xs(t,e);return cg(n)?n:null}function Cs(){return St("scip")?"scip":dg()}function $i(){return Cs()!==null}function SF(){let e=Fi(),t=lg(),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:`${pl}/releases/download/${ug}/${o}`,filename:o}}function fl(){let e=SF();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Fi()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
732
- `),console.log("Or download manually:")):Fi()==="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
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
733
784
  `),console.log("Upstream release page:")):console.log("Download from:"),console.log(e?` ${e.url}
734
- `:` ${pl}/releases/tag/${ug}
735
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function mg(e){let t=dg();if(t)return e(`Using bundled scip CLI at ${t}`),!0;if(Fi()==="darwin"&&St("brew")){e("Installing scip CLI via Homebrew...");try{if(sg("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),St("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(St("go")){e("Installing scip CLI via go install...");try{if(sg("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),St("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: ${pl}/releases`),!1}import xF from"better-sqlite3";import{execFileSync as CF}from"child_process";import{existsSync as vF,readdirSync as RF,readFileSync as kF}from"fs";import{extname as vs,join as pg}from"path";function en(e){let t=new Set((e.extensions??$u).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!vF(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Zt(e.projectRoot),r=wF(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new xF(e.dbPath);try{let o=IF(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
736
- VALUES (?, ?, NULL, ?)`),c=i.transaction(u=>{let d=0;for(let m of u){if(o.has(m))continue;let f=kF(pg(e.projectRoot,m),"utf-8"),h=s.run(DF(m),m,f);d+=Number(h.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 wF(e,t){let n=LF(e,t);if(n)return n;let r=[],i=o=>{let s=o?pg(e,o):e,a;try{a=RF(s,{withFileTypes:!0})}catch{return}for(let c of a){if(oa.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(vs(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function LF(e,t){try{return CF("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
737
- `).filter(r=>r&&t.has(vs(r).toLowerCase())).sort()}catch{return null}}function IF(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 DF(e){return vs(e).toLowerCase()===".vue"?"vue":vs(e).replace(/^\./,"").toLowerCase()||"source"}import{execFileSync as PF}from"child_process";import{existsSync as NF,readdirSync as gg}from"fs";import{extname as hg,join as yg}from"path";var EF=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),TF=[{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 Tt(e){let t=[],n=_F(e),r=MF(e);for(let i of TF){if(FF(e,i.files)){t.push(i.language);continue}if($F(n,i.globs)){t.push(i.language);continue}OF(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&fg(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&fg(t,"c"),t}function _F(e){try{return gg(e)}catch{return[]}}function FF(e,t){return t?.length?t.some(n=>NF(yg(e,n))):!1}function $F(e,t){return t?.length?e.some(n=>t.some(r=>AF(n,r))):!1}function AF(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 MF(e){let t=jF(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=gg(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=yg(i,s.name);if(s.isDirectory()){EF.has(s.name)||r.push(a);continue}let c=hg(s.name).toLowerCase();c&&n.add(c)}}return n}function jF(e){try{let t=PF("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(`
738
- `)){if(!r)continue;let i=hg(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function OF(e,t){return t?.length?t.some(n=>e.has(n)):!1}function fg(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as bg,readdirSync as BF}from"fs";import{join as gl}from"path";var HF={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",Sg(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",Sg(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=gl(e,"vendor","bin","scip-php"),r=gl(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",bg(r)?r:bg(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function An(e){return HF[e]}function Sg(e,t){let n;try{n=BF(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return gl(e,i);return null}import{readFileSync as VF,writeFileSync as qF}from"fs";import{create as hl}from"@bufbuild/protobuf";import{deserializeSCIP as UF,serializeSCIP as WF,DocumentSchema as GF,IndexSchema as zF,SymbolInformationSchema as JF}from"@c4312/scip";function KF(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=XF(e),n=QF(e.flatMap(i=>i.documents??[])),r=xg(e.flatMap(i=>i.externalSymbols??[]));return hl(zF,{metadata:t,documents:n,externalSymbols:r})}function yl(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>UF(VF(i))),r=KF(n);return qF(t,Buffer.from(WF(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function XF(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 QF(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,hl(GF,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:YF([...r.occurrences,...n.occurrences]),symbols:xg([...r.symbols,...n.symbols]),text:e$(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function YF(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 xg(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,hl(JF,{symbol:r.symbol,documentation:t$([...r.documentation,...n.documentation]),relationships:ZF([...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 ZF(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 e$(e,t){return e?t?e.length>=t.length?e:t:e:t}function t$(e){return[...new Set(e)]}import{execFileSync as n$}from"child_process";import{createHash as r$}from"crypto";import{readdirSync as i$,readFileSync as o$}from"fs";import{join as vg}from"path";function Cg(e){return(a$(e)??c$(e)).filter(t=>t&&!Rg(t)).sort()}function Mn(e,t={}){return(t.language?Cg(e).filter(r=>s$(r,t.language,t.markerFiles)):Cg(e)).map(r=>{let i=vg(e,r);try{let o=o$(i);return{path:r,size:o.byteLength,hash:r$("sha256").update(o).digest("hex")}}catch{return{path:r,size:-1,hash:"unreadable"}}})}function s$(e,t,n){let r=e.split("/").at(-1)??e;if(n?.includes(e)||n?.includes(r)||u$.has(r))return!0;let i=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return(d$[t]??[]).includes(i)}function a$(e){try{return n$("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
739
- `).filter(Boolean)}catch{return null}}function c$(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?vg(e,r):e,o;try{o=i$(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){Rg(a)||n.push(a);continue}t.push(a)}}return t}function Rg(e){return e.split("/").some(n=>l$.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var l$=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]),u$=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"]),d$={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 m$,writeFileSync as p$}from"fs";import{create as kg}from"@bufbuild/protobuf";import{deserializeSCIP as f$,DocumentSchema as g$,IndexSchema as h$,serializeSCIP as y$,SymbolRole as b$}from"@c4312/scip";function wg(e){let t;try{t=f$(m$(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=S$(t);return n.removedDefinitionOccurrences>0&&p$(e,Buffer.from(y$(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function S$(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&b$.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(kg(g$,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:kg(h$,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}import{existsSync as x$,readFileSync as C$,readdirSync as v$,statSync as R$}from"fs";import me from"path";var k$=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Lg(e,t=[]){let n=me.resolve(e),r=w$(n),i=t.flatMap(c=>L$(n,c)),o=D$([...r,...i]),s=P$(n,o)?[n,...o]:o,a=s.length>0?s:[n];return[...new Set(a.map(c=>E$(n,c)))].sort((c,l)=>c.localeCompare(l))}function w$(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=v$(r,{withFileTypes:!0})}catch{continue}for(let o of i){let s=me.join(r,o.name);if(o.isDirectory()){!k$.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&I$(s)&&t.push(me.dirname(s))}}return t}function L$(e,t){let n=t.trim();if(!n)return[];let r=me.resolve(e,n);if(!_$(e,r))return[];try{let i=R$(r);if(i.isDirectory())return[r];if(i.isFile()&&Ig(me.basename(r)))return[me.dirname(r)]}catch{return[]}return[]}function I$(e){if(!Ig(me.basename(e)))return!1;let t=Dg(e);return t?me.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function Ig(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function D$(e){let t=[...new Set(e.map(n=>me.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&T$(n,r)))}function P$(e,t){if(t.length===0||t.some(r=>me.resolve(r)===e))return!1;let n=me.join(e,"tsconfig.json");return x$(n)&&N$(n)}function N$(e){let n=Dg(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!me.extname(r))):!1}function Dg(e){try{let t=JSON.parse(C$(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function E$(e,t){let n=me.relative(e,t);return n?n.split(me.sep).join("/"):"."}function T$(e,t){let n=me.relative(e,t);return!!n&&!n.startsWith("..")&&!me.isAbsolute(n)}function _$(e,t){let n=me.relative(e,t);return!n.startsWith("..")&&!me.isAbsolute(n)}import{execFile as F$}from"child_process";import{existsSync as Rs,renameSync as Sl,rmSync as xl}from"fs";import{cpus as $$}from"os";import{join as Pg}from"path";function A$(e,t,n){if(!e.defaultOutputPath)return;let r=Pg(t,e.defaultOutputPath);n!==r&&Rs(r)&&Sl(r,n)}function M$(e,t,n){if(!e.defaultOutputPath)return null;let r=Pg(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return xl(i,{force:!0}),Rs(r)?(Sl(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function j$(e){e&&(xl(e.defaultOutputPath,{force:!0}),e.backupPath&&Rs(e.backupPath)&&Sl(e.backupPath,e.defaultOutputPath))}function O$(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 Ng(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=O$(o.length,r),c=await H$(o,a,l=>bl(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 bl(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 bl(l,t,n));return s.sort((l,u)=>e.findIndex(d=>d.id===l.id)-e.findIndex(d=>d.id===u.id))}async function bl(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),xl(e.scipPath,{force:!0});let r=M$(e.config,t,e.scipPath);try{await B$(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),A$(e.config,t,e.scipPath)}catch(i){let o=i instanceof Error?i.message:String(i),s=`${e.resolvedBinary} indexer failed: ${o.split(`
740
- `)[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{j$(r)}if(!Rs(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 B$(e,t,n){return new Promise((r,i)=>{F$(e,[...t],n,o=>{o?i(o):r()})})}async function H$(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 vl}from"child_process";import{existsSync as Cl,readFileSync as V$}from"fs";import{createRequire as q$}from"module";import{platform as U$}from"os";import{dirname as Eg,join as ks}from"path";var W$=q$(import.meta.url);function Rl(e){return[e.indexerBinary,...e.binaryAliases??[]]}function ws(e){let t=Rl(e);return t.length===1?t[0]:t.join(" or ")}function _r(e){for(let t of Rl(e))if(St(t))return t;return z$(e)}function Tg(e){return _r(e)!==null||G$(e)}function G$(e){return _g(e)!==null}function z$(e){let t=_g(e);if(!t)return null;let r=JSON.parse(V$(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return ks(Eg(t),r);for(let i of Rl(e)){let o=r[i];if(o)return ks(Eg(t),o)}return null}function _g(e){if(!e.bundledNpmPackage)return null;try{return W$.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function kl(e,t){for(let n of e.projectLocalBinaries??[]){let r=ks(t,n);if(Cl(r))return r}return null}function J$(e,t){return kl(e,t)??_r(e)}function Fg(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||wl(n,t))return t;let r=$g(n,t);return r?{...t,DOTNET_ROOT:r}:t}function Ls(e,t){let n=ws(e),r=t?J$(e,t):_r(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=K$(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function Is(e,t){let n=e.installMethods,r=ws(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(St(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{vl(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let o=_r(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 K$(e){if(wl(e,process.env))return{runnable:!0};let t=$g(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=Ag(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 $g(e,t){for(let n of Ag(t))if(wl(e,{...t,DOTNET_ROOT:n}))return n;return null}function Ag(e){let t=[],n=e.DOTNET_ROOT;if(n&&Cl(n)&&t.push(n),U$()==="darwin"&&St("brew"))try{let r=vl("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=ks(r,"libexec");Cl(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function wl(e,t){try{return vl(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import PA from"better-sqlite3";import{existsSync as NA,readFileSync as EA,writeFileSync as TA}from"fs";import{dirname as _A,join as FA,resolve as $A}from"path";import{readFileSync as X$,rmSync as Q$,statSync as Y$,mkdtempSync as Z$}from"fs";import{cpus as eA,tmpdir as tA}from"os";import{join as Ll}from"path";import{Worker as nA}from"worker_threads";function Mg(e){return e.length>=8&&Og(e.length)>1}function jg(e){let t=Og(e.vueFiles.length),n=iA(e.vueFiles),r=sA(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=Z$(Ll(tA(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=rA(),l=Date.now();try{for(let d=0;d<r.length;d++)new nA(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[d],resultPath:Ll(o,`${d}.json`),sharedBuffer:s}});for(;Atomics.load(a,0)<r.length;){if(Date.now()-l>c)throw new Error(`Vue reference workers timed out after ${(c/1e3).toFixed(0)}s`);Atomics.wait(a,0,Atomics.load(a,0),100)}let u=r.map((d,m)=>{let f=JSON.parse(X$(Ll(o,`${m}.json`),"utf-8"));if(!f.ok)throw new Error(`Vue reference worker failed: ${f.error}`);return f.result});return{occurrences:u.flatMap(d=>d.occurrences),skippedReferences:u.reduce((d,m)=>d+m.skippedReferences,0)}}finally{Q$(o,{recursive:!0,force:!0})}}function Og(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,eA().length-1));return Math.max(1,Math.min(e,n))}function rA(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function iA(e){let t=oA(),n=[];for(let r of e){let i=Bg(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 oA(){return Number.POSITIVE_INFINITY}function sA(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:aA(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 aA(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Bg(e.fileName)-e.startOffset)}function Bg(e){try{return Y$(e).size}catch{return 1}}import{createRequire as cA}from"module";import{existsSync as lA,readFileSync as Dl}from"fs";import{dirname as Hg,extname as uA,join as Vg,relative as dA,resolve as mA}from"path";import{pathToFileURL as pA}from"url";function fA(e){e.transaction(()=>{e.prepare(`
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(`
741
792
  DELETE FROM mentions
742
793
  WHERE chunk_id IN (
743
794
  SELECT c.id
@@ -752,12 +803,12 @@ Affected consumer files:`),D.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
752
803
  FROM documents
753
804
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
754
805
  )
755
- `).run()})()}function qg(e,t){return e.prepare(`
806
+ `).run()})()}function oh(e,t){return e.prepare(`
756
807
  SELECT relative_path AS relativePath
757
808
  FROM documents
758
809
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
759
810
  ORDER BY relative_path
760
- `).all().map(r=>mA(t,r.relativePath))}function Ug(e,t){let{vueCore:n,ts:r,volarTs:i}=gA(e),{parsed:o,vueOptions:s}=hA(n,r,t),a=Hg(t),c=n.createVueLanguagePlugin(r,o.options,s,f=>f),l=yA(n,r,c),u=bA(a,o),{languageServiceHost:d}=i.createLanguageServiceHost(r,r.sys,l,f=>f,u),m=r.createLanguageService(d);return{ts:r,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function gA(e){let t=cA(pA(Vg(e,"package.json")).href);return{vueCore:Il(t,"@vue/language-core",e),ts:Il(t,"typescript",e),volarTs:Il(t,"@volar/typescript",e)}}function hA(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,Hg(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function yA(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!lA(o))return;let s=Dl(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??kA(o))});return r.current=i,i}function bA(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Il(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 Wg(e,t,n){let r=SA(e);return i=>{let o=jn(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:xA(c.starts,a.line,2)}}function SA(e){let t=e.prepare(`
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(`
761
812
  SELECT
762
813
  d.relative_path AS relativePath,
763
814
  der.start_line AS startLine,
@@ -766,23 +817,23 @@ Affected consumer files:`),D.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
766
817
  FROM defn_enclosing_ranges der
767
818
  JOIN documents d ON d.id = der.document_id
768
819
  ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
769
- `).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 xA(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 Gg(e,t,n){let r=IA(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
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(`
770
821
  INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
771
822
  VALUES (?, ?, ?, ?)
772
- `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let u=jn(t,l),d=th(r.name,r.version,u);o.run(d,"default",7,`Vue component|${u}`);let m=DA(i,r,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function zg(e,t,n,r,i){return e.transaction(()=>(fA(e),CA(e,t,n,r),vA(e,i)))()}function CA(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
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(`
773
824
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
774
825
  VALUES (?, ?, ?, ?, X'00')
775
826
  `),s=e.prepare(`
776
827
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
777
828
  VALUES (?, ?, 1)
778
- `);for(let a of n){let c=r.get(a);if(!c)continue;let l=jn(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 Jg(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(Pl(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Kg(e){let t=new Set,n=[];for(let r of e){let i=Xg(r);t.has(i)||(t.add(i),n.push(r))}return n}function Xg(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function vA(e,t){let n=LA(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
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(`
779
830
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
780
831
  VALUES (?, ?, ?, ?, X'00')
781
832
  `),i=e.prepare(`
782
833
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
783
834
  VALUES (?, ?, 0)
784
- `),o=new Set,s=0,a=0;for(let c of t){let l=Xg(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*Qg(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 Yg(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Pl(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function RA(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 Zg(e,t){return jn(e,t).startsWith("node_modules/")}function jn(e,t){return dA(e,t).replaceAll("\\","/")}function kA(e){switch(uA(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 eh(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Dl(t,"utf-8"),r={text:n,lineStarts:wA(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:RA}}function wA(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function LA(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 IA(e){try{let t=JSON.parse(Dl(Vg(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 DA(e,t,n,r){let i=jn(n,r),o=th(t.name,t.version,i);return e.get(o)?.id??null}function th(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Nl(e){en({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=$A(e.projectRoot,e.tsconfig);if(!NA(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new PA(e.dbPath);try{let r=qg(n,e.projectRoot),i=FA(_A(e.dbPath),"augment-vue-meta.json"),o=nh(n,e.projectRoot,e.tsconfig),s=AA(i,o,e.onStatus);if(s)return s;let a=MA({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus});return BA(i,nh(n,e.projectRoot,e.tsconfig),a),a}finally{n.close()}}function AA(e,t,n){let r=OA(e,t);return r&&n?.(`Vue references unchanged; reused ${r.resolvedReferences} cached resolved references.`),r}function MA(e){let t=Gg(e.db,e.projectRoot,e.vueFiles),n=jA(e,t),r=Kg(n.occurrences),i=zg(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 jA(e,t){if(Mg(e.vueFiles))return jg({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=HA({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return VA({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function OA(e,t){try{let n=JSON.parse(EA(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function BA(e,t,n){TA(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
785
- `)}function nh(e,t,n){let r=e.prepare(`
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(`
786
837
  SELECT
787
838
  (SELECT COUNT(*) FROM documents) AS documents,
788
839
  (SELECT COUNT(*) FROM global_symbols) AS symbols,
@@ -791,40 +842,40 @@ Affected consumer files:`),D.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
791
842
  (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
792
843
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
793
844
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
794
- `).get();return{version:2,tsconfig:n,files:Mn(t),db:r}}function HA(e){let t=eh();return{projectRoot:e.projectRoot,context:Ug(e.projectRoot,e.configPath),symbolLookup:Wg(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function VA(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=qA(e,i);t.push(...o.occurrences),n+=o.skippedReferences}return{occurrences:t,skippedReferences:n}}function qA(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=jn(e.projectRoot,t.fileName),a=[...Qg(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:GA(a),processedStarts:new Set};return UA({...e,fileName:t.fileName,sourceInfo:i,sourceFile:s,map:o,tokenContext:c})}function UA(e){let t=[],n=0;for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start))continue;let i=Yg(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(c=>!Zg(e.projectRoot,c.fileName));if(!s){n++;continue}let a=Jg(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}rh(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a),e.tokenContext.processedStarts.add(r.start),WA(t,e,r,i,a)}return{occurrences:t,skippedReferences:n}}function WA(e,t,n,r,i){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let o of zA(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&&(rh(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i),t.tokenContext.processedStarts.add(o))}}function rh(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 GA(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function zA(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=JA(r,l.textSpan.start,o,i.text);u!==null&&a.push(u)}return a}function JA(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Pl(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function tn(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=tM(e),s=Date.now();_l(at(o.outputScip),{recursive:!0}),_l(at(o.outputDb),{recursive:!0});let a=e.languages??Tt(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=kM(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects}),l=await hM(xt(at(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),u=null;try{let d=nM({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r});if(d)return d;lM(i,r);let m=rM(o);return u=m.runDir,await iM({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:m,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r})}catch(d){throw fh(o.metaPath,$l({trigger:e.trigger,result:"failed",start:s,error:d instanceof Error?d.message:String(d)})),d}finally{u&&Mi(u,{recursive:!0,force:!0}),l()}}function tM(e){let t=e.outputScip??xt(e.projectRoot,"index.scip"),n=e.outputDb??xt(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:xt(at(n),"meta.json")}}function nM(e){if(e.opts.skipIfUnchanged===!1||!Ps(e.paths.outputScip)||!Ps(e.paths.outputDb)||!wM(e.paths.metaPath,e.fingerprint))return null;en({projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let t=Date.now()-e.start,n=$l({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return fh(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 rM(e){let t=YA(xt(at(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:xt(t,Ds(e.outputScip)),tempOutputDb:xt(t,Ds(e.outputDb)),tempMetaPath:xt(t,Ds(e.metaPath))}}async function iM(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:r,reusedLanguages:i}=await oM(e,t);i.length>0&&e.onStatus(`Reused ${i.length} cached language shard(s): ${i.join(", ")}`);let o=sM(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 oM(e,t){let n=aM(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}=uM({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 Ng(i,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:a}=mM(s,o),c=[...n,...a];return pM(c,o,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:c,skippedLanguages:o,reusedLanguages:[...r]}}function sM(e,t,n,r){cM(e.paths.outputDb,n),fM(n,e.tempPaths.tempOutputScip,e.onStatus),gM(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),en({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus});let i=$l({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:lh(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}),RM({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 aM(e){let t;try{t=JSON.parse(Ns(e.paths.metaPath,"utf-8"))}catch{return[]}if(t.version!==3||!t.languageFingerprints)return[];let n=[],r=lh(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects});for(let i of e.languages){let o=mh(e.paths.outputDb,i);Ps(o)&&Fr(t.languageFingerprints[i])===Fr(r[i])&&n.push({language:i,scipPath:o})}return n}function cM(e,t){for(let n of t){let r=mh(e,n.language);_l(at(r),{recursive:!0}),n.scipPath!==r&&QA(n.scipPath,r)}}function lM(e,t){if(!Cs()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
795
- Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!mg(t))throw new Error(`The scip CLI is required but could not be installed.
796
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function uM(e){let t=[],n=[],r=e.languages.map((i,o)=>({language:i,scipPath:e.languages.length>1?ch(e.tempOutputScip,i,o):e.tempOutputScip}));for(let{language:i,scipPath:o}of r){let s=dM({...e,language:i,scipPath:o});for(let a of s)"skipped"in a?ah(n,a.skipped):t.push(a.prepared)}return{preparedRuns:t,skippedLanguages:n}}function dM(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[El({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=Lg(e.projectRoot,e.typescriptProjects);return t.length===0?[El({...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)=>El({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:ch(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function El(e){let t=An(e.language),n=ws(t),r=kl(t,e.projectRoot);if(!r&&!Tg(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...`),!Is(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??_r(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:Fg(t,e.env,i)}}}function mM(e,t){let n=new Map;for(let i of e)if(i.skipped)ah(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)yl(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&Ai(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function ah(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 pM(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
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(`
797
848
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
798
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.
799
850
  `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
800
- `))}function fM(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),yl(e.map(r=>r.scipPath),t)):e[0].scipPath!==t&&Ai(e[0].scipPath,t)}function gM(e,t,n,r){if(r("Converting to SQLite..."),!Ps(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let i=wg(e);i.removedDefinitionOccurrences>0&&r(`Sanitized ${i.removedDefinitionOccurrences} invalid definition occurrences across ${i.touchedDocuments} documents before SQLite conversion.`);let o=Cs();if(!o)throw new Error("scip CLI is not available");KA(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 ch(e,t,n){let r=eM(e)||".scip",i=Ds(e,r);return xt(at(e),`${i}.${n+1}.${t}${r}`)}async function hM(e,t){for(let n=0;n<2;n++){let r=yM(e,t);if(r)return r;let i=bM(e);if(i&&SM(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),await CM(i.pid),Mi(e,{force:!0});continue}if(i&&!Fl(i.pid)){Mi(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${at(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${at(e)}.`)}function yM(e,t){let n;try{n=ZA(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 sh(n,JSON.stringify(r)+`
801
- `),()=>{try{XA(n)}finally{Mi(e,{force:!0})}}}function bM(e){try{let t=JSON.parse(Ns(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:at(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function SM(e,t){return e?.kind==="manual-cli"&&xM(t?.trigger)}function xM(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function CM(e){ih(e,"SIGTERM"),!await oh(e,2e3)&&(ih(e,"SIGKILL"),await oh(e,1e3))}function ih(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function oh(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!Fl(e))return!0;await vM(50)}return!Fl(e)}function Fl(e){try{return process.kill(e,0),!0}catch{return!1}}function vM(e){return new Promise(t=>setTimeout(t,e))}function RM(e){Tl(e.tempOutputScip,e.outputScip),Tl(e.tempOutputDb,e.outputDb),Tl(e.tempMetaPath,e.metaPath)}function Tl(e,t){Mi(`${t}.tmp-replace`,{force:!0}),Ai(e,`${t}.tmp-replace`),Ai(`${t}.tmp-replace`,t)}function kM(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:dh(n),typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:uh(n.typescriptProjects),files:Mn(e)}}function lh(e,t,n){return Object.fromEntries(t.map(r=>{let i=An(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:uh(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]};return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&dh(n),...o,files:Mn(e,{language:r,markerFiles:i})}]}))}function uh(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function dh(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function mh(e,t){return xt(at(e),"language-indexes",`${t}.scip`)}function wM(e,t){try{let n=JSON.parse(Ns(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&Fr(n.fingerprint)===Fr(t)&&Fr([...n.indexedLanguages??[]].sort())===Fr(t.languages)}catch{return!1}}function ph(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;sh(n,`${JSON.stringify(t,null,2)}
802
- `),Ai(n,e)}function fh(e,t){try{let n=JSON.parse(Ns(e,"utf-8"));if(n.version!==2&&n.version!==3)return;ph(e,{...n,lastRefresh:t})}catch{}}function $l(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 Fr(e){return JSON.stringify(e)}import{existsSync as gh,readFileSync as LM}from"fs";function On(e,t,n){let r=new Date().toISOString();if(!gh(n.dbPath))return{state:"missing",checkedAt:r,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!gh(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(LM(n.metaPath,"utf-8")),o=t.languages??Tt(e),s=IM(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 IM(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:DM(n.indexer?.typescript?.projects),files:Mn(e)}}function DM(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}import{execFileSync as JM}from"child_process";import{createRequire as PM}from"module";var NM=PM(import.meta.url);function hh(e,t=[]){let n=EM(),r=La(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 EM(){try{return NM.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as $r,spawnSync as xh}from"child_process";import{existsSync as _t,mkdtempSync as Ch,readFileSync as TM,readdirSync as _M,rmSync as vh,symlinkSync as FM,writeFileSync as $M}from"fs";import{tmpdir as Rh}from"os";import{join as Ke}from"path";var AM=3e5,MM=12;function Al(e,t,n={}){let r=Ml(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],batches:[]};let i=jM(t,r),o=n.timeoutMs??AM,s=HM(e,t),a=Ch(Ke(Rh(),"scip-cleanup-verify-")),c=[],l=new Set;try{$r("git",["-C",e,"worktree","add","--detach","--force",a,"HEAD"],{stdio:"ignore"}),VM(e,a);for(let u of r)for(let d of Sh(u,a,o).errorKeys)l.add(d);for(let u of t.batches){wh(a,u);let d=[];for(let m of r){let f=Sh(m,a,o);d.push(...f.rawErrors.filter(h=>!l.has(kh(h))))}if(d.length===0)c.push({depth:u.depth,status:"verified"});else{c.push({depth:u.depth,status:"failed",errors:d.slice(0,MM)});break}}}finally{try{$r("git",["-C",e,"worktree","remove","--force",a],{stdio:"ignore"})}catch{vh(a,{recursive:!0,force:!0})}}return{checkers:r.map(u=>u.label),uncoveredFiles:i,baselineErrors:l.size,dirtyOverlap:s,batches:c}}function jM(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 kh(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var yh=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"];function Ml(e){let t=[];if(_t(Ke(e,"tsconfig.json"))){let n=Ke(e,"node_modules",".bin","tsc");t.push(_t(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:yh}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:yh})}if(_t(Ke(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"]}),["pyproject.toml","setup.py","requirements.txt"].some(n=>_t(Ke(e,n)))){let n=OM();n&&t.push(n)}for(let n of BM(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:Ke(e,n,"..","target")}});return t}function OM(){return bh("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--select","E9,F821,F822","."],coversExtensions:[".py"]}:bh("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"]}:null}function bh(e){try{return xh(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}function BM(e){let t=[];if(_t(Ke(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=_M(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||_t(Ke(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function HM(e,t){let n;try{n=$r("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}let r=new Set(n.split(`
803
- `).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 VM(e,t){for(let n of["node_modules"]){let r=Ke(e,n),i=Ke(t,n);if(_t(r)&&!_t(i))try{FM(r,i,"junction")}catch{}}}function wh(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=Ke(e,r);_t(o)&&$M(o,qM(TM(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function jl(e,t){for(let n of t)wh(e,n)}function Lh(e,t){let n=Ch(Ke(Rh(),"scip-cleanup-patch-"));try{return $r("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),jl(n,t),$r("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{$r("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{vh(n,{recursive:!0,force:!0})}}}function Ol(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 Bl(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 qM(e,t,n={}){let r=e.split(`
804
- `),i=(n.rust===!0?UM(e):mn(e)).split(`
805
- `),o=new Set;for(let s of t){let a=WM(r,s.start),c=zM(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(`
806
- `)}function UM(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 WM(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 GM=200;function zM(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>GM)break}return n}function Sh(e,t,n){let r=xh(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??""}
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??""}
807
858
  ${r.stderr??""}`.split(`
808
- `).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(kh))}}var Ih={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"]},KM={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 Ct(e,t){let n=t.languages??Tt(e),r=n.map(s=>{let a=Ls(An(s),e);return{...a,language:s,resolvedBinary:a.resolvedBinary??void 0}}),i=n.includes("typescript")?{language:"typescript",...hh(e,t.semantic?.typescript?.tsconfigs)}:void 0,o=Ml(e).map(s=>({label:s.label,coversExtensions:s.coversExtensions}));return{languages:n,indexers:r,semantic:i,checkers:o,gitAvailable:ZM(e)}}function Bn(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=>XM(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 XM(e,t){let n=e.indexers.find(a=>a.language===t),r=n?.runnable?"available":"unavailable",i=KM[t],o=t==="typescript"?QM(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=YM(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 ${Ih[t].join(", ")} files.`}}}function QM(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 YM(e,t){let n=new Set(Ih[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function ZM(e){try{return JM("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as ej,existsSync as Es,readFileSync as Ts,writeFileSync as Nh}from"fs";import{join as Oi}from"path";var ji="<!-- scip-query:agent-setup:begin -->",Hl="<!-- scip-query:agent-setup:end -->",Dh="# scip-query:agent-setup";function Bi(){if(process.stdin.isTTY)return"";try{return Ts(0,"utf-8")}catch{return""}}function _s(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function Hi(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(`
809
- `)}function Fs(e,t={}){let n={written:[],unchanged:[],skipped:[]};return tj(e,n),t.gitHook&&nj(e,n),n}function tj(e,t){let n=[ji,"## 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.",Hl].join(`
810
- `);Ph(e,"AGENTS.md",n,t);let r=Es(Oi(e,"CLAUDE.md"))?Ts(Oi(e,"CLAUDE.md"),"utf-8"):"";if(r.includes("@AGENTS.md")&&!r.includes(ji)){t.unchanged.push("CLAUDE.md");return}let i=[ji,"@AGENTS.md",Hl].join(`
811
- `);Ph(e,"CLAUDE.md",i,t)}function Ph(e,t,n,r){let i=Oi(e,t),o=Es(i)?Ts(i,"utf-8"):"",s;if(o.includes(ji)){let a=new RegExp(`${ji}[\\s\\S]*?${Hl}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
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*$/,`
812
863
 
813
864
  `)}${n}
814
865
  `:`${n}
815
- `;s===o?r.unchanged.push(t):(Nh(i,s),r.written.push(t))}function nj(e,t){let n=Oi(e,".git","hooks");if(!Es(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let r=Oi(n,"pre-commit"),i=["#!/bin/sh",Dh,"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(`
816
- `);if(Es(r)){let o=Ts(r,"utf-8");if(o.includes(Dh)){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}}Nh(r,i),ej(r,493),t.written.push(".git/hooks/pre-commit")}var Fh="SCIP_QUERY_SKIP_HOOK_INSTALL",Vl="SCIP_QUERY_STOP_HOOK_MODE",cj="scip-query hook-",lj="scip-query diff-gate --hook";function $s(e,t={}){let n=$h(),r=t.env??process.env;return dj(r)?(n.skipped.push({target:"project agent hooks",reason:`${Fh}=1`}),n):(Eh({provider:"codex",rootDir:Ar(e,".codex"),configPath:Ar(e,".codex","hooks.json"),label:".codex/hooks.json",createRoot:!0,result:n}),Eh({provider:"claude",rootDir:Ar(e,".claude"),configPath:Ar(e,".claude","settings.json"),label:".claude/settings.json",createRoot:!0,result:n}),t.removeLegacyUserHooks!==!1&&uj({homeDir:t.homeDir,result:n}),n)}function uj(e={}){let t=e.result??$h(),n=e.homeDir??sj();return Th({configPath:Ar(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),Th({configPath:Ar(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function $h(){return{installed:[],updated:[],unchanged:[],removed:[],skipped:[]}}function dj(e=process.env){let t=e[Fh];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function mj(e=process.env){let t=e[Vl]?.toLowerCase();return t==="block"||t==="blocking"||t==="1"||t==="true"||t==="yes"?"block":t==="feedback"||t==="continue"?"feedback":"warn"}function Eh(e){if(!e.createRoot&&!Vi(e.rootDir))return;let t=Ah(e.configPath,e.label,e.result);if(!t)return;let n=pj(t,e.provider);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let r=Vi(e.configPath);ij(aj(e.configPath),{recursive:!0}),_h(e.configPath,`${JSON.stringify(n,null,2)}
817
- `),e.result[r?"updated":"installed"].push(e.label)}function Th(e){if(!Vi(e.configPath))return;let t=Ah(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=Mh(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,_h(e.configPath,`${JSON.stringify(o,null,2)}
818
- `),e.result.removed.push(e.label)}function Ah(e,t,n){if(!Vi(e))return{};try{let r=JSON.parse(oj(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 pj(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]=[...Mh(o),gj(t,i)]}return r}function Mh(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!fj(n)):[]})).filter(t=>t.hooks.length>0)}function fj(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(cj)||t===lj)}function gj(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 jh(){let e=await bj(Bi());e&&console.log(JSON.stringify(e))}function Oh(){let e=Bi();if(_s(e))return;let t=Bh(e),n=Hh(t);!n||!Vi(n.paths.dbPath)||kj(n,r=>{let i=ki(r,{minTogether:6,skip:[]});i.findings.length!==0&&console.log(JSON.stringify(hj(i,mj())))})}function hj(e,t="warn"){let n=Hi(e),r=yj(e);return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${r}
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}
819
870
 
820
871
  This is non-error Stop hook feedback. Fix true findings, or explain why a finding is intentionally accepted before finishing.`}}:{systemMessage:`${r}
821
872
 
822
- Stop hook allowed this turn to finish. Review these findings when relevant. Set ${Vl}=feedback to ask the agent to continue without a hook error, or ${Vl}=block to enforce the gate.`}}function yj(e){return Hi(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}async function bj(e){let t=Bh(e),n=vj(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit")return;let r=Hh(t);if(!r)return;let i=await Sj(r),o=n==="SessionStart"?xj(r.projectRoot,r.config,r.paths):Cj(String(t.prompt??"")),s=[i,o].filter(a=>!!a?.trim()).join(`
823
- `);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}async function Sj(e){if(Pr(e.config).autoRefresh===!1)return;let n=On(e.projectRoot,e.config,e.paths);if(n.state!=="fresh")try{let r=await tn({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 xj(e,t,n){let r=On(e,t,n),i=Ct(e,t),s=Bn(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(`
824
- `)}function Cj(e){let t=e.toLowerCase(),n=[];return Hn(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."),Hn(t,["explain","how does","walk me through","trace","understand"])&&n.push("Exploration request: use scip-explore before answering behavioral questions."),Hn(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."),Hn(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."),Hn(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."),Hn(t,["setup","adopt","install","bootstrap"])&&n.push("Setup request: use scip-adoption or scip-query-setup; keep CI setup out of the default path."),Hn(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(`
825
- `)}function Hn(e,t){return t.some(n=>e.includes(n))}function Bh(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function vj(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function Hh(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=Rj(t);if(n)try{let r=Pe(n),i=bt(n,r);return{projectRoot:n,config:r,paths:i}}catch{return}}function Rj(e){try{return rj("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function kj(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 Ir(n,Zt(e.projectRoot));try{return t(r)}finally{r.close()}}import{existsSync as ql,mkdirSync as wj,symlinkSync as Lj,readlinkSync as Ij,unlinkSync as Dj}from"fs";import{join as qi,dirname as Vh,resolve as Ul}from"path";import{homedir as Wl,platform as Pj}from"os";import{fileURLToPath as Nj}from"url";var Ej=Pj()==="win32",Gl=["scip-query","scip-query-setup","scip-adoption","scip-health-audit","scip-health-improve","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 As(e={}){let t=e.quiet?()=>{}:console.log,n=Nj(import.meta.url),r=Ul(Vh(n),"..","skills"),i=[qi(Wl(),".claude","skills"),qi(Wl(),".codex","skills"),qi(Wl(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[]};for(let s of i){let a=Vh(s);if(!ql(a))continue;wj(s,{recursive:!0});let c=Tj(s);for(let l of Gl){let u=qi(r,l),d=qi(s,l);if(!ql(u)){o.skipped.push(`${c}/${l}`);continue}if(ql(d)){try{let m=Ij(d);if(Ul(m)===Ul(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}Dj(d)}Lj(u,d,Ej?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function Tj(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as cy}from"child_process";import{existsSync as jr,renameSync as sy,rmSync as RO}from"fs";import{dirname as kO,extname as wO}from"path";import{execFileSync as _j,fork as Fj}from"child_process";import{statSync as $j,watch as Aj}from"fs";import{join as Mj,relative as jj}from"path";import Oj from"ignore";var Ms=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=Pr(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=Zt(t.projectRoot),this.extraIgnore=Oj(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let t=Aj(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=jj(this.projectRoot,Mj(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=Bj(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=Pe(this.projectRoot),s=Object.keys(o).length>0?o:this.config,a=bt(this.projectRoot,s),c=s.indexer?.typescript,l=Fj(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=qh(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n={head:qh(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 qh(e,t){try{return _j("git",["-C",e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function Bj(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 Yj}from"fs";import{existsSync as Hj,mkdirSync as Vj,readFileSync as qj,writeFileSync as Uj}from"fs";import{dirname as Wj,join as Uh}from"path";function Gh(e){let t={markdownPath:Uh(e.projectRoot,"docs","scip-query","health-dossier.md"),jsonPath:Uh(e.projectRoot,"docs","scip-query","health-dossier.json"),status:"written",written:[],unchanged:[]},n={...e,healthDossier:t};try{return Wh(t.markdownPath,Gj(n),t),Wh(t.jsonPath,`${JSON.stringify(n,null,2)}
826
- `,t),t}catch(r){return{...t,status:"failed",error:r instanceof Error?r.message:String(r)}}}function Gj(e){return`${["# scip-query Health Dossier","",`Generated: ${new Date().toISOString()}`,`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${Xj(e)}`,"","## Items That Need Attention","",...zj(e),"","## Blocked Or Unavailable Checks","",...Jj(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","",...Kj(e),"","## JSON","",`Machine-readable report: \`${Qj(e)}\``,""].join(`
827
- `)}`}function zj(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 Jj(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 Kj(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 Xj(e){return e.health.score===null?`unavailable (${e.health.unavailableReason??"not checked"})`:`${e.health.score} (risk ${e.health.riskScore}, hygiene ${e.health.hygieneScore})`}function Qj(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function Wh(e,t,n){if(Vj(Wj(e),{recursive:!0}),(Hj(e)?qj(e,"utf-8"):null)===t){n.unchanged.push(e);return}Uj(e,t),n.written.push(e)}async function Qh(e={}){let t=[],{projectRoot:n,config:r,paths:i,dbPath:o}=Nr(),s=$i();X(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=As({quiet:!0});X(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(I=>`Skipped ${I}`)});let c=Dr(r,{projectRoot:n}),l=c.filter(I=>I.level==="error");X(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(I=>`${I.level.toUpperCase()} ${I.path}: ${I.message}`)});let u=Pr(r);X(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=Ct(n,r);X(t,{id:"readiness",label:"Indexer readiness",status:d.languages.length===0?"failed":d.indexers.some(I=>!I.runnable)?"warn":"ok",message:d.languages.length===0?"No supported project languages detected.":`Detected languages: ${d.languages.join(", ")}`,details:d.indexers.map(I=>`${I.runnable?"OK":I.installed?"WARN":"MISSING"} ${I.language}: ${I.binaryLabel}${I.note?` - ${I.note}`:""}`)});let m=aO(n,d,t),f=Ct(n,r),h=null;if(f.languages.length===0||l.length>0)X(t,{id:"reindex",label:"Index refresh",status:"skipped",message:f.languages.length===0?"Skipped because no supported languages were detected.":"Skipped because config validation has errors."});else{let I=[];try{h=await tn({projectRoot:n,languages:f.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=>I.push(z)}),X(t,{id:"reindex",label:"Index refresh",status:h.skipped.length>0?"warn":"ok",message:`${h.reused?"Reused":"Indexed"} ${h.languages.join(", ")} in ${(h.durationMs/1e3).toFixed(1)}s.`,details:[...I,...h.skipped.map(z=>`Skipped ${z.language}: ${z.reason}`)]})}catch(z){X(t,{id:"reindex",label:"Index refresh",status:"failed",message:js(z),details:I})}}let g=Ct(n,r),y=Bn(g),S=On(n,r,i);X(t,{id:"capabilities",label:"Capability matrix",status:mO(y),message:pO(y)});let v=await lO(i.dbPath,t),k=null;try{k=$s(n),X(t,{id:"project-hooks",label:"Project agent hooks",status:k.skipped.length>0?"warn":"ok",message:`${k.installed.length} installed, ${k.updated.length} updated, ${k.unchanged.length} already configured, ${k.removed.length} legacy user hook config(s) cleaned up, ${k.skipped.length} skipped.`,details:[...k.removed.map(I=>`Removed legacy user-level ${I}`),...k.skipped.map(I=>`Skipped ${I.target}: ${I.reason}`)]})}catch(I){X(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:js(I)})}let N=null;try{N=Fs(n,{gitHook:e.gitHook}),X(t,{id:"agent-guidance",label:"Project agent guidance",status:N.skipped.length>0?"warn":"ok",message:`${N.written.length} written, ${N.unchanged.length} already wired, ${N.skipped.length} skipped.`,details:N.skipped.map(I=>`Skipped ${I.target}: ${I.reason}`)})}catch(I){X(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:js(I)})}let w=Zj({reindexResult:h,readiness:g,capabilities:y,freshness:S,health:v,hooksResult:k,agentResult:N,steps:t});X(t,{id:"smoke-tests",label:"Setup smoke tests",status:eO(w),message:tO(w),details:w.map(I=>`${I.command}: ${I.status} - ${I.evidence}`)});let R={projectRoot:n,dbPath:o,configuredDbPath:i.dbPath,scipCliInstalled:s,languages:g.languages,steps:t,skills:a,initialReadiness:d,indexerRemediation:m,readiness:g,capabilities:y,freshness:S,reindex:h,health:v,smokeTests:w,healthDossier:null,hooks:k,setupAgent:N,filesWritten:N?.written??[],verdict:Xh(t,g)},$=Gh(R);return R.healthDossier=$,R.filesWritten=[...R.filesWritten,...$.written],X(t,{id:"health-dossier",label:"Health dossier",status:$.status==="failed"?"failed":"ok",message:$.status==="failed"?$.error:`${$.written.length} written, ${$.unchanged.length} unchanged.`,details:[$.markdownPath,$.jsonPath]}),R.verdict=Xh(t,g),R}function Yh(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${fO(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 Zj(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:nO(e.steps),evidence:rO(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?iO(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:zh(e.readiness,e.freshness),evidence:Jh(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:zh(e.readiness,e.freshness),evidence:Jh(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:oO(e.capabilities),evidence:sO(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 eO(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function tO(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 nO(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function rO(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function iO(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 zh(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function Jh(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 oO(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function sO(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 aO(e,t,n){let r=[];if(t.languages.length===0)return X(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=An(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,u=!1;l?u=Is(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=cO(Ls(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 X(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 X(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 cO(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function lO(e,t){if(!Yj(e)){let n="Skipped because no SQLite index database exists yet.";return X(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Kh(n)}try{let n=await bs({full:!0,json:!0});return X(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),uO(n)}catch(n){let r=js(n);return X(t,{id:"health",label:"Health audit",status:"failed",message:r}),Kh(r)}}function uO(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(dO),warnings:e.warnings??[]}}function dO(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 Kh(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function Xh(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 mO(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 pO(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 fO(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function X(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function js(e){return e instanceof Error?e.message:String(e)}import{existsSync as gO,mkdirSync as hO,writeFileSync as yO}from"fs";import{dirname as bO,join as SO}from"path";function Zh(e,t={}){let n=SO(e,".github","workflows","scip-query.yml"),r=xO();return gO(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(hO(bO(n),{recursive:!0}),yO(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function xO(){return`name: scip-query
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
828
879
 
829
880
  on:
830
881
  pull_request:
@@ -842,48 +893,48 @@ jobs:
842
893
  - run: npm ci
843
894
  - run: npx scip-query reindex
844
895
  - run: npx scip-query diff-gate --base "origin/\${{ github.base_ref }}"
845
- `}var ey=Symbol("option-value-source");function K(e){return(...t)=>{let{args:n,opts:r}=vO(t);Je(i=>e({db:i,args:n,opts:r}))}}function Q(e,t){return K(n=>{let r=ys(n.db,e,C(n.opts,"full"),{quiet:C(n.opts,"json")});t({...n,budget:r})})}function ty(e){return K(t=>Mr(t,e,{kind:"list"}))}function ny(e){return K(t=>Mr(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function ry(e){return K(t=>Mr(t,e,{kind:"grouped",key:e.key}))}function Vn(e){return K(t=>Kl(t,e))}function iy(e){return Vn({commandName:e.commandName,query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>D.sectionedReport(e.sections(t,n)),toJson:e.toJson,after:e.after})}function Xe(e,t){return Q(e,n=>Kl(n,{...t,commandName:t.commandName??e}))}function oy(e,t){return Xe(e,{commandName:t.commandName??e,query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,r)=>D.sectionedReport(t.sections(n,r)),toJson:t.toJson,after:t.after})}function Ft(e,t){return Q(e,n=>Mr(n,{...t,commandName:e},{kind:"list"}))}function Os(e,t){return Q(e,n=>Mr(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Bs(e,t){return Q(e,n=>Mr(n,{...t,commandName:e},{kind:"grouped",key:t.key}))}function H(e,t){return String(e[t])}function pe(e,t){let n=e[t];return typeof n=="string"?n:void 0}function E(e,t){let n=e[t];return typeof n=="string"?n:void 0}function ke(e,t){let n=e[t];return typeof n=="number"?n:void 0}function C(e,t){return!!e[t]}function zl(e,t){let n=e[t];return Array.isArray(n)&&n.every(r=>typeof r=="string")?n:[]}function P(e,t,n){return ke(e,t)??n}function O(e,t,n){let r=ke(e,t),i=r!==void 0&&Jl(e,t)!=="default";if(C(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 Jl(e,t){return e[ey]?.(t)}function Mr(e,t,n){Kl(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"?D.list(r,o=>t.format(o,i)):n.kind==="table"?D.table(n.headers,r.map(o=>t.format(o,i)),n.dashWidths):D.groupedByFile(r,o=>t.format(o,i),n.key?o=>n.key(o,i):void 0)},toJson:t.toJson,after:t.after})}function Kl(e,t){let n=t.query(e);if(C(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){D.empty(r);return}t.heuristicLabel&&Tr(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:CO(t),options:n,result:r},null,2))}function CO(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function vO(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:se(t)}}function se(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,ey,{value:r=>t.getOptionValueSource(r),enumerable:!1}),n)}return e}var LO=new Set(["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"]),IO=18e4,ly=100*1024*1024,DO=new Set(ia),PO=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],NO=[["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 EO(e){return e.filter(t=>LO.has(t))}async function uy(e){let t=se(e),n=de(),r=Pe(n),i=bt(n,r);try{let o=EO(zl(t,"language")),s=await tn({projectRoot:n,languages:o.length>0?o:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:C(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,skipIfUnchanged:!C(t,"force"),allowPartial:C(t,"allowPartial"),indexerConcurrency:ke(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 dy(){let e=de(),t=Er(e);try{let n=en({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 my(e){let t=se(e),n=de(),r=Er(n);try{let i=Nl({projectRoot:n,dbPath:r,tsconfig:E(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${i.vueFiles}; resolved references: ${i.resolvedReferences}; inserted mentions: ${i.insertedMentions}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}}function py(e){let t=se(e);Je(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=gt(n,{base:E(t,"base")}),o=Jo(n,r,i.changedFiles,i.changedRanges);console.log(JSON.stringify(o))})}async function fy(e){let t=se(e);try{let n=await rg({base:E(t,"base")});if(C(t,"json")){M("diff-impact",[],t,n);return}og(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function gy(e,t){let n=se(t),r=String(e).split(",").filter(i=>i.length>0);Je(i=>{let o=[];for(let c of r)Lr.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:E(n,"scope"),full:C(n,"full")},a=o.length===1?Gc(i,o[0],s):zc(i,o,s);console.log(JSON.stringify(a))})}async function hy(e){let t=se(e);if(C(t,"writeBaseline")||C(t,"baseline")){OO(t);return}try{let n=await bs({scope:E(t,"scope"),full:!0,json:C(t,"json")});if(C(t,"json")){M("health",[],t,n);return}ng(n,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function yy(e){let t=se(e),n=de(),r=ke(t,"timeoutMs")??IO,i={projectRoot:n,...MO(n),index:Xl(jr(Er(n))),commands:[]};C(t,"coldIndex")&&(i.coldIndex=await TO(n),i.warmIndex=await _O(n),i.index=Xl(jr(Er(n))));for(let o of FO(t))i.commands.push(AO(n,o,r));if(C(t,"json")){M("bench",[],t,i);return}jO(i)}async function TO(e){let t=Pe(e),n=bt(e,t),r=kO(n.dbPath),i=`${r}.bench-backup-${Date.now()}`,o=!1;jr(r)&&(sy(r,i),o=!0);try{let s=await by(()=>tn({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&&RO(i,{recursive:!0,force:!0}),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...Sy(e)}}catch(s){throw o&&!jr(r)&&sy(i,r),s}}async function _O(e){let t=Pe(e),n=bt(e,t),r=await by(()=>tn({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,...Sy(e)}}async function by(e){let t=performance.now(),n=await e();return{durationMs:Math.round(performance.now()-t),value:n}}function Sy(e){return jr(Er(e))?Je(t=>{let n=Fe(t);return{files:n.documents,symbols:n.symbols}}):{}}function FO(e){let t=zl(e,"command");return t.length>0?t.map($O).filter(n=>n.length>0):[...PO.map(n=>[...n]),...C(e,"includeHeavy")?NO.map(n=>[...n]):[]]}function $O(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function AO(e,t,n){let r=performance.now(),i=cy(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,encoding:"buffer",maxBuffer:ly,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 MO(e){let t=cy("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:ly});if(t.status!==0)return{repoFiles:null,sourceFiles:null};let n=t.stdout.split(`
846
- `).filter(Boolean);return{repoFiles:n.length,sourceFiles:n.filter(r=>DO.has(wO(r).toLowerCase())).length}}function jO(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, ${$n(e.index.indexSizeBytes)}`),e.coldIndex&&ay("Cold index",e.coldIndex),e.warmIndex&&ay("Warm index",e.warmIndex),console.log(`
847
- 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 ay(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function OO(e){let t=E(e,"scope");Je(n=>{if(C(e,"writeBaseline")){let i=Bc(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=Ci(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 xy(){let e=As(),t=e.installed.length+e.alreadyLinked.length;console.log(`
848
- ${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 Cy(e){let t=se(e),n=de(),r=$s(n);if(C(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(`
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(`
849
900
  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(`
850
- No project-local hook config was written.`)}function vy(){let e=!1;$i()?console.log("scip CLI: installed"):(fl(),e=!0);let t=de(),n=Pe(t),r=Ct(t,n);if(r.languages.length===0){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(`
851
902
  No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
852
903
  Detected languages: ${r.languages.join(", ")}`),console.log(`
853
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(`
854
- 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 Ry(e){wy(e,"capabilities")}function ky(e){wy(e,"capability-matrix")}function wy(e,t){let n=se(e),r=de(),i=Pe(r),o=Ct(r,i),s=Bn(o);if(C(n,"json")){M(t,[],n,s);return}Ql(s)}function Ly(){let e=de(),t=Tt(e),n=zf(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Iy(e){let t=se(e),n=de(),r=Pe(n),i=Dr(r,{projectRoot:n});if(C(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 Dy(e,t){let n=se(t),r=E(n,"reason");if(!r||r.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let i=Jf(de(),{id:String(e),check:E(n,"check"),file:E(n,"file"),reason:r,expiresAt:E(n,"expiresAt")});if(C(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 Py(e){let t=se(e),{report:n,hasIndexerProblems:r,hasErrors:i}=Ny("doctor");C(t,"json")?M("doctor",[],t,n):BO(n,r),process.exitCode=i?1:0}function Ny(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=Nr(),o=Dr(n,{projectRoot:t}),s=Ct(t,n),a=Bn(s),c=On(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:jr(i),configDiagnostics:o,readiness:s,freshness:c,capabilities:a,ok:!u},hasIndexerProblems:l,hasErrors:u}}function Ey(e){let t=se(e),n=de(),r=Fs(n,{gitHook:C(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(`
855
- 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 Ty(e){let t=se(e);try{let n=await Qh({gitHook:C(t,"gitHook")});C(t,"json")?M("setup",[],t,n):Yh(n),process.exitCode=n.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function _y(e){let t=se(e),n=de(),r=Zh(n,{force:C(t,"force"),dryRun:C(t,"dryRun")});if(C(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 Fy(e){let t=se(e),n=de(),r=Pe(n),i=ke(t,"debounce"),o=ke(t,"cooldown"),s=ke(t,"gitPoll");i&&((r.watch??={}).debounceMs=i),o&&((r.watch??={}).cooldownMs=o),s&&((r.watch??={}).gitPollMs=s);let a=new Ms({projectRoot:n,config:r,languages:r.languages,onStatus:c=>{process.stdout.write(`\r\x1B[K${Xf(c)}`)},onReindexComplete:c=>{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(`
856
907
  Reindex complete in ${(c/1e3).toFixed(1)}s`)},onError:c=>{console.error(`
857
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.
858
909
  `),a.start(),process.on("SIGINT",()=>{a.stop(),console.log(`
859
- Stopped.`),process.exit(0)})}function $y(e){let t=se(e),{report:n}=Ny("status");if(C(t,"json")){M("status",[],t,{...n,stats:Xl(n.exists)});return}HO(n,{capabilities:C(t,"capabilities")})}function BO(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})`:""}`),Ql(e.capabilities)}function HO(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: ${VO(e.freshness.lastRefresh)}`),qO(e.exists),t.capabilities&&(console.log(""),Ql(e.capabilities))}function VO(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 Xl(e){if(e)return Je(t=>{let n=Fe(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function qO(e){e&&Je(t=>{let n=Fe(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${$n(n.indexSizeBytes)}`),n.lastBuilt){let r=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${r}s ago`)}})}function Ql(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(`
860
- 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 Ui(e){return{...e,options:_(e.options)}}function vt({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,...o}){let s=Ui(o);return{...s,renderShape:"list",handler:ty({commandName:s.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i})}}function Hs({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s,...a}){let c=Ui(a);return{...c,renderShape:"table",handler:ny({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s})}}function Ay({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o,...s}){let a=Ui(s);return{...a,renderShape:"grouped-by-file",handler:ry({commandName:a.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o})}}function My({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,after:o,...s}){let a=Ui(s);return{...a,renderShape:"sectioned-report",handler:iy({commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,after:o})}}function Vs({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,after:o,...s}){let a=Ui(s);return{...a,budget:a.budget??"semantic",renderShape:"sectioned-report",handler:oy(a.id,{commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,after:o})}}function Yl(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(` ${Re(l.startLine,l.endLine)} (${l.loc} LOC) ${l.shortName}`)}}var jy=Q("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:pe(t,0)||void 0,minLoc:P(n,"minLoc",1),includeTests:C(n,"includeTests"),skipBarrels:C(n,"skipBarrels"),includeMembers:C(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=Dt(e,i),s=o.symbols.filter(y=>y.kind==="dead-code"),a=o.symbols.filter(y=>y.kind!=="dead-code"),c=!C(n,"onlyInternal"),l=!C(n,"onlyDead"),u=c?s:[],d=l?a:[],m=u.reduce((y,S)=>y+S.loc,0),f=d.reduce((y,S)=>y+S.loc,0),h={total:u.length+d.length,deadCode:u.length,fileInternal:d.length,loc:m+f};if(C(n,"json")){M("dead",t,n,{...o,shown:{deadCode:u,fileInternal:d},shownCounts:h,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){D.empty("No matching dead-code symbols found.");return}u.length>0&&Yl(u,"DEAD CODE",` Zero references anywhere \u2014 no cross-file callers AND no same-file uses.
861
- Safe to delete.`,m),d.length>0&&(u.length>0&&console.log(""),Yl(d,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
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
862
913
  single-use helper, an abstraction-in-progress, or a callback registered
863
914
  through a framework path that static analysis cannot trace (signal
864
915
  handlers, event listeners, dependency injection). NOT necessarily dead \u2014
865
- review case by case.`,f));let g=[];c&&g.push(`${u.length} dead code (${m} LOC)`),l&&g.push(`${d.length} file-internal (${f} LOC)`),console.log(`
866
- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${u.length+d.length} symbols \u2014 ${g.join(" + ")}`)}),Oy=Ft("unused-imports",{query:({db:e,args:t,budget:n})=>Ua(e,H(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
867
- ${e.length} unused import(s)`)}),By=Bs("isolated",{query:({db:e,opts:t,budget:n})=>xn(e,{scope:E(t,"scope"),minLoc:P(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${Re(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
868
- ${e.length} isolated symbol(s)`)}),Hy=Q("extract-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=wn(e,{scope:E(n,"scope"),minLoc:P(n,"minLoc",10),minCallees:P(n,"minCallees",6),limit:O(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(C(n,"json")){M("extract-candidates",t,n,i);return}if(i.length===0)return D.empty("No extraction candidates found.");Tr("extraction candidates");for(let o of i){console.log(`
869
- ${Se(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(`
870
- ${i.length} extraction candidate(s) found.`)}),Vy=Q("locality-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=bc(e,{target:pe(t,0)||void 0,scope:E(n,"scope"),minConsumers:P(n,"minConsumers",1),limit:O(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(C(n,"json")){M("locality-candidates",t,n,i);return}if(i.length===0)return D.empty("No locality candidates found.");Tr("locality candidates");for(let o of i){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?Se(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
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(`
871
922
  ${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(`
872
- ${i.length} locality candidate(s) found.`)}),qy=Ft("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>_n(e,{scope:E(t,"scope"),maxLoc:P(t,"maxLoc",15),limit:O(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${Se(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
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)
873
924
  Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
874
925
  Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
875
- ${e.length} wrapper candidate(s).`)}),Uy=Ft("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>En(e,{scope:E(t,"scope"),maxLoc:P(t,"maxLoc",15),limit:O(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${Se(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
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)
876
927
  Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
877
928
  Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
878
929
  Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
879
930
  Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
880
- ${e.length} passthrough candidate(s).`)}),Wy=Ft("stale-abstractions",{query:({db:e,opts:t,budget:n})=>Tn(e,{scope:E(t,"scope"),minLoc:P(t,"minLoc",3),limit:O(t,"limit",30),includeLowConfidence:C(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}] ${Se(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
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})
881
932
  ${e.reason}
882
933
  Kind: ${e.stalenessKind}; tier: ${e.actionTier}
883
934
  Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
884
- ${e.length} stale abstraction(s).`)}),Gy=Os("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>Ii(e,{scope:E(t,"scope"),minLoc:P(t,"minLoc",10),limit:O(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.score.toFixed(1).padStart(5)} ${String(e.loc).padStart(4)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${String(e.calleeCount).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No complexity hotspots found.",heuristicLabel:"complexity hotspot candidates",dashWidths:[5,4,6,7,7,6]}),zy=Xe("similar",{query:({db:e,args:t,opts:n,budget:r})=>{let i=pe(t,0);return i?{mode:"target",rows:di(e,i,{minSimilarity:P(n,"minSimilarity",.4),limit:O(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:Pt(e,{minSimilarity:P(n,"minSimilarity",.4),limit:O(n,"limit",20),scope:E(n,"scope"),minCallees:P(n,"minCallees",4),crossFileOnly:C(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"){D.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=[`
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=[`
885
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(`
886
- `)});return}D.list(e.rows,t=>`
937
+ `)});return}N.list(e.rows,t=>`
887
938
  ${Math.round(t.similarity*100)}% similar:
888
939
  A: ${t.shortNameA} (${t.fileA})
889
940
  B: ${t.shortNameB} (${t.fileB})
@@ -891,85 +942,85 @@ ${Math.round(t.similarity*100)}% similar:
891
942
  Recommendation: ${t.recommendation}
892
943
  `+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
893
944
  `:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
894
- ${e.rows.length} similar pair(s) found.`)}}),Jy=Vn({commandName:"similar-files",query:({db:e,args:t,opts:n})=>mc(e,{minSimilarity:P(n,"minSimilarity",.5),limit:O(n,"limit",20),scope:E(n,"scope"),minDeps:ke(n,"minDeps"),filePattern:pe(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{D.list(e,t=>{let n=[`
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=[`
895
946
  ${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(`
896
947
  `)}),console.log(`
897
- ${e.length} similar pair(s) found.`)}}),Ky=Vn({commandName:"similar-chains",query:({db:e,opts:t})=>pc(e,{minSimilarity:P(t,"minSimilarity",.5),limit:O(t,"limit",15),scope:E(t,"scope"),minChainLength:P(t,"minLength",3),maxChainLength:P(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(`
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(`
898
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(`
899
- ${e.length} similar chain pair(s) found.`)}}),Xy=Xe("drift",{query:({db:e,args:t,opts:n,budget:r})=>Nn(e,{scope:pe(t,0),minDeviation:P(n,"minDeviation",5),semantic:r.semantic}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),D.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(`
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(`
900
951
  `)},t=>t.file),console.log(`
901
- ${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)`)}}),Qy=Xe("convergence",{query:({db:e,args:t,budget:n})=>Qc(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(`
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(`
902
953
  ${Math.round(e.similarity*100)}% callee overlap
903
954
  `),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)
904
955
  `),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
905
956
  Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
906
957
  Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
907
- Strategy: ${e.consolidationStrategy}`)}}}),Yy=Ft("similar-signatures",{query:({db:e,opts:t,budget:n})=>nl(e,{scope:E(t,"scope"),minLoc:P(t,"minLoc",3),limit:O(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=`
908
- Signature: ${e.signature} (${e.functions.length} functions)`,n=e.functions.map(r=>` ${Se(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
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(`
909
960
  `);return`${t}
910
961
  ${n}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
911
- ${e.length} group(s) found.`)}),Zy=Q("cleanup-plan",({db:e,args:t,opts:n,budget:r})=>{let i=Uo(e,{scope:E(n,"scope"),minLoc:P(n,"minLoc",1),maxDepth:P(n,"maxDepth",5),scanLimit:r.scanLimit}),o=de(),s=C(n,"patch"),a=C(n,"json"),c=C(n,"verify")||s;if(s&&!C(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 D.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=Ol(i),u=c?Al(o,i):void 0;if(a){M("cleanup-plan",t,n,{result:i,verification:u});return}if(s){let d=Bl(u,l);if(d.length>0){for(let f of d)console.error(`error: ${f}`);process.exitCode=1;return}let m=Lh(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.
912
- `);for(let d of i.batches){let m=d.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${d.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${d.depth}: dead once batch ${d.depth-1} lands (cascade, ${d.loc} LOC) \u2500\u2500`;console.log(m);for(let f of d.entries)console.log(` ${f.file}:${f.startLine+1}-${f.endLine+1} ${f.shortName} (${f.loc} LOC)`);d.filesEmptied.length>0&&console.log(` -> empties: ${d.filesEmptied.join(", ")}`),console.log("")}if(i.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let d of i.blocked)console.log(` ${d.shortName} (${d.file}) blocked by ${d.blockingFiles.join(", ")}`)}if(u){if(console.log(`
913
- 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}`)}}}),eb=Q("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!C(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let r=C(t,"all"),i=ke(t,"batch");if(r===(i!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=Uo(e,{scope:E(t,"scope"),minLoc:P(t,"minLoc",1),maxDepth:P(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){D.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=Ol(o,{all:r,batch:i});if(s.length===0){console.error(`error: No cleanup batch ${i} exists.`),process.exitCode=1;return}let a=de(),c=Al(a,o),l=Bl(c,s,{allowDirty:C(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,f)=>m+f.entries.length,0),d=s.reduce((m,f)=>m+f.loc,0);console.log(`Applied ${s.length} compiler-verified cleanup batch(es): ${u} symbol(s), ${d} LOC.`)}),tb=Q("recent-duplicates",({db:e,args:t,opts:n,budget:r})=>{let i=qc(e,{windowCommits:P(n,"window",100),minSimilarity:ke(n,"minSimilarity"),limit:O(n,"limit",30),scope:E(n,"scope"),scanLimit:r.scanLimit,semantic:r.semantic});if(C(n,"json")){M("recent-duplicates",t,n,i);return}if(!i.available)return D.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return D.empty(`No recent re-implementations found (window: last ${i.windowCommits} commits).`);console.log(`Recent re-implementations (window: last ${i.windowCommits} commits):
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):
914
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(`
915
- ${i.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),nb=K(({db:e,args:t,opts:n})=>{let r=Ac(e,{doc:t[0]===void 0?void 0:H(t,0),limit:O(n,"limit",20),minCoupling:P(n,"minCoupling",3)});if(C(n,"json")){M("doc-drift",t,n,r);return}if(!r.available)return D.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return D.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):
916
- `);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: ${fs(c)}`)}}console.log(`
917
- Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),rb=Ft("unused-params",{query:({db:e,opts:t,budget:n})=>Ri(e,{scope:E(t,"scope"),limit:O(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${Se(e.file,e.startLine,e.endLine)} ${e.shortName}
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}
918
969
  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(`
919
- ${e.length} function(s) with trailing unused parameters.`)});var ib=Xe("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Cn(e,{minSimilarity:P(n,"minSimilarity",.62),minTokens:P(n,"minTokens",8),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:r.scanLimit,filePattern:pe(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{D.list(e,t=>{let n=[`
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=[`
920
971
  ${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(`
921
972
  `)}),console.log(`
922
- ${e.length} duplicated React component pair(s) found.`)}}),ob=Xe("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:r})=>vn(e,{minSimilarity:P(n,"minSimilarity",.45),minSharedBehaviors:P(n,"minSharedBehaviors",6),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:r.scanLimit,filePattern:pe(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{D.list(e,t=>{let n=[`
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=[`
923
974
  ${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(`
924
975
  `)}),console.log(`
925
- ${e.length} React hook candidate pair(s) found.`)}}),sb=Xe("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:r})=>mi(e,{minComponentLines:P(n,"minComponentLines",300),minFileLines:P(n,"minFileLines",800),minJsxTokens:P(n,"minJsxTokens",80),minBehaviorTokens:P(n,"minBehaviorTokens",40),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:r.scanLimit,filePattern:pe(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{D.list(e,t=>[`
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=>[`
926
977
  ${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(`
927
978
  `)),console.log(`
928
- ${e.length} large React component(s) found.`)}}),ab=Xe("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Rn(e,{minSimilarity:P(n,"minSimilarity",.62),minTokens:P(n,"minTokens",8),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:r.scanLimit,filePattern:pe(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{D.list(e,t=>{let n=[`
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=[`
929
980
  ${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(`
930
981
  `)}),console.log(`
931
- ${e.length} duplicated Vue component pair(s) found.`)}}),cb=Xe("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:r})=>kn(e,{minSimilarity:P(n,"minSimilarity",.45),minSharedBehaviors:P(n,"minSharedBehaviors",6),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:r.scanLimit,filePattern:pe(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{D.list(e,t=>{let n=[`
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=[`
932
983
  ${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(`
933
984
  `)}),console.log(`
934
- ${e.length} Vue composable candidate pair(s) found.`)}}),lb=Xe("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:r})=>pi(e,{minTotalLines:C(n,"reviewThresholds")&&Jl(n,"minTotalLines")==="default"?300:P(n,"minTotalLines",800),minTemplateLines:P(n,"minTemplateLines",300),minScriptLines:P(n,"minScriptLines",300),minStyleLines:P(n,"minStyleLines",500),limit:O(n,"limit",20),scope:E(n,"scope"),scanLimit:r.scanLimit,filePattern:pe(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{D.list(e,t=>{let n=[`
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=[`
935
986
  ${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(`
936
987
  `)}),console.log(`
937
- ${e.length} large Vue view pressure file(s) found.`)}});function ct(e){return{docs:L("Cleanup"),...e}}function we({heuristicLabel:e,...t}){return ct({...t,heuristic:{label:e}})}var qs=[ct({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:_([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings",x,30),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:L("Cleanup",["scip-query unused-params -s src/services"]),handler:rb}),ct({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",x,1),p("--max-depth <n>","Maximum cascade depth",x,5),p("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),p("--patch","With --verify, print the compiler-verified deletion patch to stdout"),p("--json","Output as JSON for programmatic consumption"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:L("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:Zy}),ct({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",x,1),p("--max-depth <n>","Maximum cascade depth",x,5),p("--verified","Required: verify the selected cleanup batch before applying it"),p("--batch <n>","Apply one batch depth",x),p("--all","Apply every compiler-verified batch in the plan"),p("--force-dirty","Allow applying when plan files already have working-tree edits"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:L("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:eb}),ct({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:_([p("--window <n>",'How many commits back counts as "recent"',x,100),p("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",st),p("-n, --limit <n>","Maximum findings",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:L("Cleanup",["scip-query recent-duplicates --window 50"]),handler:tb}),ct({id:"doc-drift",command:"doc-drift [doc]",description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:_([p("-n, --limit <n>","Maximum docs to report",x,20),p("--min-coupling <n>","Minimum historical co-changes to track a subject",x,3),p("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:L("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:nb}),ct({id:"dead",command:"dead [scope]",description:"Find dead code and file-internal symbols (no cross-file consumers)",options:_([p("--min-loc <n>","Only show symbols >= N lines",x,1),p("--include-tests","Include test files"),p("--skip-barrels","Ignore refs from barrel re-export files"),p("--include-members","Include class members"),p("--only-dead","Show only [dead code] symbols (skip [file-internal only])"),p("--only-internal","Show only [file-internal only] symbols (skip [dead code])"),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:L("Cleanup",["scip-query dead --min-loc 10"]),handler:jy}),ct({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:_([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:Oy}),ct({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum lines of code",x,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:By}),we({id:"similar",command:"similar [symbol]",description:"Find heuristic function similarity candidates from callee fingerprints",options:_([p("--min-similarity <n>","Minimum Jaccard similarity (0-1)",st,.4),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-callees <n>","Minimum callees to consider",x,4),p("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:zy}),we({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:_([p("--min-similarity <n>","Minimum Jaccard similarity (0-1)",st,.5),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-deps <n>","Minimum dependencies to consider",x),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:Jy}),we({id:"react-component-duplicates",command:"react-component-duplicates [file]",description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:_([p("--min-similarity <n>","Minimum JSX structure similarity (0-1)",st,.62),p("--min-tokens <n>","Minimum structural tokens to consider",x,8),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:ib}),we({id:"react-hook-candidates",command:"react-hook-candidates [file]",description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:_([p("--min-similarity <n>","Minimum behavior similarity (0-1)",st,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:ob}),we({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:_([p("--min-component-lines <n>","Minimum component lines",x,300),p("--min-file-lines <n>","Minimum file lines",x,800),p("--min-jsx-tokens <n>","Minimum JSX structure tokens",x,80),p("--min-behavior-tokens <n>","Minimum behavior tokens",x,40),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:sb}),we({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:_([p("--min-similarity <n>","Minimum template similarity (0-1)",st,.62),p("--min-tokens <n>","Minimum structural tokens to consider",x,8),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:ab}),we({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:_([p("--min-similarity <n>","Minimum behavior similarity (0-1)",st,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:cb}),we({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:_([p("--min-total-lines <n>","Minimum total component lines",x,800),p("--min-template-lines <n>","Minimum template lines",x,300),p("--min-script-lines <n>","Minimum script lines",x,300),p("--min-style-lines <n>","Minimum style lines",x,500),p("--review-thresholds","Use lower review thresholds without changing health scoring"),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:lb}),we({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:_([p("--min-similarity <n>","Minimum chain similarity (0-1)",st,.5),p("-n, --limit <n>","Number of results",x,15),p("-s, --scope <path>","Limit to files matching path"),p("--min-length <n>","Minimum chain length",x,3),p("--max-length <n>","Maximum chain length",x,8),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Ky}),we({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum function LOC",x,10),p("--min-callees <n>","Minimum callees to analyze",x,6),p("-n, --limit <n>","Number of results",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Hy}),we({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:_([p("-s, --scope <path>","Limit scan mode to files matching path"),p("--min-consumers <n>","Minimum consumers in scan mode",x,1),p("-n, --limit <n>","Number of results",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:L("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:Vy}),we({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations",options:_([p("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",_i,5),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:Xy}),we({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",x,15),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:qy}),we({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",x,15),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:Uy}),we({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",x,3),p("-n, --limit <n>","Number of results",x,30),p("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:Wy}),we({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",x,10),p("-n, --limit <n>","Number of results",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:Gy}),ct({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Show what a consolidated version of two similar functions would look like",options:_([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:Qy}),Ay({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded analysis on large indexes")],docs:L("Cleanup"),query:({db:e,opts:t})=>Zc(e,{scope:E(t,"scope"),limit:O(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
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})
938
989
  barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
939
990
  Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
940
991
  Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
941
- ${e.length} redundant re-export(s).`)}),ct({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC per function",x,3),p("-n, --limit <n>","Number of groups",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:Yy})];var WO=K(({db:e,args:t,opts:n})=>{let r=Fe(e);if(C(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: ${$n(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),ub=[{id:"stats",command:"stats",description:"Show index statistics",options:[ml()],renderShape:"custom",docs:L("Core"),handler:WO}];var GO=Os("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Za(e,{limit:O(t,"limit",20),scope:E(t,"scope"),minFanIn:P(t,"minFanIn",2),minFanOut:P(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."}),zO=K(({db:e,args:t,opts:n})=>{let r=pe(t,0),i=O(n,"limit",30);if(r){let s=za(e,r);if(C(n,"json")){M("fan-in",t,n,{mode:"symbol",symbol:r,rows:s});return}if(s.length===0)return D.empty(`No fan-in for ${r}.`);D.list(s,a=>` ${String(a.count).padStart(4)} files ${a.name}`);return}let o=Ka(e,{limit:i,scope:E(n,"scope")});if(C(n,"json")){M("fan-in",t,n,{mode:"top",rows:o});return}D.table(["files","symbol"],o.map(s=>` ${String(s.count).padStart(5)} ${s.name}`))}),JO=K(({db:e,args:t,opts:n})=>{let r=pe(t,0),i=O(n,"limit",30);if(r){let s=Ja(e,r);if(C(n,"json")){M("fan-out",t,n,{mode:"file",file:r,rows:s});return}if(s.length===0)return D.empty(`No fan-out for ${r}.`);D.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=Xa(e,{limit:i,scope:E(n,"scope")});if(C(n,"json")){M("fan-out",t,n,{mode:"top",rows:o});return}D.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),KO=K(({db:e,args:t,opts:n})=>{let r=pe(t,0),i=pe(t,1),o=O(n,"limit",20);if(r&&i){let a=Qa(e,r,i);if(C(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=Ya(e,{limit:o,scope:E(n,"scope")});if(C(n,"json")){M("coupling",t,n,{mode:"top",rows:s});return}D.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}`))}),XO=Vn({commandName:"cycles",query:({db:e,opts:t})=>Sn(e,{scope:E(t,"scope"),maxDepth:P(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(`
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(`
942
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(`
943
- ${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.)`)}}),QO=Vn({commandName:"deep-chains",query:({db:e,opts:t})=>ic(e,{limit:O(t,"limit",10),scope:E(t,"scope"),minDepth:P(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(`
944
- 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("; ")}`)}}}),db=[Hs({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[p("-n, --limit <n>","Number of results",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")],docs:L("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>Ha(e,{limit:O(t,"limit",30),scope:E(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"How many files reference a symbol (or top fan-in across codebase)",options:_([p("-n, --limit <n>","Number of results for top mode",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:L("Graph"),handler:zO},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:_([p("-n, --limit <n>","Number of results for top mode",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:L("Graph"),handler:JO},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:_([p("-n, --limit <n>","Number of results for top mode",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:L("Graph"),handler:KO},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--max-depth <n>","Maximum cycle depth",x,10)]),renderShape:"custom",docs:L("Graph"),handler:XO},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:_([p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-fan-in <n>","Minimum fan-in",x,2),p("--min-fan-out <n>","Minimum fan-out",x,2),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:L("Graph"),handler:GO},{id:"deep-chains",command:"deep-chains",description:"Find the longest transitive dependency chains",options:_([p("-n, --limit <n>","Number of chains to show",x,10),p("-s, --scope <path>","Limit to files matching path"),p("--min-depth <n>","Minimum chain depth",x,3),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:L("Graph"),handler:QO},Vs({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[p("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:L("Graph"),query:({db:e,args:t,budget:n})=>li(e,String(t[0]),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"Symbol not found.",before:e=>{e&&console.log(`Symbol: ${e.shortName}
945
- `)},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 YO=Q("complexity",({db:e,args:t,opts:n,budget:r})=>{let i=wi(e,H(t,0),{semantic:r.semantic});if(C(n,"json")){M("complexity",t,n,i);return}if(!i)return D.empty("Symbol not found.");console.log(`${Se(i.relativePath,i.startLine,i.endLine)} ${i.shortName}
946
- `),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}`)}),ZO=K(({db:e,args:t,opts:n})=>{let r=tl(e,{samples:P(n,"samples",50),scope:E(n,"scope")});if(C(n,"json")){M("self-audit",t,n,r);return}if(!r.available)return D.empty("No semantic provider available to audit against (TypeScript projects only).");console.log(`Sampled ${r.sampleSize} symbols; oracle answered ${Math.round(r.oracleCoverage*100)}%.
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)}%.
947
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(`
948
- 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(", ")}`)}}),mb=[{id:"self-audit",command:"self-audit",description:"Score the cheap evidence paths against the TypeScript compiler oracle on sampled symbols",options:_([p("--samples <n>","Number of symbols to sample",x,50),p("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:L("Health",["scip-query self-audit --samples 100"]),handler:ZO},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:_([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:L("Health"),handler:YO}];var eB=K(({db:e,args:t,opts:n})=>{let r=fi(e,H(t,0),{maxDepth:P(n,"maxDepth",5),scope:E(n,"scope")});if(C(n,"json")){M("affected",t,n,r);return}if(r.length===0)return D.empty("No affected symbols found.");let i=-1;for(let o of r)o.depth!==i&&(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(`
949
1000
  \u2500\u2500 Depth ${o.depth} \u2500\u2500`),i=o.depth),console.log(` ${o.file} ${o.shortName}`);console.log(`
950
- ${r.length} affected symbol(s) across ${new Set(r.map(o=>o.file)).size} files.`)}),tB=K(({db:e,args:t,opts:n})=>{let r=t[0]===void 0?void 0:H(t,0),i=In(e,r,{minTogether:P(n,"minTogether",4),limit:O(n,"limit",30),includeLinked:n.all===!0});if(C(n,"json")){M("co-change",t,n,i);return}if(!i.available)return D.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return D.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):
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):
951
1002
  `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${i.commitsAnalyzed} commits analyzed):
952
- `);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 ${nB(o.lastTogetherAt)}`),console.log(` subjects: ${rB(o.subjectContext)}`),o.declaredCouplingSuggestion&&console.log(` declare coupling: ${o.declaredCouplingSuggestion.name} (${o.declaredCouplingSuggestion.reason})`)}console.log(`
953
- ${i.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function nB(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function rB(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 iB=Q("change-surface",({db:e,args:t,opts:n,budget:r})=>{let i=gi(e,H(t,0),{semantic:r.semantic});if(C(n,"json")){M("change-surface",t,n,i);return}if(!i)return D.empty("File not found in index.");console.log(`File: ${i.file}`),console.log(`External consumers: ${i.totalExternalConsumers}
954
- `),D.list(i.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${Re(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),oB=Q("incomplete-migration",({db:e,args:t,opts:n,budget:r})=>{let i=vi(e,{base:E(n,"base"),minContainment:P(n,"minContainment",.7),maxHelpers:ke(n,"maxHelpers"),limit:O(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(C(n,"json")){M("incomplete-migration",t,n,i),i.available&&i.findings.length>0&&(process.exitCode=1);return}if(!i.available)return D.empty("No git history available (not a repository, or git missing).");if(i.changedFiles.length===0)return D.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(`
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(`
955
1006
  No incomplete migrations detected.`);return}for(let o of i.findings){console.log(`
956
1007
  ${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(`
957
- ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function sB(e){let t=Array.isArray(e)?e:[],n=t.filter(r=>!as.includes(r));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${as.join(", ")}`),process.exit(1)),t}var aB=K(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&_s(Bi()))return;let r=ys(e,"diff-gate",C(t,"full"),{quiet:n||C(t,"json")}),i=ki(e,{base:E(t,"base"),minTogether:P(t,"minTogether",6),maxEchoChecks:ke(t,"maxEchoChecks"),maxHelpers:ke(t,"maxHelpers"),includeBaseline:C(t,"baseline"),scanLimit:r.scanLimit,semantic:r.semantic,skip:sB(t.skip)});if(!n&&C(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(Hi(i)),process.exitCode=2;return}if(i.changedFiles.length===0)return D.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(", ")}
958
- `);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: ${fs(a)}`);s.declaredCouplingSuggestion&&console.log(` declare coupling: ${s.declaredCouplingSuggestion.name} (${s.declaredCouplingSuggestion.reason})`),console.log(` -> ${s.remediation}`)}console.log(`
959
- 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:_([p("--max-depth <n>","Maximum traversal depth",x,5),p("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:L("Impact"),handler:eB},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:_([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:L("Impact"),handler:iB},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: echo candidates, incomplete migrations, missing co-change partners, uncited doc updates, unused params, new dead symbols; exit 1 on findings",options:[p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-together <n>","Minimum historical co-changes for the partner check",x,6),p("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",x),p("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",x),p("--baseline","Also run the full health-baseline ratchet"),p("--full","Run unbounded semantic analysis on large indexes"),p("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, doc-reference, unused-params, new-dead, baseline",Ti,[]),p("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),p("--json","Output as JSON for programmatic consumption")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:L("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:aB},{id:"incomplete-migration",command:"incomplete-migration",description:"Partially-completed extraction candidates: new helpers in the diff wired into some sites while similar un-migrated sites remain",options:_([p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",st,.7),p("--max-helpers <n>","Maximum new helpers to score (default: all)",x),p("-n, --limit <n>","Maximum findings to report",x,20),p("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:L("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:oB},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:_([p("--min-together <n>","Minimum commits where both files changed",x,4),p("-n, --limit <n>","Maximum pairs to report",x,30),p("--all","Include pairs that already have a dependency edge"),p("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:L("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:tB}];function cB(e){let t=[];for(let i of e.definitions){let o=i.signature?` \u2014 ${i.signature}`:"";t.push(` ${Se(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&t.push(i.source.split(`
960
- `).map((s,a)=>` ${je(i.startLine+a)} ${s}`).join(`
961
- `))}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 ${je(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var lB=K(({db:e,args:t,opts:n})=>{let r=H(t,0),i=C(n,"signatures"),o=Wa(e,r);if(C(n,"json")){M("outline",t,n,o);return}if(o.length===0)return D.empty(`No symbols found for "${r}".`);function s(a,c){for(let l of a){let u=" ".repeat(c),d=i&&l.signature?` - ${uB(l.signature)}`:"";console.log(`${u}${Re(l.startLine,l.endLine)} ${l.shortName}${d}`),s(l.children,c+1)}}s(o,0)});function uB(e){return e.length>120?`${e.slice(0,117)}...`:e}var dB=Ft("imports",{query:({db:e,args:t,budget:n})=>Va(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)."}),mB=Bs("refs",{query:({db:e,args:t,budget:n})=>Fa(e,H(t,0),{semantic:n.semantic}),format:e=>` line ${je(e.line)}`}),pB=K(({db:e,args:t,opts:n})=>{let r=Yc(e,H(t,0),{context:P(n,"context",0)});if(C(n,"json")){M("code",t,n,r);return}if(!r)return D.empty("Symbol not found or file unreadable.");console.log(`${Se(r.relativePath,r.startLine,r.endLine)} ${r.shortName} [${r.language??"unknown"}]
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"}]
962
1013
  `);let i=r.source.split(`
963
- `);for(let o=0;o<i.length;o++)console.log(` ${String(je(r.startLine+o)).padStart(4)} ${i[o]}`)}),fB=Q("dataflow",({db:e,args:t,opts:n,budget:r})=>{let i=Li(e,H(t,0),{semantic:r.semantic});if(C(n,"json")){M("dataflow",t,n,i);return}if(!i)return D.empty("Symbol not found.");if(console.log(`${i.shortName} (${i.relativePath})
964
- `),i.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let o of i.definitionSites)console.log(` ${o.file}:${je(o.line)}`)}if(i.usageSites.length>0){console.log(`
965
- \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let o of i.usageSites)console.log(` ${o.file}:${je(o.line)} in ${o.enclosingShort}`)}if(i.producers.length>0){console.log(`
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(`
966
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(`
967
- \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let o of i.consumers)console.log(` ${o.file} ${o.shortName}`)}}),gB=Q("slice",({db:e,args:t,opts:n,budget:r})=>{let i=C(n,"forward")?"forward":"backward",o=wr(e,H(t,0),{direction:i,maxDepth:P(n,"depth",3),semantic:r.semantic});if(C(n,"json")){M("slice",t,n,o);return}if(!o)return D.empty("Symbol not found.");if(console.log(`${o.direction} slice of ${o.shortName}
968
- `),o.connectedSymbols.length===0){console.log(" No connected symbols found.");return}D.list(o.connectedSymbols,s=>` ${s.file} ${s.shortName}
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}
1019
+ `),o.connectedSymbols.length===0){console.log(" No connected symbols found.");return}N.list(o.connectedSymbols,s=>` ${s.file} ${s.shortName}
969
1020
  ${s.relationship}`),console.log(`
970
- ${o.connectedSymbols.length} connected symbol(s).`)}),fb=[vt({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:L("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>Js(e,H(t,0)),format:e=>e.relativePath}),vt({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:L("Navigation"),query:({db:e,args:t})=>_a(e,H(t,0)),format:e=>` ${Re(e.startLine,e.endLine)} ${e.name}`}),{id:"refs",command:"refs <symbol>",description:"Find all files referencing a symbol",options:[p("--full","Run unbounded semantic analysis on large indexes"),p("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"grouped-by-file",docs:L("Navigation",["scip-query refs login"]),handler:mB},Vs({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[p("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:L("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>ri(e,H(t,0),{semantic:n.semantic}),sections:cB}),vt({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:L("Navigation"),query:({db:e,args:t})=>ii(e,H(t,0)),format:e=>e.relativePath}),vt({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:L("Navigation"),query:({db:e,args:t})=>oi(e,H(t,0)),format:e=>e.relativePath}),My({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",docs:L("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>si(e,H(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${Re(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}`)}]}),vt({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:L("Navigation"),query:({db:e,args:t})=>ai(e,H(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[p("--full","Run unbounded semantic analysis on large indexes"),p("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:L("Navigation"),handler:dB},vt({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:L("Navigation"),query:({db:e,args:t})=>qa(e,H(t,0)),format:e=>` ${e.fromFile}`}),{id:"outline",command:"outline <file>",description:"Tree view of symbols in a file, with line ranges",options:_([p("--signatures","Show trimmed symbol signatures")]),renderShape:"custom",docs:L("Navigation"),handler:lB},vt({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:L("Navigation"),query:({db:e,args:t})=>Ga(e,H(t,0)),format:e=>` ${Re(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`}),vt({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",x,100),p("--full","Run unbounded analysis on large indexes")],docs:L("Navigation"),query:({db:e,args:t,opts:n})=>nc(e,H(t,0),{scope:E(n,"scope"),limit:O(n,"limit",100)}),format:e=>` ${Se(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(`
971
- ${e.length} symbol(s)`)}),Hs({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[p("-s, --scope <path>","Limit to files matching path")],docs:L("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>rc(e,{scope:E(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),vt({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:L("Navigation"),query:({db:e,args:t})=>oc(e,H(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,emptyMessage:()=>"Symbol not found."}),{id:"code",command:"code <symbol>",description:"Read the source code for a symbol (bounded to its definition range)",options:_([p("-C, --context <n>","Extra lines of context above/below",x,0)]),renderShape:"custom",docs:L("Navigation"),handler:pB},{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:_([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:L("Navigation"),handler:fB},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:_([p("--forward","Forward slice (what does this affect). Default is backward."),p("--depth <n>","Max transitive depth for backward slice",x,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:L("Navigation"),handler:gB}];var hB=Q("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=O(n,"limit",20),o=Uc(e,H(t,0),{semantic:r.semantic,impactDepth:P(n,"impactDepth",3),sliceDepth:P(n,"sliceDepth",3),scope:E(n,"scope")});if(o.warnings.length===1&&o.warnings[0]==="No symbol, file, or module matched target."){if(C(n,"json")){M("plan-context",t,n,o);return}return D.empty(o.warnings[0])}if(C(n,"json")){M("plan-context",t,n,o);return}let s=[{title:"TARGET",rows:yB(o)},{title:"DEFINITIONS",rows:bB(o,i),skipIfEmpty:!0},{title:"REFERENCES",rows:SB(o,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:xB(o,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:CB(o,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:vB(o,i),skipIfEmpty:!0},{title:"SURFACE",rows:RB(o,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:kB(o,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:wB(o,i),skipIfEmpty:!0},{title:"HISTORY",rows:LB(o),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:IB(o),skipIfEmpty:!0}];D.sectionedReport(s)}),gb=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:_([p("--impact-depth <n>","Maximum affected traversal depth",x,3),p("--slice-depth <n>","Maximum backward slice depth",x,3),p("-s, --scope <path>","Limit downstream impact to files matching path"),p("-n, --limit <n>","Rows per section",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:L("Planning",["scip-query plan-context parseSymbol"]),handler:hB}];function yB(e){return[`Target: ${e.target}`,`Matched: symbol=${Zl(e.matched.symbol)} file=${Zl(e.matched.file)} module=${Zl(e.matched.module)}`]}function bB(e,t){let n=[];for(let r of e.trace.definitions){let i=r.signature?` -- ${r.signature}`:"";n.push(` ${Se(r.relativePath,r.startLine,r.endLine)}${i}`),r.source&&n.push(...r.source.split(`
972
- `).map((o,s)=>` ${String(je(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${Re(r.startLine,r.endLine)} ${r.shortName}`)),nn(n,t).rows}function SB(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${je(r.line)} in ${r.enclosingShort}`);return qn(nn(n,t))}function xB(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 qn(nn([...n,...r],t))}function CB(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}:${je(o.line)} in ${o.enclosingShort}`);return qn(nn([...n,...r,...i],t))}function vB(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 qn(nn(n,t))}function RB(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${Re(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return qn(nn(n,t))}function kB(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 qn(nn(n,t))}function wB(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` ${Re(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${Se(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}`)),qn(nn(n,t))}function LB(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 IB(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 nn(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function qn(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function Zl(e){return e?"yes":"no"}var hb=["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"],DB=[ub,fb,db,qs,pb,gb,mb],yb=DB.flat(),PB=new Map(yb.map(e=>[e.id,e]));for(let e of yb)if(!hb.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Or=hb.map(e=>NB(e));function NB(e){let t=PB.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var EB=Or.slice(0,eu("plan-context")),TB=Or.slice(Us("drift"),eu("self-audit")),_B=Or.slice(Us("convergence"),eu("slice")),FB=Or.slice(Us("redundant-reexports")),bb=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[p("-l, --language <lang>","Index only this language (can be repeated)",Ti,[]),p("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),p("--force","Rebuild even if source inputs are unchanged"),p("--allow-partial","Write an incomplete index when one or more detected languages fail"),p("--indexer-concurrency <n>","Number of language indexers to run at once",_i)],renderShape:"custom",docs:L("Indexing",["scip-query reindex"]),handler:uy},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:L("Indexing"),handler:dy},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[p("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:L("Indexing"),handler:my},...EB,{id:hs,command:hs,description:"Internal diff-impact batch worker",hidden:!0,options:[p("--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:_([p("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:L("Impact"),handler:fy},...TB,{id:Ei,command:Ei,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:gy},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[p("-s, --scope <path>","Limit to files matching path"),p("--full","Compatibility flag; health already runs unbounded candidate analyses by default"),p("--json","Output as JSON for programmatic consumption"),p("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),p("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:L("Health",["scip-query health --json","scip-query health --baseline"]),handler:hy},{id:"bench",command:"bench",description:"Benchmark indexing and command runtimes for this repository",options:[p("--json","Output as JSON for programmatic consumption"),p("--cold-index","Temporarily clear this project index cache and measure a cold rebuild"),p("--include-heavy","Include expensive full-detector commands in the command matrix"),p("--command <cmd>","Benchmark a specific scip-query command (can be repeated)",Ti,[]),p("--timeout-ms <n>","Per-command timeout in milliseconds",_i,18e4)],renderShape:"custom",docs:L("Maintenance",["scip-query bench","scip-query bench --json --cold-index"]),handler:yy},..._B,{id:"install-skills",command:"install-skills",description:`Install skills (${Gl.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:L("Maintenance"),handler:xy},{id:"setup-hooks",command:"setup-hooks",description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:L("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:Cy},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:jh},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:Oh},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:L("Maintenance"),handler:vy},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:L("Maintenance"),handler:Ry},{id:"capability-matrix",command:"capability-matrix",description:"Report the evidence and verification capability matrix by language",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:L("Maintenance"),handler:ky},...FB,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:L("Maintenance"),handler:Ly},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:L("Maintenance",["scip-query config-validate"]),handler:Iy},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding in .scipquery.json with a required reason",options:_([p("--reason <text>","Required human reason for accepting the finding"),p("--check <check>","Optional detector/check name to narrow the suppression"),p("--file <path>","Optional file path to narrow the suppression"),p("--expires-at <iso>","Optional ISO date after which the suppression expires")]),renderShape:"custom",docs:L("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:Dy},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:L("Maintenance"),handler:Py},{id:"setup",command:"setup",description:"Bootstrap this project: install agent skills, refresh the index, verify capabilities, and report health",options:_([p("--git-hook","Also install a git pre-commit hook that runs diff-gate")]),renderShape:"custom",docs:L("Maintenance",["scip-query setup","scip-query setup --json"]),handler:Ty},{id:"setup-agent",command:"setup-agent",description:"Seed agent guidance for this project: AGENTS.md/CLAUDE.md block pointing agents at the scip-query skills and diff gate, plus an optional git pre-commit backstop",options:[p("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:L("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:Ey},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[p("--force","Overwrite an existing workflow"),p("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:L("Maintenance",["scip-query setup-ci"]),handler:_y},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[p("--debounce <ms>","Ms to wait after last change (default: 30000)",Ss),p("--cooldown <ms>","Min ms between reindexes (default: 60000)",Ss),p("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",Ss)],renderShape:"custom",docs:L("Maintenance"),handler:Fy},{id:"status",command:"status",description:"Show index status for this project",options:[p("--json","Output as JSON for programmatic consumption"),p("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:L("Maintenance"),handler:$y}];function Us(e){let t=Or.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function eu(e){return Us(e)+1}function Sb(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){$B(o)}}),{descriptor:n,command:r}})}function $B(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${t}`),process.exitCode=1}import{existsSync as AB,mkdirSync as MB,readFileSync as jB,writeFileSync as OB}from"fs";import{homedir as BB}from"os";import{join as Ws}from"path";var HB=1440*60*1e3,Cb="update-check.json",VB="https://registry.npmjs.org/scip-query/latest";async function vb(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let n=e.cacheDir??WB(t),r=e.now??Date.now(),i=e.currentVersion??gs,o=GB(n),s=o&&r-o.checkedAt<HB?o.latestVersion:await zB(n,e.fetchLatestVersion??KB,r);if(!s||!UB(s,i))return;(e.writeNotice??(c=>console.error(c)))(qB(i,s))}function qB(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
973
- `)}function UB(e,t){let n=xb(e),r=xb(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 WB(e){let t=e.XDG_CACHE_HOME||Ws(BB(),".cache");return Ws(t,"scip-query")}function GB(e){let t=Ws(e,Cb);if(!AB(t))return null;try{let n=JSON.parse(jB(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 zB(e,t,n){let r;try{r=await t()}catch{r=null}return JB(e,{checkedAt:n,latestVersion:r}),r}function JB(e,t){try{MB(e,{recursive:!0}),OB(Ws(e,Cb),`${JSON.stringify(t,null,2)}
974
- `)}catch{}}async function KB(){let e=await fetch(VB,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function xb(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}Gs.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(gs);Sb(Gs,bb);Gs.hook("preAction",async()=>{await vb()});QB()&&await Gs.parseAsync();function QB(){if(!process.argv[1])return!1;let e=XB(import.meta.url);try{return Rb(e)===Rb(process.argv[1])}catch{return e===process.argv[1]}}export{Gs as program,Tr as renderHeuristicNotice};
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};
975
1026
  //# sourceMappingURL=cli.js.map