scip-query 0.19.3 → 0.19.4

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 (268) hide show
  1. package/README.md +1 -1
  2. package/dist/augment-vue-worker.js +1 -1
  3. package/dist/{chunk-LSJDKJIB.js → chunk-25LPM4DG.js} +2 -2
  4. package/dist/chunk-2CTX5CMX.js +4 -0
  5. package/dist/chunk-2Y373BDD.js +2 -0
  6. package/dist/{chunk-24ET4VLC.js → chunk-2YU7I3QO.js} +2 -2
  7. package/dist/{chunk-QNO3QIMN.js → chunk-3MJ5YA4Y.js} +2 -2
  8. package/dist/{chunk-B26UX7ZD.js → chunk-3SVWW4PN.js} +2 -2
  9. package/dist/{chunk-WWCZCH7W.js → chunk-4333ETTV.js} +2 -2
  10. package/dist/{chunk-6EWBPAA3.js → chunk-4RSI5EMG.js} +2 -2
  11. package/dist/{chunk-CIYUFF24.js → chunk-4SALD7RU.js} +2 -2
  12. package/dist/{chunk-XWE7PZQH.js → chunk-4T3LTWUS.js} +2 -2
  13. package/dist/{chunk-34MLC6UI.js → chunk-4XTA5OMB.js} +2 -2
  14. package/dist/chunk-52ZYCAEO.js +2 -0
  15. package/dist/{chunk-SJ6XSCG7.js → chunk-54HA4ZXH.js} +2 -2
  16. package/dist/{chunk-J4MYRIYT.js → chunk-64RFXJT5.js} +2 -2
  17. package/dist/{chunk-FUFNRZFJ.js → chunk-6E7UTQY7.js} +2 -2
  18. package/dist/{chunk-PNESKY2Z.js → chunk-6NSFJYRC.js} +2 -2
  19. package/dist/{chunk-AOSFSYEA.js → chunk-7B3UPBVA.js} +2 -2
  20. package/dist/{chunk-4BUMNEYQ.js → chunk-7GXM52MI.js} +2 -2
  21. package/dist/{chunk-SOS256TP.js → chunk-A2EZV2UM.js} +2 -2
  22. package/dist/{chunk-6FIA5BEB.js → chunk-ABMYA4TN.js} +2 -2
  23. package/dist/{chunk-64QITTX7.js → chunk-B5NLK2B3.js} +2 -2
  24. package/dist/{chunk-OLG2YPLS.js → chunk-BTEE5NZQ.js} +2 -2
  25. package/dist/{chunk-MP43RX4O.js → chunk-C7NIYIQ4.js} +1 -1
  26. package/dist/{chunk-AEM24WSF.js → chunk-CFMXJPHH.js} +2 -2
  27. package/dist/{chunk-HHOJH3RJ.js → chunk-CNKAGUPL.js} +2 -2
  28. package/dist/{chunk-MQ2B33LQ.js → chunk-D4U5Q3FT.js} +2 -2
  29. package/dist/{chunk-YZXV3CU3.js → chunk-DGAGY7RJ.js} +1 -1
  30. package/dist/{chunk-FRXB74RQ.js → chunk-DLWR3NUU.js} +5 -5
  31. package/dist/{chunk-YGQBJUS6.js → chunk-DZ74OMG6.js} +2 -2
  32. package/dist/{chunk-APLNTJPJ.js → chunk-EOOJGLDU.js} +2 -2
  33. package/dist/{chunk-TYEGFDOP.js → chunk-F6O7AAC3.js} +2 -2
  34. package/dist/{chunk-HFBNIIZX.js → chunk-FECYOO5O.js} +2 -2
  35. package/dist/{chunk-AFVU2GB2.js → chunk-FWUUZTIO.js} +2 -2
  36. package/dist/{chunk-KMOMNTB4.js → chunk-GBQ5NYPR.js} +2 -2
  37. package/dist/{chunk-2ROSOG2I.js → chunk-GPBBJ5Y4.js} +2 -2
  38. package/dist/{chunk-IXAALOUP.js → chunk-H7UKLTWJ.js} +2 -2
  39. package/dist/{chunk-YILKXTIY.js → chunk-HEXVUYFQ.js} +2 -2
  40. package/dist/{chunk-J5XJWCB3.js → chunk-HKEHS2AS.js} +2 -2
  41. package/dist/{chunk-JRCJEHRG.js → chunk-I5AWSI2G.js} +2 -2
  42. package/dist/{chunk-XYBNOILR.js → chunk-I5RJM53C.js} +2 -2
  43. package/dist/{chunk-AD7WUFFT.js → chunk-IG7N5ZIK.js} +2 -2
  44. package/dist/{chunk-C3KCSAQ4.js → chunk-IUFDSKGG.js} +2 -2
  45. package/dist/{chunk-OQ6TCHBB.js → chunk-IZKFSVBV.js} +2 -2
  46. package/dist/{chunk-5OZCNAVM.js → chunk-J77UIT3I.js} +2 -2
  47. package/dist/{chunk-EGKWRX5I.js → chunk-K2ERX4UT.js} +2 -2
  48. package/dist/{chunk-FYE4PWWP.js → chunk-KP6XRY5Z.js} +2 -2
  49. package/dist/{chunk-FC5K7T35.js → chunk-L7SPDE73.js} +1 -1
  50. package/dist/{chunk-YGBHQOB2.js → chunk-LBMJEAEW.js} +2 -2
  51. package/dist/chunk-LHMNRHGV.js +3 -0
  52. package/dist/{chunk-5TZ2MQBG.js → chunk-M7AIS73L.js} +2 -2
  53. package/dist/{chunk-53SUJOJA.js → chunk-M7MTH5NR.js} +2 -2
  54. package/dist/{chunk-HNTLCR4F.js → chunk-MITTUCEH.js} +2 -2
  55. package/dist/{chunk-5GCAM4JE.js → chunk-MSWVMDAH.js} +6 -6
  56. package/dist/chunk-NH5ALKPW.js +2 -0
  57. package/dist/{chunk-EHU4TZJJ.js → chunk-NPKYOIFM.js} +3 -3
  58. package/dist/{chunk-XWJ3JYRG.js → chunk-NRCXJDHL.js} +2 -2
  59. package/dist/{chunk-5GOBZI34.js → chunk-NSS46APD.js} +2 -2
  60. package/dist/{chunk-5FUAFNMP.js → chunk-NZL2DBT7.js} +2 -2
  61. package/dist/{chunk-C3VQZFP2.js → chunk-OMPZHGHO.js} +2 -2
  62. package/dist/{chunk-XYNWAZ6J.js → chunk-P2PC2WGR.js} +2 -2
  63. package/dist/{chunk-CAKPEQZB.js → chunk-Q3AFUTGB.js} +2 -2
  64. package/dist/{chunk-ZJGZCBYT.js → chunk-Q4IIEGXJ.js} +2 -2
  65. package/dist/chunk-QDV6RDCP.js +4 -0
  66. package/dist/{chunk-FTRNGQGR.js → chunk-QGXBRIM5.js} +2 -2
  67. package/dist/{chunk-WXVGNFAO.js → chunk-QOKYJ33H.js} +1 -1
  68. package/dist/{chunk-FB6IKAKZ.js → chunk-QRGV2F7L.js} +2 -2
  69. package/dist/chunk-QVWS2VWZ.js +7 -0
  70. package/dist/{chunk-77IOFJVY.js → chunk-R4FQGQ4X.js} +2 -2
  71. package/dist/{chunk-4CZJ4YJB.js → chunk-RV2FQIX3.js} +2 -2
  72. package/dist/{chunk-4FMT4HPC.js → chunk-S44IULR6.js} +2 -2
  73. package/dist/{chunk-PCIFZHWS.js → chunk-SOAT6NLA.js} +2 -2
  74. package/dist/{chunk-TDUU63FC.js → chunk-STOL2BTL.js} +2 -2
  75. package/dist/chunk-SVLTAG5O.js +927 -0
  76. package/dist/{chunk-2WCXKANA.js → chunk-U6WNH5GC.js} +2 -2
  77. package/dist/chunk-U7DSEKOM.js +30 -0
  78. package/dist/{chunk-EII5ZHL2.js → chunk-UKZBVX4U.js} +2 -2
  79. package/dist/chunk-UOAV44HR.js +38 -0
  80. package/dist/{chunk-VIKEPD4D.js → chunk-VGRICIQI.js} +2 -2
  81. package/dist/{chunk-TOIS2VAI.js → chunk-VMNZB6WI.js} +2 -2
  82. package/dist/{chunk-JFO2UVQP.js → chunk-VTKGCT3V.js} +5 -5
  83. package/dist/{chunk-PJENL245.js → chunk-VXQNNXJE.js} +2 -2
  84. package/dist/{chunk-HAC5EI2T.js → chunk-WER3B7MI.js} +2 -2
  85. package/dist/{chunk-5OR4QRPR.js → chunk-WQTAC523.js} +2 -2
  86. package/dist/{chunk-GAE7WCBK.js → chunk-X6D5IC6I.js} +2 -2
  87. package/dist/{chunk-FBUNGRKI.js → chunk-XLTP42QA.js} +2 -2
  88. package/dist/chunk-XTX6QHOF.js +4 -0
  89. package/dist/{chunk-AYRHVJXW.js → chunk-XYADIZHU.js} +5 -5
  90. package/dist/{chunk-WAU7HVDI.js → chunk-YGAGTIDK.js} +2 -2
  91. package/dist/{chunk-IICQP2DY.js → chunk-YIJ7ZAA4.js} +3 -3
  92. package/dist/{chunk-EYF5HOUZ.js → chunk-YNRNA5LK.js} +2 -2
  93. package/dist/{chunk-QKW7ISEW.js → chunk-YVVCVR2L.js} +2 -2
  94. package/dist/{chunk-MRYPDVOS.js → chunk-ZAIILQNP.js} +3 -3
  95. package/dist/{chunk-Z7M7X3ZG.js → chunk-ZGZUZ7XE.js} +2 -2
  96. package/dist/{chunk-PTYQQHZM.js → chunk-ZXJYMGD3.js} +2 -2
  97. package/dist/cli.js +2 -2
  98. package/dist/{command-descriptors-QJEYYND2.js → command-descriptors-MFU4BCJ7.js} +55 -50
  99. package/dist/{config-types-BA3xLCfG.d.ts → config-types-D20KuvvZ.d.ts} +67 -0
  100. package/dist/{db-CzA-9_rL.d.ts → db-G_II8yXU.d.ts} +1 -1
  101. package/dist/diff-gate-types-C9BoYwYD.d.ts +10 -0
  102. package/dist/direct-navigation-MRMQFIRB.js +3 -0
  103. package/dist/{health-DYy13GAe.d.ts → health-oblXYgkF.d.ts} +1 -1
  104. package/dist/index.d.ts +2 -2
  105. package/dist/index.js +1 -1
  106. package/dist/queries/affected.d.ts +2 -2
  107. package/dist/queries/affected.js +1 -1
  108. package/dist/queries/architecture.d.ts +86 -4
  109. package/dist/queries/architecture.js +1 -1
  110. package/dist/queries/bottlenecks.d.ts +2 -2
  111. package/dist/queries/bottlenecks.js +1 -1
  112. package/dist/queries/by-kind.d.ts +2 -2
  113. package/dist/queries/by-kind.js +1 -1
  114. package/dist/queries/call-graph.d.ts +2 -2
  115. package/dist/queries/call-graph.js +1 -1
  116. package/dist/queries/change-surface.d.ts +2 -2
  117. package/dist/queries/change-surface.js +1 -1
  118. package/dist/queries/cleanup-plan.d.ts +2 -2
  119. package/dist/queries/cleanup-plan.js +1 -1
  120. package/dist/queries/co-change.d.ts +2 -2
  121. package/dist/queries/co-change.js +1 -1
  122. package/dist/queries/code.d.ts +2 -2
  123. package/dist/queries/code.js +1 -1
  124. package/dist/queries/complexity-hotspots.d.ts +2 -2
  125. package/dist/queries/complexity-hotspots.js +1 -1
  126. package/dist/queries/complexity.d.ts +2 -2
  127. package/dist/queries/complexity.js +1 -1
  128. package/dist/queries/convergence.d.ts +2 -2
  129. package/dist/queries/convergence.js +1 -1
  130. package/dist/queries/coupling.d.ts +2 -2
  131. package/dist/queries/coupling.js +1 -1
  132. package/dist/queries/cycles.d.ts +2 -2
  133. package/dist/queries/cycles.js +1 -1
  134. package/dist/queries/dataflow.d.ts +2 -2
  135. package/dist/queries/dataflow.js +1 -1
  136. package/dist/queries/dead.d.ts +2 -2
  137. package/dist/queries/dead.js +1 -1
  138. package/dist/queries/decorative-checkers.d.ts +2 -2
  139. package/dist/queries/decorative-checkers.js +1 -1
  140. package/dist/queries/deep-chains.d.ts +2 -2
  141. package/dist/queries/deep-chains.js +1 -1
  142. package/dist/queries/deps.d.ts +2 -2
  143. package/dist/queries/deps.js +1 -1
  144. package/dist/queries/diff-gate.d.ts +3 -3
  145. package/dist/queries/diff-gate.js +1 -1
  146. package/dist/queries/diff-impact.d.ts +4 -8
  147. package/dist/queries/diff-impact.js +1 -1
  148. package/dist/queries/doc-drift.d.ts +3 -3
  149. package/dist/queries/doc-drift.js +1 -1
  150. package/dist/queries/drift.d.ts +2 -2
  151. package/dist/queries/drift.js +1 -1
  152. package/dist/queries/duplicate-bodies.d.ts +2 -2
  153. package/dist/queries/duplicate-bodies.js +1 -1
  154. package/dist/queries/extract-candidates.d.ts +2 -2
  155. package/dist/queries/extract-candidates.js +1 -1
  156. package/dist/queries/fan.d.ts +2 -2
  157. package/dist/queries/fan.js +1 -1
  158. package/dist/queries/files.d.ts +2 -2
  159. package/dist/queries/health.d.ts +3 -3
  160. package/dist/queries/health.js +1 -1
  161. package/dist/queries/hierarchy.d.ts +2 -2
  162. package/dist/queries/hierarchy.js +1 -1
  163. package/dist/queries/hotspots.d.ts +2 -2
  164. package/dist/queries/hotspots.js +1 -1
  165. package/dist/queries/imports.d.ts +2 -2
  166. package/dist/queries/imports.js +1 -1
  167. package/dist/queries/incomplete-migration.d.ts +3 -2
  168. package/dist/queries/incomplete-migration.js +1 -1
  169. package/dist/queries/index.d.ts +21 -5
  170. package/dist/queries/index.js +1 -1
  171. package/dist/queries/isolated.d.ts +2 -2
  172. package/dist/queries/isolated.js +1 -1
  173. package/dist/queries/locality-candidates.d.ts +2 -2
  174. package/dist/queries/locality-candidates.js +1 -1
  175. package/dist/queries/members.d.ts +2 -2
  176. package/dist/queries/members.js +1 -1
  177. package/dist/queries/methods.d.ts +2 -2
  178. package/dist/queries/methods.js +1 -1
  179. package/dist/queries/not-implemented.d.ts +2 -2
  180. package/dist/queries/not-implemented.js +1 -1
  181. package/dist/queries/outline.d.ts +2 -2
  182. package/dist/queries/outline.js +1 -1
  183. package/dist/queries/passthrough-candidates.d.ts +2 -2
  184. package/dist/queries/passthrough-candidates.js +1 -1
  185. package/dist/queries/plan-context.d.ts +2 -2
  186. package/dist/queries/plan-context.js +1 -1
  187. package/dist/queries/react-component-duplicates.d.ts +2 -2
  188. package/dist/queries/react-component-duplicates.js +1 -1
  189. package/dist/queries/react-hook-candidates.d.ts +2 -2
  190. package/dist/queries/react-hook-candidates.js +1 -1
  191. package/dist/queries/react-large-component-pressure.d.ts +2 -2
  192. package/dist/queries/react-large-component-pressure.js +1 -1
  193. package/dist/queries/recent-duplicates.d.ts +2 -2
  194. package/dist/queries/recent-duplicates.js +1 -1
  195. package/dist/queries/redundant-reexports.d.ts +2 -2
  196. package/dist/queries/redundant-reexports.js +1 -1
  197. package/dist/queries/refs.d.ts +2 -2
  198. package/dist/queries/refs.js +1 -1
  199. package/dist/queries/self-audit.d.ts +2 -2
  200. package/dist/queries/self-audit.js +1 -1
  201. package/dist/queries/similar-chains.d.ts +2 -2
  202. package/dist/queries/similar-chains.js +1 -1
  203. package/dist/queries/similar-files.d.ts +2 -2
  204. package/dist/queries/similar-files.js +1 -1
  205. package/dist/queries/similar-signatures.d.ts +2 -2
  206. package/dist/queries/similar-signatures.js +1 -1
  207. package/dist/queries/similar.d.ts +2 -2
  208. package/dist/queries/similar.js +1 -1
  209. package/dist/queries/slice.d.ts +2 -2
  210. package/dist/queries/slice.js +1 -1
  211. package/dist/queries/stale-abstractions.d.ts +2 -2
  212. package/dist/queries/stale-abstractions.js +1 -1
  213. package/dist/queries/stats.d.ts +2 -2
  214. package/dist/queries/surface.d.ts +2 -2
  215. package/dist/queries/surface.js +1 -1
  216. package/dist/queries/symbols.d.ts +2 -2
  217. package/dist/queries/symbols.js +1 -1
  218. package/dist/queries/system.d.ts +2 -2
  219. package/dist/queries/system.js +1 -1
  220. package/dist/queries/test-quality.d.ts +2 -2
  221. package/dist/queries/test-quality.js +1 -1
  222. package/dist/queries/trace.d.ts +2 -2
  223. package/dist/queries/trace.js +1 -1
  224. package/dist/queries/twin-ab.d.ts +2 -2
  225. package/dist/queries/twin-ab.js +1 -1
  226. package/dist/queries/twin-drift.d.ts +2 -2
  227. package/dist/queries/twin-drift.js +1 -1
  228. package/dist/queries/unused-imports.d.ts +2 -2
  229. package/dist/queries/unused-imports.js +1 -1
  230. package/dist/queries/unused-params.d.ts +2 -2
  231. package/dist/queries/unused-params.js +1 -1
  232. package/dist/queries/vue-component-duplicates.d.ts +2 -2
  233. package/dist/queries/vue-component-duplicates.js +1 -1
  234. package/dist/queries/vue-composable-candidates.d.ts +2 -2
  235. package/dist/queries/vue-composable-candidates.js +1 -1
  236. package/dist/queries/vue-large-view-pressure.d.ts +2 -2
  237. package/dist/queries/vue-large-view-pressure.js +1 -1
  238. package/dist/queries/wrapper-candidates.d.ts +2 -2
  239. package/dist/queries/wrapper-candidates.js +1 -1
  240. package/dist/reindex-worker.js +7 -7
  241. package/dist/reindex.d.ts +3 -3
  242. package/dist/reindex.js +1 -1
  243. package/dist/runtime.d.ts +3 -3
  244. package/dist/runtime.js +2 -2
  245. package/dist/rust-semantic-session-worker.js +1 -1
  246. package/dist/rust-semantic-worker.js +1 -1
  247. package/dist/{scip-cli-1bVKJgXi.d.ts → scip-cli-kRpaexVJ.d.ts} +1 -1
  248. package/dist/watch-server.js +4 -4
  249. package/docs/AI_FAILURE_MODES.md +1 -1
  250. package/docs/COMMAND_REFERENCE.md +1 -1
  251. package/docs/DETECTOR_GUIDE.md +1 -1
  252. package/docs/analyzer-inventory.md +1 -1
  253. package/docs/analyzer-validation-ledger.md +131 -1
  254. package/docs/architecture-coherence-vision.md +29 -0
  255. package/package.json +2 -2
  256. package/dist/chunk-26JI77AY.js +0 -927
  257. package/dist/chunk-2E7QY4B5.js +0 -7
  258. package/dist/chunk-33RLKB6L.js +0 -4
  259. package/dist/chunk-DO775SYA.js +0 -2
  260. package/dist/chunk-HCSTQGQE.js +0 -4
  261. package/dist/chunk-NLNZK7RL.js +0 -5
  262. package/dist/chunk-OAM22BCR.js +0 -2
  263. package/dist/chunk-PLDIXTKR.js +0 -38
  264. package/dist/chunk-UJKZQLDB.js +0 -2
  265. package/dist/chunk-WFWQWQK6.js +0 -3
  266. package/dist/chunk-XAMVIPE2.js +0 -29
  267. package/dist/diff-gate-types-CG2YQ_ei.d.ts +0 -4
  268. package/dist/direct-navigation-TT23TDBS.js +0 -3
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{c as kc,d as Qr,e as Nn,f as wc,g as $c,h as Cc,j as Pc}from"./chunk-TOIS2VAI.js";import{a as ot,b as x,c as Be,d as fe,e as $t,f as u,g as mc,h as P,i as $,j as oe,k as se,l as ve,m as Ut,n as Rc}from"./chunk-MRYPDVOS.js";import{$ as Cn,$a as _s,$b as ja,$c as ac,A as qo,Aa as fs,Ab as da,Ac as Ne,Ad as yc,B as vn,Bb as ua,Bd as Se,C as Bo,Ca as gs,Cb as pa,Cc as Ga,Cd as bc,D as Vo,Da as hs,Db as ma,Dc as Ua,Dd as de,E as xn,Ea as ys,Eb as fa,Ec as Ja,Ed as On,Fa as bs,Fb as ga,Fc as za,Fd as Sc,G as Bt,Ga as Ss,Gb as Wr,Gc as Ka,Gd as A,H as Ho,Ha as vs,Hb as xt,Hc as Qa,Hd as V,I as Wo,Ia as xs,Ib as En,Ic as Ya,Id as w,J as Go,Ja as Rs,Jb as jn,Jc as Xa,Jd as U,K as De,Ka as ks,Kb as ha,Kc as Za,Kd as b,L as ze,La as ws,Lb as ya,Lc as ec,Ld as Ct,M as Uo,Mb as ba,Mc as tc,Md as C,N as yt,Na as $s,Nb as Sa,Nc as nc,Nd as L,O as Rn,Oa as Cs,Ob as va,Oc as An,Od as vc,P as kn,Pa as Ps,Pb as xa,Pc as rc,Pd as I,Q as Jo,Qa as Ts,Qb as Ra,Qc as ic,Qd as xc,R as zo,Ra as Is,Rb as ka,Rc as Ln,Rd as G,S as Ko,Sa as Es,Sb as wa,Sc as oc,T as wn,Ta as js,Tb as $a,Tc as Gr,U as Qo,Ua as As,Ub as Ca,Uc as sc,V as bt,Va as Ls,Vb as be,Vc as Ur,W as St,Wa as Ds,Wb as Pa,X as Yo,Xa as Fs,Xb as Gt,Xc as Y,Y as Xo,Ya as Os,Yb as Ta,Z as $n,Za as Ns,Zb as Ia,Zc as Me,_ as Zo,_a as Ms,_b as Ea,_c as wt,aa as es,ab as Wt,ac as Aa,ba as Pn,bb as qs,bc as La,bd as ce,c as hn,cb as Bs,cc as Da,d as pe,da as ts,db as Vs,dc as Fa,dd as _e,e as yn,ea as ns,eb as Hs,ed as Jr,f as B,fa as Tn,fb as Ws,fc as Oa,fd as qe,g as J,ga as Vr,gb as Gs,gc as Na,gd as ie,hb as Us,hc as Ma,hd as M,ia as rs,ib as Js,id as Dn,ja as nt,jb as zs,jd as E,kb as Ks,kd as zr,lb as Qs,lc as Fe,ld as Kr,m as Mt,ma as Vt,mb as Ys,mc as Oe,md as Te,n as _t,na as is,nb as Xs,nc as Rt,nd as cc,o as qt,oa as os,ob as Zs,oc as _a,od as lc,p as Le,pa as ss,pb as ea,pc as me,pd as Fn,q as Do,qa as as,qb as Hr,qc as kt,qd as dc,r as bn,ra as Ht,rb as ta,rc as Ce,rd as uc,s as Fo,sa as cs,sb as na,sc as qa,sd as pc,t as Br,ta as ls,tb as ra,tc as Ba,u as Oo,ua as In,ub as ia,uc as Va,ud as le,v as No,va as ds,vb as oa,vc as rt,vd as K,w as Mo,wa as us,wb as sa,wc as Ha,wd as fc,x as _o,xa as ps,xb as aa,xc as Wa,xd as gc,y as Sn,ya as vt,yb as ca,yc as it,yd as hc,z as Q,za as ms,zb as la,zc as Pe,zd as Ke}from"./chunk-26JI77AY.js";import{execFileSync as ll,spawn as Gg}from"child_process";import{existsSync as dt,mkdirSync as ui,readFileSync as dl,rmSync as Ug,writeFileSync as Jn}from"fs";import{homedir as Jg}from"os";import{dirname as zn,isAbsolute as zg,join as Qt,resolve as Kg}from"path";import{execFileSync as fg}from"child_process";import{existsSync as Tc,readdirSync as Ef}from"fs";import{isAbsolute as jf,join as Yr,resolve as Af}from"path";var Lf={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:yt.language,indexerBinary:yt.indexerBinary,checkCommand:`${yt.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:yt.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:yt.installUrl},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",jf(r)?r:Af(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Ic(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",Ic(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=Yr(e,"vendor","bin","scip-php"),r=Yr(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",Tc(r)?r:Tc(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function st(e){return Lf[e]}function Ic(e,t){let n;try{n=Ef(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Yr(e,i);return null}import{createRequire as Df}from"module";var Ff=Df(import.meta.url);function Ec(e,t=[]){let n=Of(),r=ls(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 Of(){try{return Ff.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as Pt,spawnSync as Nf}from"child_process";import{existsSync as xe,mkdtempSync as Dc,readFileSync as Mf,readdirSync as _f,rmSync as Fc,symlinkSync as qf,writeFileSync as Bf}from"fs";import{tmpdir as Oc}from"os";import{join as ae}from"path";var Vf=3e5,Hf=12;function ei(e,t,n={}){let r=ti(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],dirtyWorkingTree:Xr(e),batches:[]};let i=Jf(t,r),o=n.timeoutMs??Vf,s=Xf(e,t),a=Xr(e),c=Dc(ae(Oc(),"scip-cleanup-verify-")),l=[],d=new Map;try{Pt("git",["-C",e,"worktree","add","--detach","--force",c,"HEAD"],{stdio:"ignore"}),Zf(e,c);for(let p of r)d.set(p.label,Ac(p,c,o).rawErrors);for(let p of t.batches){Mc(c,p);let m=null;for(let f of r){let g=Ac(f,c,o),h=Wf(g,d.get(f.label)??[],g.rawErrors);if(h.status==="failed"){let y=h.errors.length>0?h.errors:g.outputTail;m={depth:p.depth,status:"failed",reason:`${f.label}: ${h.reason}`,errors:y.slice(0,Hf)};break}}if(!m)l.push({depth:p.depth,status:"verified"});else{l.push(m);break}}}finally{try{Pt("git",["-C",e,"worktree","remove","--force",c],{stdio:"ignore"})}catch{Fc(c,{recursive:!0,force:!0})}}return{checkers:r.map(p=>p.label),uncoveredFiles:i,baselineErrors:[...d.values()].reduce((p,m)=>p+m.length,0),dirtyOverlap:s,dirtyWorkingTree:a,batches:l}}function Wf(e,t,n){let r=Gf(t,n);return r.length>0?{status:"failed",reason:"checker reported new errors",errors:r}:e.ok?{status:"verified",reason:"checker passed",errors:[]}:{status:"failed",reason:`checker exited ${e.exitCode===null?"unknown":String(e.exitCode)} with unparsed output`,errors:[...e.outputTail??[]]}}function Gf(e,t){let n=Uf(e),r=new Map,i=[];for(let o of t){let s=Nc(o),a=(r.get(s)??0)+1;r.set(s,a),a>(n.get(s)??0)&&i.push(o)}return i}function Uf(e){let t=new Map;for(let n of e){let r=Nc(n);t.set(r,(t.get(r)??0)+1)}return t}function Jf(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 Nc(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var jc=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],zf=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function ti(e){let t=[];if(xe(ae(e,"tsconfig.json"))){let n=ae(e,"node_modules",".bin","tsc");t.push(xe(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:jc,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:jc,strength:"reference-aware"})}if(xe(ae(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"],strength:"reference-aware"}),["pyproject.toml","setup.py","requirements.txt"].some(n=>xe(ae(e,n)))){let n=Kf();n&&t.push(n)}if(zf.some(n=>xe(ae(e,n)))){let n=Qf(e);n&&t.push(n)}for(let n of Yf(e))t.push({label:`cargo check --quiet --manifest-path ${n}`,binary:"cargo",args:["check","--quiet","--message-format","json","--manifest-path",n],coversExtensions:[".rs"],strength:"reference-aware",env:{...process.env,CARGO_TARGET_DIR:ae(e,n,"..","target")}});return t}function Kf(){return De("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--output-format","json","--select","E9,F821,F822","."],coversExtensions:[".py"],strength:"reference-aware"}:De("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function Qf(e){let t=ae(e,"node_modules",".bin","clj-kondo");return xe(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...yn],strength:"reference-aware"}:De("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...yn],strength:"reference-aware"}:De("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...yn],strength:"reference-aware"}:null}function Yf(e){let t=[];if(xe(ae(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=_f(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||xe(ae(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function Xf(e,t){let n=new Set(Xr(e));return[...new Set(t.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>n.has(i)).sort()}function Xr(e){let t;try{t=Pt("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}return t.split(`
3
- `).map(n=>n.slice(3).trim()).filter(n=>n!=="").sort()}function Zf(e,t){for(let n of["node_modules"]){let r=ae(e,n),i=ae(t,n);if(xe(r)&&!xe(i))try{qf(r,i,"junction")}catch{}}}function Mc(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=ae(e,r);xe(o)&&Bf(o,eg(Mf(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function ni(e,t){for(let n of t)Mc(e,n)}function _c(e,t){let n=Dc(ae(Oc(),"scip-cleanup-patch-"));try{return Pt("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),ni(n,t),Pt("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{Pt("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{Fc(n,{recursive:!0,force:!0})}}}function ri(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 ii(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 verified by the detected checker(s).`);return r}function eg(e,t,n={}){let r=e.split(`
2
+ import{c as kc,d as Qr,e as Nn,f as wc,g as $c,h as Cc,j as Pc}from"./chunk-VMNZB6WI.js";import{a as ot,b as x,c as qe,d as fe,e as $t,f as u,g as mc,h as P,i as $,j as oe,k as se,l as ve,m as Ut,n as Rc}from"./chunk-ZAIILQNP.js";import{$ as Cn,$a as _s,$b as ja,$c as ac,A as Bo,Aa as fs,Ab as da,Ac as Ne,Ad as yc,B as vn,Bb as ua,Bd as Se,C as qo,Ca as gs,Cb as pa,Cc as Ga,Cd as bc,D as Vo,Da as hs,Db as ma,Dc as Ua,Dd as de,E as xn,Ea as ys,Eb as fa,Ec as Ja,Ed as On,Fa as bs,Fb as ga,Fc as za,Fd as Sc,G as qt,Ga as Ss,Gb as Wr,Gc as Ka,Gd as A,H as Ho,Ha as vs,Hb as xt,Hc as Qa,Hd as V,I as Wo,Ia as xs,Ib as En,Ic as Ya,Id as w,J as Go,Ja as Rs,Jb as jn,Jc as Xa,Jd as U,K as De,Ka as ks,Kb as ha,Kc as Za,Kd as b,L as ze,La as ws,Lb as ya,Lc as ec,Ld as Ct,M as Uo,Mb as ba,Mc as tc,Md as C,N as yt,Na as $s,Nb as Sa,Nc as nc,Nd as L,O as Rn,Oa as Cs,Ob as va,Oc as An,Od as vc,P as kn,Pa as Ps,Pb as xa,Pc as rc,Pd as I,Q as Jo,Qa as Ts,Qb as Ra,Qc as ic,Qd as xc,R as zo,Ra as Is,Rb as ka,Rc as Ln,Rd as G,S as Ko,Sa as Es,Sb as wa,Sc as oc,T as wn,Ta as js,Tb as $a,Tc as Gr,U as Qo,Ua as As,Ub as Ca,Uc as sc,V as bt,Va as Ls,Vb as be,Vc as Ur,W as St,Wa as Ds,Wb as Pa,X as Yo,Xa as Fs,Xb as Gt,Xc as Y,Y as Xo,Ya as Os,Yb as Ta,Z as $n,Za as Ns,Zb as Ia,Zc as Me,_ as Zo,_a as Ms,_b as Ea,_c as wt,aa as es,ab as Wt,ac as Aa,ba as Pn,bb as Bs,bc as La,bd as ce,c as hn,cb as qs,cc as Da,d as pe,da as ts,db as Vs,dc as Fa,dd as _e,e as yn,ea as ns,eb as Hs,ed as Jr,f as q,fa as Tn,fb as Ws,fc as Oa,fd as Be,g as J,ga as Vr,gb as Gs,gc as Na,gd as ie,hb as Us,hc as Ma,hd as M,ia as rs,ib as Js,id as Dn,ja as nt,jb as zs,jd as E,kb as Ks,kd as zr,lb as Qs,lc as Fe,ld as Kr,m as Mt,ma as Vt,mb as Ys,mc as Oe,md as Te,n as _t,na as is,nb as Xs,nc as Rt,nd as cc,o as Bt,oa as os,ob as Zs,oc as _a,od as lc,p as Le,pa as ss,pb as ea,pc as me,pd as Fn,q as Do,qa as as,qb as Hr,qc as kt,qd as dc,r as bn,ra as Ht,rb as ta,rc as Ce,rd as uc,s as Fo,sa as cs,sb as na,sc as Ba,sd as pc,t as qr,ta as ls,tb as ra,tc as qa,u as Oo,ua as In,ub as ia,uc as Va,ud as le,v as No,va as ds,vb as oa,vc as rt,vd as K,w as Mo,wa as us,wb as sa,wc as Ha,wd as fc,x as _o,xa as ps,xb as aa,xc as Wa,xd as gc,y as Sn,ya as vt,yb as ca,yc as it,yd as hc,z as Q,za as ms,zb as la,zc as Pe,zd as Ke}from"./chunk-SVLTAG5O.js";import{execFileSync as ll,spawn as Gg}from"child_process";import{existsSync as dt,mkdirSync as ui,readFileSync as dl,rmSync as Ug,writeFileSync as Jn}from"fs";import{homedir as Jg}from"os";import{dirname as zn,isAbsolute as zg,join as Qt,resolve as Kg}from"path";import{execFileSync as fg}from"child_process";import{existsSync as Tc,readdirSync as Ef}from"fs";import{isAbsolute as jf,join as Yr,resolve as Af}from"path";var Lf={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:yt.language,indexerBinary:yt.indexerBinary,checkCommand:`${yt.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:yt.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:yt.installUrl},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",jf(r)?r:Af(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Ic(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",Ic(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=Yr(e,"vendor","bin","scip-php"),r=Yr(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",Tc(r)?r:Tc(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function st(e){return Lf[e]}function Ic(e,t){let n;try{n=Ef(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Yr(e,i);return null}import{createRequire as Df}from"module";var Ff=Df(import.meta.url);function Ec(e,t=[]){let n=Of(),r=ls(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 Of(){try{return Ff.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as Pt,spawnSync as Nf}from"child_process";import{existsSync as xe,mkdtempSync as Dc,readFileSync as Mf,readdirSync as _f,rmSync as Fc,symlinkSync as Bf,writeFileSync as qf}from"fs";import{tmpdir as Oc}from"os";import{join as ae}from"path";var Vf=3e5,Hf=12;function ei(e,t,n={}){let r=ti(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],dirtyWorkingTree:Xr(e),batches:[]};let i=Jf(t,r),o=n.timeoutMs??Vf,s=Xf(e,t),a=Xr(e),c=Dc(ae(Oc(),"scip-cleanup-verify-")),l=[],d=new Map;try{Pt("git",["-C",e,"worktree","add","--detach","--force",c,"HEAD"],{stdio:"ignore"}),Zf(e,c);for(let p of r)d.set(p.label,Ac(p,c,o).rawErrors);for(let p of t.batches){Mc(c,p);let m=null;for(let f of r){let g=Ac(f,c,o),h=Wf(g,d.get(f.label)??[],g.rawErrors);if(h.status==="failed"){let y=h.errors.length>0?h.errors:g.outputTail;m={depth:p.depth,status:"failed",reason:`${f.label}: ${h.reason}`,errors:y.slice(0,Hf)};break}}if(!m)l.push({depth:p.depth,status:"verified"});else{l.push(m);break}}}finally{try{Pt("git",["-C",e,"worktree","remove","--force",c],{stdio:"ignore"})}catch{Fc(c,{recursive:!0,force:!0})}}return{checkers:r.map(p=>p.label),uncoveredFiles:i,baselineErrors:[...d.values()].reduce((p,m)=>p+m.length,0),dirtyOverlap:s,dirtyWorkingTree:a,batches:l}}function Wf(e,t,n){let r=Gf(t,n);return r.length>0?{status:"failed",reason:"checker reported new errors",errors:r}:e.ok?{status:"verified",reason:"checker passed",errors:[]}:{status:"failed",reason:`checker exited ${e.exitCode===null?"unknown":String(e.exitCode)} with unparsed output`,errors:[...e.outputTail??[]]}}function Gf(e,t){let n=Uf(e),r=new Map,i=[];for(let o of t){let s=Nc(o),a=(r.get(s)??0)+1;r.set(s,a),a>(n.get(s)??0)&&i.push(o)}return i}function Uf(e){let t=new Map;for(let n of e){let r=Nc(n);t.set(r,(t.get(r)??0)+1)}return t}function Jf(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 Nc(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var jc=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],zf=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function ti(e){let t=[];if(xe(ae(e,"tsconfig.json"))){let n=ae(e,"node_modules",".bin","tsc");t.push(xe(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:jc,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:jc,strength:"reference-aware"})}if(xe(ae(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"],strength:"reference-aware"}),["pyproject.toml","setup.py","requirements.txt"].some(n=>xe(ae(e,n)))){let n=Kf();n&&t.push(n)}if(zf.some(n=>xe(ae(e,n)))){let n=Qf(e);n&&t.push(n)}for(let n of Yf(e))t.push({label:`cargo check --quiet --manifest-path ${n}`,binary:"cargo",args:["check","--quiet","--message-format","json","--manifest-path",n],coversExtensions:[".rs"],strength:"reference-aware",env:{...process.env,CARGO_TARGET_DIR:ae(e,n,"..","target")}});return t}function Kf(){return De("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--output-format","json","--select","E9,F821,F822","."],coversExtensions:[".py"],strength:"reference-aware"}:De("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function Qf(e){let t=ae(e,"node_modules",".bin","clj-kondo");return xe(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...yn],strength:"reference-aware"}:De("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...yn],strength:"reference-aware"}:De("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...yn],strength:"reference-aware"}:null}function Yf(e){let t=[];if(xe(ae(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=_f(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||xe(ae(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function Xf(e,t){let n=new Set(Xr(e));return[...new Set(t.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>n.has(i)).sort()}function Xr(e){let t;try{t=Pt("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}return t.split(`
3
+ `).map(n=>n.slice(3).trim()).filter(n=>n!=="").sort()}function Zf(e,t){for(let n of["node_modules"]){let r=ae(e,n),i=ae(t,n);if(xe(r)&&!xe(i))try{Bf(r,i,"junction")}catch{}}}function Mc(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=ae(e,r);xe(o)&&qf(o,eg(Mf(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function ni(e,t){for(let n of t)Mc(e,n)}function _c(e,t){let n=Dc(ae(Oc(),"scip-cleanup-patch-"));try{return Pt("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),ni(n,t),Pt("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{Pt("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{Fc(n,{recursive:!0,force:!0})}}}function ri(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 ii(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 verified by the detected checker(s).`);return r}function eg(e,t,n={}){let r=e.split(`
4
4
  `),i=(n.rust===!0?tg(e):Do(e)).split(`
5
5
  `),o=new Set;for(let s of t){let a=ng(r,s.start),c=ig(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(`
6
6
  `)}function tg(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 ng(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 rg=200;function ig(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>rg)break}return n}function Ac(e,t,n){let r=Nf(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,env:e.env??process.env,maxBuffer:33554432}),i=`${r.stdout??""}
7
- ${r.stderr??""}`;if(r.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostics:[],parseBasis:"heuristic",outputTail:Lc(i)};let o=og(e.label,i),s=o.diagnostics.length>0?o.diagnostics:r.error?[{file:"",message:String(r.error),parseBasis:"heuristic"}]:[];return{ok:!1,exitCode:r.status,rawErrors:s.map(mg),diagnostics:s,parseBasis:o.parseBasis,outputTail:Lc(i)}}function og(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:sg(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:ag(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=cg(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:lg(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:dg(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:ug(t),parseBasis:"clj-kondo-json"}:{diagnostics:pg(t),parseBasis:"heuristic"}}function sg(e){let t=[],n=/^(.+?)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),code:r[4],message:r[5]??"",parseBasis:"tsc"});return t}function ag(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),message:r[4]??"",parseBasis:"go"});return t}function cg(e){let t=qc(e);if(!Array.isArray(t))return[];let n=[];for(let r of t){if(!r||typeof r!="object")continue;let i=r,o=i.location,s=o&&typeof o=="object"?o:{},a=typeof i.filename=="string"?i.filename:"",c=typeof i.message=="string"?i.message:"";!a&&!c||n.push({file:a,line:typeof s.row=="number"?s.row:void 0,column:typeof s.column=="number"?s.column:void 0,code:typeof i.code=="string"?i.code:void 0,message:c,parseBasis:"ruff-json"})}return n}function lg(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+([A-Z]\d{3})\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),code:r[4],message:r[5]??"",parseBasis:"ruff-text"});return t}function dg(e){let t=[];for(let n of e.split(`
8
- `)){if(!n.trim().startsWith("{"))continue;let r=Zr(n);if(!r||typeof r!="object")continue;let i=r;if(i.reason!=="compiler-message")continue;let o=i.message;if(!o||typeof o!="object")continue;let s=o;if(s.level!=="error")continue;let l=(Array.isArray(s.spans)?s.spans:[]).find(p=>!!p&&typeof p=="object"&&p.is_primary===!0),d=s.code;t.push({file:typeof l?.file_name=="string"?l.file_name:"",line:typeof l?.line_start=="number"?l.line_start:void 0,column:typeof l?.column_start=="number"?l.column_start:void 0,code:d&&typeof d=="object"&&typeof d.code=="string"?String(d.code):void 0,message:typeof s.message=="string"?s.message:"",parseBasis:"cargo-json"})}return t}function ug(e){let t=qc(e);if(!t||typeof t!="object")return[];let n=t.findings;if(!Array.isArray(n))return[];let r=[];for(let i of n){if(!i||typeof i!="object")continue;let o=i;o.level==="error"&&r.push({file:typeof o.filename=="string"?o.filename:"",line:typeof o.row=="number"?o.row:void 0,column:typeof o.col=="number"?o.col:void 0,code:typeof o.type=="string"?o.type:void 0,message:typeof o.message=="string"?o.message:"",parseBasis:"clj-kondo-json"})}return r}function pg(e){return e.split(`
9
- `).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function mg(e){let t=e.file.length>0?`${e.file}${e.line?`:${e.line}`:""}${e.column?`:${e.column}`:""}: `:"",n=e.code?`${e.code} `:"";return`${t}${n}${e.message}`.trim()}function qc(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return Zr(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(r=>r>=0));return Number.isFinite(n)?Zr(t.slice(n)):null}function Zr(e){try{return JSON.parse(e)}catch{return null}}function Lc(e,t=10){return e.split(`
10
- `).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var Hc={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".vue"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"],clojure:[".clj",".cljs",".cljc"]},gg={typescript:"typescript",javascript:"javascript",java:"java",scala:"scala",kotlin:"kotlin",rust:"rust",python:"python",ruby:"ruby",cpp:"cpp",c:"c",csharp:"csharp",vb:"vb",php:"php",clojure:"clojure"},hg={typescript:"javascript",javascript:"javascript",java:"jvm",scala:"jvm",kotlin:"jvm",rust:"rust",python:"python",ruby:"ruby",cpp:"c/cpp",c:"c/cpp",csharp:"dotnet",vb:"dotnet",dart:"dart",php:"php",clojure:"clojure"};function ge(e,t){let n=t.languages??rt(e),r=n.map(a=>{let c=wn(st(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),i=wg(e,n,t),o=oi({semantics:i},"typescript"),s=ti(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:r,semantics:i,semantic:o,checkers:s,gitAvailable:Pg(e)}}function Qe(e,t={}){let n=e.indexers.filter(c=>c.runnable).length,r=e.languages.length===0||n===0&&!t.hasIndexedGraph?"unavailable":n===e.indexers.length&&e.indexers.length>0?"available":"partial",i=r!=="unavailable",o=e.languages.map(c=>xg(e,c,{hasIndexedGraph:Rg(c,t),runtimeProbe:t.runtimeProbe})),s=o.map(c=>c.cleanupVerification.status),a=s.length===0||s.every(c=>c==="unavailable")?"unavailable":s.every(c=>c==="available")?"available":"partial";return{languages:e.languages,matrix:o,capabilities:[{id:"indexing",label:"SCIP indexing",status:r,evidence:"graph-fact",reason:r==="available"?"All detected/configured language indexers are runnable.":t.hasIndexedGraph?`An indexed graph is present; ${n}/${e.indexers.length} detected/configured language indexers are runnable for refresh.`:`${n}/${e.indexers.length} detected/configured language indexers are runnable.`},...yg(e),{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:i?"available":"unavailable",evidence:"heuristic",reason:i?"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index.":"Heuristic detectors need an indexed code graph."},{id:"cleanup-verification",label:"Project cleanup verification",status:a,evidence:"checker",reason:a!=="unavailable"?o.map(c=>`${c.language}: ${c.cleanupVerification.status} (${c.cleanupVerification.reason})`).join("; "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-gate",label:"Git diff gate",status:e.gitAvailable&&i?"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 yg(e){return bg(e).map(t=>{let n=oi(e,t),r=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${Sg(t)} semantic provider`,status:r,evidence:"semantic",reason:vg(t,n)}})}function bg(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of Gc(e))t.add(n.language);return[...t].sort((n,r)=>Bc(n)-Bc(r))}function Bc(e){return e==="typescript"?0:1}function Sg(e){return e==="typescript"?"TypeScript":"Rust"}function vg(e,t){return t?.available?e==="typescript"?"ts-morph can load the configured TypeScript project.":"rust-analyzer semantic queries are available.":t?t.reason??(e==="typescript"?"TypeScript semantic checks will fall back to SCIP/source evidence.":"Rust semantic checks will fall back to SCIP/source evidence."):e==="typescript"?"TypeScript is not detected/configured for this project.":"Rust is not detected/configured for this project."}function xg(e,t,n){let r=e.indexers.find(d=>d.language===t),i=r?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=i!=="unavailable",s=kg(t,n.runtimeProbe),a=$g(e,t),c=Cg(e,t),l=c.length===0?"unavailable":c.every(d=>d.strength!=="syntax-only")?"available":"partial";return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:i==="available"?`${r?.binaryLabel??t} is runnable${r?.resolvedBinary?` at ${r.resolvedBinary}`:""}.`:i==="partial"?`An indexed ${t} graph is present, but ${r?.binaryLabel??t} is not currently runnable for refresh.`:r?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:o?s.status:"unavailable",evidence:"heuristic",reason:o?s.reason:"Source fallback needs indexed documents before it can attach evidence."},semantic:a,detectors:{id:"detectors",label:"Cleanup detectors",status:o?"available":"unavailable",evidence:"heuristic",reason:o?"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above.":"Cleanup detectors need an indexed graph for this language."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:l,evidence:"checker",reason:c.length>0?c.map(d=>d.label).join(", "):`No detected checker covers ${Hc[t].join(", ")} files.`}}}function Rg(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function kg(e,t){if(e==="go")return{status:"unavailable",reason:"No Go source-fallback adapter is registered; Go relies on SCIP graph facts."};if(e==="clojure")return(t?.(e)??Vc(e))==="unavailable"?{status:"unavailable",reason:"Clojure built-in reader is not available in this environment; no source-fallback evidence can be produced."}:{status:"available",reason:"Clojure source fallback uses the built-in reader for namespace imports plus callable, callsite, and protocol/record member evidence for .clj, .cljs, and .cljc files."};let n=Wc(e);if(n==="regex-only")return{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`};if(!n)return{status:"unavailable",reason:`No source-fallback adapter is registered for ${e}.`};let r=t?.(e)??Vc(e);return r==="unavailable"?{status:"partial",reason:"tree-sitter native module not loadable \u2014 regex/import-only evidence remains available where registered."}:r==="regex"?{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`}:r==="reader"?{status:"available",reason:`${e} source fallback is reader-backed.`}:{status:"available",reason:n==="ast-dispatch-with-regex-fallback"?`AST-dispatched source fallback covers ${e} imports.`:`AST/source fallback covers ${e} imports and source-backed evidence.`}}function Vc(e){let t=gg[e];return t?bn(t):Wc(e)==="regex-only"?"regex":"unavailable"}function Wc(e){let t=hg[e],n=t?_o(t):null;return n?.imports??n?.exports??n?.reExports??null}function wg(e,t,n){let r=[];return t.includes("typescript")&&r.push({language:"typescript",...Ec(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")&&r.push({language:"rust",...Qo(e)}),r}function Gc(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function oi(e,t){return Gc(e).find(n=>n.language===t)}function $g(e,t){if(t!=="typescript"&&t!=="rust")return{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:`No semantic provider is registered for ${t}; commands use graph and source evidence instead.`};let n=oi(e,t);return n?{id:"semantic",label:"Semantic provider",status:n.available?"available":n.dependencyAvailable?"partial":"unavailable",evidence:"semantic",reason:n.available?t==="typescript"?"ts-morph can load the configured TypeScript project.":"rust-analyzer semantic queries are available.":n.reason??`${t} semantic checks fall back to SCIP/source evidence.`}:{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:t==="typescript"?"TypeScript is not detected/configured for this project.":"Rust is not detected/configured for this project."}}function Cg(e,t){let n=new Set(Hc[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function Pg(e){try{return fg("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as Tg,existsSync as Tt,readFileSync as It,rmSync as zc,writeFileSync as ai}from"fs";import{join as ct}from"path";var at="<!-- scip-query:agent-setup:begin -->",Mn="<!-- scip-query:agent-setup:end -->",si="# scip-query:agent-setup";function Jt(){if(process.stdin.isTTY)return"";try{return It(0,"utf-8")}catch{return""}}function _n(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function zt(e){let t=jn(e.findings),n=e.findings.length-t.length,r=e.rootCauseGroups?.length??e.findings.length,i=[`scip-query diff-gate found ${t.length} issue(s) in ${r} root-cause group(s) in this diff`+(n>0?` (+${n} advisory, non-blocking)`:"")+" \u2014 fix or knowingly accept them before finishing:"],o=e.rootCauseGroups?.filter(s=>s.count>1)??[];for(let s of o)i.push(`- group [${s.check}] ${s.count} finding(s): ${s.message}`),i.push(` -> ${s.remediation}`);for(let s of e.findings)i.push(`- [${s.check}]${s.advisory?" (advisory)":""} ${s.message}`),i.push(` -> ${s.remediation}`);return i.join(`
11
- `)}function qn(e,t={}){let n={written:[],unchanged:[],skipped:[]};return Ig(e,n),t.gitHook&&Eg(e,n),n}function Kc(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Jc(e,"AGENTS.md",t,n),Jc(e,"CLAUDE.md",t,n),jg(e,t,n),n}function Ig(e,t){let n=[at,"## 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.","- Each specialist skill carries its own command shortlist \u2014 prefer it over the full `_shared` catalog.","- For non-trivial implementation requests: plan first (`scip-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.","- Repository records: commit `.scipquery/suppressions/*.json` and `.scipquery/events/*.json` with the code or docs change that produced them; do not ignore or drop these shared records.","- Checkout preferences: `.codex/hooks.json` and `.claude/settings.local.json` are local agent-tool settings and must not be committed.",Mn].join(`
7
+ ${r.stderr??""}`;if(r.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostics:[],parseBasis:"heuristic",outputTail:Lc(i)};let o=og(e.label,i),s=o.diagnostics.length>0?o.diagnostics:r.error?[{file:"",message:String(r.error),parseBasis:"heuristic"}]:[];return{ok:!1,exitCode:r.status,rawErrors:s.map(mg),diagnostics:s,parseBasis:o.parseBasis,outputTail:Lc(i)}}function og(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:sg(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:ag(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=cg(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:lg(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:dg(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:ug(t),parseBasis:"clj-kondo-json"}:{diagnostics:pg(t),parseBasis:"heuristic"}}function sg(e){let t=[],n=/^(.+?)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),code:r[4],message:r[5]??"",parseBasis:"tsc"});return t}function ag(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),message:r[4]??"",parseBasis:"go"});return t}function cg(e){let t=Bc(e);if(!Array.isArray(t))return[];let n=[];for(let r of t){if(!r||typeof r!="object")continue;let i=r,o=i.location,s=o&&typeof o=="object"?o:{},a=typeof i.filename=="string"?i.filename:"",c=typeof i.message=="string"?i.message:"";!a&&!c||n.push({file:a,line:typeof s.row=="number"?s.row:void 0,column:typeof s.column=="number"?s.column:void 0,code:typeof i.code=="string"?i.code:void 0,message:c,parseBasis:"ruff-json"})}return n}function lg(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+([A-Z]\d{3})\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),code:r[4],message:r[5]??"",parseBasis:"ruff-text"});return t}function dg(e){let t=[];for(let n of e.split(`
8
+ `)){if(!n.trim().startsWith("{"))continue;let r=Zr(n);if(!r||typeof r!="object")continue;let i=r;if(i.reason!=="compiler-message")continue;let o=i.message;if(!o||typeof o!="object")continue;let s=o;if(s.level!=="error")continue;let l=(Array.isArray(s.spans)?s.spans:[]).find(p=>!!p&&typeof p=="object"&&p.is_primary===!0),d=s.code;t.push({file:typeof l?.file_name=="string"?l.file_name:"",line:typeof l?.line_start=="number"?l.line_start:void 0,column:typeof l?.column_start=="number"?l.column_start:void 0,code:d&&typeof d=="object"&&typeof d.code=="string"?String(d.code):void 0,message:typeof s.message=="string"?s.message:"",parseBasis:"cargo-json"})}return t}function ug(e){let t=Bc(e);if(!t||typeof t!="object")return[];let n=t.findings;if(!Array.isArray(n))return[];let r=[];for(let i of n){if(!i||typeof i!="object")continue;let o=i;o.level==="error"&&r.push({file:typeof o.filename=="string"?o.filename:"",line:typeof o.row=="number"?o.row:void 0,column:typeof o.col=="number"?o.col:void 0,code:typeof o.type=="string"?o.type:void 0,message:typeof o.message=="string"?o.message:"",parseBasis:"clj-kondo-json"})}return r}function pg(e){return e.split(`
9
+ `).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function mg(e){let t=e.file.length>0?`${e.file}${e.line?`:${e.line}`:""}${e.column?`:${e.column}`:""}: `:"",n=e.code?`${e.code} `:"";return`${t}${n}${e.message}`.trim()}function Bc(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return Zr(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(r=>r>=0));return Number.isFinite(n)?Zr(t.slice(n)):null}function Zr(e){try{return JSON.parse(e)}catch{return null}}function Lc(e,t=10){return e.split(`
10
+ `).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var Hc={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".vue"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"],clojure:[".clj",".cljs",".cljc"]},gg={typescript:"typescript",javascript:"javascript",java:"java",scala:"scala",kotlin:"kotlin",rust:"rust",python:"python",ruby:"ruby",cpp:"cpp",c:"c",csharp:"csharp",vb:"vb",php:"php",clojure:"clojure"},hg={typescript:"javascript",javascript:"javascript",java:"jvm",scala:"jvm",kotlin:"jvm",rust:"rust",python:"python",ruby:"ruby",cpp:"c/cpp",c:"c/cpp",csharp:"dotnet",vb:"dotnet",dart:"dart",php:"php",clojure:"clojure"};function ge(e,t){let n=t.languages??rt(e),r=n.map(a=>{let c=wn(st(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),i=wg(e,n,t),o=oi({semantics:i},"typescript"),s=ti(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:r,semantics:i,semantic:o,checkers:s,gitAvailable:Pg(e)}}function Qe(e,t={}){let n=e.indexers.filter(c=>c.runnable).length,r=e.languages.length===0||n===0&&!t.hasIndexedGraph?"unavailable":n===e.indexers.length&&e.indexers.length>0?"available":"partial",i=r!=="unavailable",o=e.languages.map(c=>xg(e,c,{hasIndexedGraph:Rg(c,t),runtimeProbe:t.runtimeProbe})),s=o.map(c=>c.cleanupVerification.status),a=s.length===0||s.every(c=>c==="unavailable")?"unavailable":s.every(c=>c==="available")?"available":"partial";return{languages:e.languages,matrix:o,capabilities:[{id:"indexing",label:"SCIP indexing",status:r,evidence:"graph-fact",reason:r==="available"?"All detected/configured language indexers are runnable.":t.hasIndexedGraph?`An indexed graph is present; ${n}/${e.indexers.length} detected/configured language indexers are runnable for refresh.`:`${n}/${e.indexers.length} detected/configured language indexers are runnable.`},...yg(e),{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:i?"available":"unavailable",evidence:"heuristic",reason:i?"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index.":"Heuristic detectors need an indexed code graph."},{id:"cleanup-verification",label:"Project cleanup verification",status:a,evidence:"checker",reason:a!=="unavailable"?o.map(c=>`${c.language}: ${c.cleanupVerification.status} (${c.cleanupVerification.reason})`).join("; "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-gate",label:"Git diff gate",status:e.gitAvailable&&i?"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 yg(e){return bg(e).map(t=>{let n=oi(e,t),r=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${Sg(t)} semantic provider`,status:r,evidence:"semantic",reason:vg(t,n)}})}function bg(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of Gc(e))t.add(n.language);return[...t].sort((n,r)=>qc(n)-qc(r))}function qc(e){return e==="typescript"?0:1}function Sg(e){return e==="typescript"?"TypeScript":"Rust"}function vg(e,t){return t?.available?e==="typescript"?"ts-morph can load the configured TypeScript project.":"rust-analyzer semantic queries are available.":t?t.reason??(e==="typescript"?"TypeScript semantic checks will fall back to SCIP/source evidence.":"Rust semantic checks will fall back to SCIP/source evidence."):e==="typescript"?"TypeScript is not detected/configured for this project.":"Rust is not detected/configured for this project."}function xg(e,t,n){let r=e.indexers.find(d=>d.language===t),i=r?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=i!=="unavailable",s=kg(t,n.runtimeProbe),a=$g(e,t),c=Cg(e,t),l=c.length===0?"unavailable":c.every(d=>d.strength!=="syntax-only")?"available":"partial";return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:i==="available"?`${r?.binaryLabel??t} is runnable${r?.resolvedBinary?` at ${r.resolvedBinary}`:""}.`:i==="partial"?`An indexed ${t} graph is present, but ${r?.binaryLabel??t} is not currently runnable for refresh.`:r?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:o?s.status:"unavailable",evidence:"heuristic",reason:o?s.reason:"Source fallback needs indexed documents before it can attach evidence."},semantic:a,detectors:{id:"detectors",label:"Cleanup detectors",status:o?"available":"unavailable",evidence:"heuristic",reason:o?"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above.":"Cleanup detectors need an indexed graph for this language."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:l,evidence:"checker",reason:c.length>0?c.map(d=>d.label).join(", "):`No detected checker covers ${Hc[t].join(", ")} files.`}}}function Rg(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function kg(e,t){if(e==="go")return{status:"unavailable",reason:"No Go source-fallback adapter is registered; Go relies on SCIP graph facts."};if(e==="clojure")return(t?.(e)??Vc(e))==="unavailable"?{status:"unavailable",reason:"Clojure built-in reader is not available in this environment; no source-fallback evidence can be produced."}:{status:"available",reason:"Clojure source fallback uses the built-in reader for namespace imports plus callable, callsite, and protocol/record member evidence for .clj, .cljs, and .cljc files."};let n=Wc(e);if(n==="regex-only")return{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`};if(!n)return{status:"unavailable",reason:`No source-fallback adapter is registered for ${e}.`};let r=t?.(e)??Vc(e);return r==="unavailable"?{status:"partial",reason:"tree-sitter native module not loadable \u2014 regex/import-only evidence remains available where registered."}:r==="regex"?{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`}:r==="reader"?{status:"available",reason:`${e} source fallback is reader-backed.`}:{status:"available",reason:n==="ast-dispatch-with-regex-fallback"?`AST-dispatched source fallback covers ${e} imports.`:`AST/source fallback covers ${e} imports and source-backed evidence.`}}function Vc(e){let t=gg[e];return t?bn(t):Wc(e)==="regex-only"?"regex":"unavailable"}function Wc(e){let t=hg[e],n=t?_o(t):null;return n?.imports??n?.exports??n?.reExports??null}function wg(e,t,n){let r=[];return t.includes("typescript")&&r.push({language:"typescript",...Ec(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")&&r.push({language:"rust",...Qo(e)}),r}function Gc(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function oi(e,t){return Gc(e).find(n=>n.language===t)}function $g(e,t){if(t!=="typescript"&&t!=="rust")return{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:`No semantic provider is registered for ${t}; commands use graph and source evidence instead.`};let n=oi(e,t);return n?{id:"semantic",label:"Semantic provider",status:n.available?"available":n.dependencyAvailable?"partial":"unavailable",evidence:"semantic",reason:n.available?t==="typescript"?"ts-morph can load the configured TypeScript project.":"rust-analyzer semantic queries are available.":n.reason??`${t} semantic checks fall back to SCIP/source evidence.`}:{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:t==="typescript"?"TypeScript is not detected/configured for this project.":"Rust is not detected/configured for this project."}}function Cg(e,t){let n=new Set(Hc[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function Pg(e){try{return fg("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as Tg,existsSync as Tt,readFileSync as It,rmSync as zc,writeFileSync as ai}from"fs";import{join as ct}from"path";var at="<!-- scip-query:agent-setup:begin -->",Mn="<!-- scip-query:agent-setup:end -->",si="# scip-query:agent-setup";function Jt(){if(process.stdin.isTTY)return"";try{return It(0,"utf-8")}catch{return""}}function _n(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function zt(e){let t=jn(e.findings),n=e.findings.length-t.length,r=e.rootCauseGroups?.length??e.findings.length,i=[`scip-query diff-gate found ${t.length} issue(s) in ${r} root-cause group(s) in this diff`+(n>0?` (+${n} advisory, non-blocking)`:"")+" \u2014 fix or knowingly accept them before finishing:"],o=e.rootCauseGroups?.filter(s=>s.count>1)??[];for(let s of o)i.push(`- group [${s.check}] ${s.count} finding(s): ${s.message}`),i.push(` -> ${s.remediation}`);for(let s of e.findings)i.push(`- [${s.check}]${s.advisory?" (advisory)":""} ${s.message}`),i.push(` -> ${s.remediation}`);return i.join(`
11
+ `)}function Bn(e,t={}){let n={written:[],unchanged:[],skipped:[]};return Ig(e,n),t.gitHook&&Eg(e,n),n}function Kc(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Jc(e,"AGENTS.md",t,n),Jc(e,"CLAUDE.md",t,n),jg(e,t,n),n}function Ig(e,t){let n=[at,"## 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.","- Each specialist skill carries its own command shortlist \u2014 prefer it over the full `_shared` catalog.","- For non-trivial implementation requests: plan first (`scip-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.","- Repository records: commit `.scipquery/suppressions/*.json` and `.scipquery/events/*.json` with the code or docs change that produced them; do not ignore or drop these shared records.","- Checkout preferences: `.codex/hooks.json` and `.claude/settings.local.json` are local agent-tool settings and must not be committed.",Mn].join(`
12
12
  `);Uc(e,"AGENTS.md",n,t);let r=Tt(ct(e,"CLAUDE.md"))?It(ct(e,"CLAUDE.md"),"utf-8"):"";if(r.includes("@AGENTS.md")&&!r.includes(at)){t.unchanged.push("CLAUDE.md");return}let i=[at,"@AGENTS.md",Mn].join(`
13
13
  `);Uc(e,"CLAUDE.md",i,t)}function Uc(e,t,n,r){let i=ct(e,t),o=Tt(i)?It(i,"utf-8"):"",s;if(o.includes(at)){let a=new RegExp(`${at}[\\s\\S]*?${Mn}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
14
14
 
@@ -23,7 +23,7 @@ ${r.stderr??""}`;if(r.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostic
23
23
  `).filter(r=>r.trim()!==`${Xc} merge=union`).join(`
24
24
  `).replace(/^\n+|\n+$/g,"");n===""?Qc(t):Yc(t,`${n}
25
25
  `)}function Gn(e){let t=[],n=Ve(e,Wn);if(Vn(n))for(let i of Dg(n).sort()){if(!i.endsWith(".json"))continue;let o=nl(Hn(Ve(n,i),"utf-8"));o&&t.push(o)}let r=ci(e);return Vn(r)&&t.push(...tl(r)),Mg(t)}function tl(e){let t=[];for(let n of Hn(e,"utf-8").split(`
26
- `)){let r=nl(n);r&&t.push(r)}return t}function nl(e){if(e.trim()==="")return null;let t;try{t=JSON.parse(e)}catch{return null}return qg(t)?t:null}function Mg(e){let t=new Map;for(let n of e){let r=`${n.check}\0${n.findingId}\0${n.event}\0${n.commit??""}`,i=t.get(r);(!i||Bn(n)>Bn(i)||Bn(n)===Bn(i)&&n.ts<i.ts)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.ts-r.ts)}function Bn(e){return+(e.comparisonBaseCommit!==void 0)+ +(e.verifiedAgainstCommit!==void 0)*2}var _g=["caught","resolved","suppressed","reopened"];function qg(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.ts=="number"&&typeof t.check=="string"&&typeof t.findingId=="string"&&_g.includes(t.event)&&(t.commit===null||typeof t.commit=="string")&&(t.comparisonBaseCommit===void 0||typeof t.comparisonBaseCommit=="string")&&(t.verifiedAgainstCommit===void 0||t.event==="resolved"&&typeof t.verifiedAgainstCommit=="string")&&(t.symbol===void 0||typeof t.symbol=="string")}function Un(e,t,n={}){let r=(n.now??Date.now)(),i=Hg(t),o=Ea(e),s=e.config.projectRoot,a=n.headCommit?n.headCommit(s):nt(s)?.headCommit??null,c=n.resolveCommit?n.resolveCommit(s,t.base):Vg(s,t.base),l=Bg({previous:o,observed:i,result:t,projectRoot:s,commit:a,comparisonBaseCommit:c,runtime:n}),d=ja(e,l.ledgerObserved,l.checksRun,r,l.retainedKeys);try{let p=new Map;for(let f of t.findings)f.symbol&&p.set(f.id,f.symbol);for(let f of t.suppressed)f.finding.symbol&&p.set(f.finding.id,f.finding.symbol);for(let[f,g]of l.replaySymbols)p.set(f,g);let m=Pa(o,d,p,a,r,{...c?{comparisonBaseCommit:c}:{},verifiedAgainstByFinding:l.verifiedAgainstByFinding});return(n.appendEvents??el)(s,m),{ledger:d,observed:i,now:r,...l.warning?{warning:l.warning}:{}}}catch(p){return{ledger:d,observed:i,now:r,warning:[l.warning,`outcome event ledger not updated: ${p instanceof Error?p.message:String(p)}`].filter(Boolean).join("; ")}}}function Bg(e){let t=[...e.observed],n=new Set(e.result.checksRun),r=new Set,i=new Map,o=new Map,s=new Set(e.observed.map(h=>be(h.check,h.findingId))),a=new Set(e.result.checksRun),c=e.result.changedFiles.length===0&&!En(e.result)&&e.commit!==null&&e.comparisonBaseCommit!==null,l=e.previous.filter(h=>h.outcome!=="resolved"&&(a.has(h.check)||c)&&!s.has(be(h.check,h.findingId)));if(lt(`primary base=${String(e.comparisonBaseCommit)} head=${String(e.commit)} checks=${e.result.checksRun.join(",")} missing=${l.length}`),l.length===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let d;try{d=(e.runtime.readEvents??Gn)(e.projectRoot)}catch(h){for(let y of l)r.add(be(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,warning:`cross-HEAD outcome verification deferred: ${h instanceof Error?h.message:String(h)}`}}let p=new Map;for(let h of d){let y=be(h.check,h.findingId),S=p.get(y)??[];S.push(h),p.set(y,S)}let m=new Map;for(let h of l){let y=be(h.check,h.findingId),S=Gt(p.get(y)??[]),v=S?.comparisonBaseCommit??S?.commit;if(lt(`candidate ${y} anchor=${String(v)} current=${String(e.comparisonBaseCommit)}`),!S?.comparisonBaseCommit&&S?.commit&&S.commit===e.commit){n.add(h.check);continue}if(!v||!e.commit||!e.comparisonBaseCommit){r.add(y);continue}if(v===e.comparisonBaseCommit){n.add(h.check);continue}let k=m.get(v)??[];k.push(h),m.set(v,k)}if(m.size===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let f=e.runtime.worktreeIsClean?.(e.projectRoot)??nt(e.projectRoot)?.clean??!1;if(lt(`replay groups=${m.size} clean=${f} callback=${!!e.runtime.replayGate}`),!f||!e.runtime.replayGate){for(let h of m.values())for(let y of h)r.add(be(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o}}let g=[];for(let[h,y]of m){let S;try{S=e.runtime.replayGate(h),lt(`replay base=${h} checks=${S.checksRun.join(",")} findings=${S.findings.length} suppressed=${S.suppressed.length}`)}catch(R){for(let D of y)r.add(be(D.check,D.findingId));g.push(`cross-HEAD outcome verification deferred for ${h.slice(0,12)}: ${R instanceof Error?R.message:String(R)}`);continue}let v=new Set(S.checksRun),k=Wg(S);for(let R of y){let D=be(R.check,R.findingId);if(!v.has(R.check)){r.add(D);continue}n.add(R.check);let q=k.find(F=>F.key===D);if(q){lt(`replay retained exact ${D}`),t.push(q.observed),q.symbol&&o.set(q.observed.findingId,q.symbol);continue}let z=Gt(p.get(D)??[]),T=z?.symbol?k.find(F=>F.check===R.check&&F.symbol===z.symbol):void 0;if(T){lt(`replay moved ${D} -> ${T.key}`),t.push(T.observed),T.symbol&&o.set(T.observed.findingId,T.symbol);continue}i.set(D,h),lt(`replay verified ${D} against ${h}`)}}return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,...g.length>0?{warning:g.join("; ")}:{}}}function Vg(e,t){let n=Vt(e,["rev-parse","--verify",`${t}^{commit}`]);return n&&/^[0-9a-f]{40}$/.test(n)?n:null}function lt(e){process.env.SCIP_QUERY_DEBUG&&console.error(`outcome-verification: ${e}`)}function Hg(e){return[...e.findings.map(t=>({check:t.check,findingId:t.id,suppressed:!1})),...e.suppressed.map(t=>({check:t.finding.check,findingId:t.finding.id,suppressed:!0}))]}function Wg(e){return[...e.findings.map(t=>({key:be(t.check,t.id),check:t.check,observed:{check:t.check,findingId:t.id,suppressed:!1},...t.symbol?{symbol:t.symbol}:{}})),...e.suppressed.map(t=>({key:be(t.finding.check,t.finding.id),check:t.finding.check,observed:{check:t.finding.check,findingId:t.finding.id,suppressed:!0},...t.finding.symbol?{symbol:t.finding.symbol}:{}}))]}var ul="SCIP_QUERY_SKIP_HOOK_INSTALL",li="SCIP_QUERY_STOP_HOOK_MODE",Qg="scip-query hook-",Yg="scip-query diff-gate --hook",rl="# scip-query:local-hooks:begin",il="# scip-query:local-hooks:end",Kt=[{relativePath:".codex/hooks.json",label:".codex/hooks.json"},{relativePath:".claude/settings.local.json",label:".claude/settings.local.json"}];function Et(e,t={}){let n=pl(),r=t.env??process.env;if(th(r))return n.skipped.push({target:"project agent hooks",reason:`${ul}=1`}),n;let i=ch(e);return t.shared&&n.warnings.push("--shared is deprecated; project hooks are always checkout-local and will not be committed."),Zg(e,n,t.dryRun),t.remove?(sl(e,Kt[0],n,{dryRun:t.dryRun}),sl(e,Kt[1],n,{writeDeclinedTombstone:!0,dryRun:t.dryRun}),n):(ol(e,Kt[0],n,{provider:"codex",commandPrefix:i,force:t.force}),ol(e,Kt[1],n,{provider:"claude",commandPrefix:i,force:t.force}),t.removeLegacyUserHooks!==!1&&Xg({homeDir:t.homeDir,result:n}),n)}function Xg(e={}){let t=e.result??pl(),n=e.homeDir??Jg();return di({configPath:Qt(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),di({configPath:Qt(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function pl(){return{installed:[],updated:[],unchanged:[],removed:[],gitExcluded:[],warnings:[],skipped:[]}}function ol(e,t,n,r){if(pi(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook setup will not modify it"});return}let i=Qt(e,t.relativePath);rh({provider:r.provider,rootDir:zn(i),configPath:i,label:t.label,createRoot:!0,commandPrefix:r.commandPrefix,force:r.force,result:n})}function sl(e,t,n,r){if(pi(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook removal will not modify it"});return}ih({configPath:Qt(e,t.relativePath),label:t.label,result:n,writeDeclinedTombstone:r.writeDeclinedTombstone,dryRun:r.dryRun})}function Zg(e,t,n=!1){let r=eh(e);if(!r){t.warnings.push("Could not locate .git/info/exclude; local hook files may appear as untracked.");return}let i=Kt.filter(d=>!pi(e,d.relativePath));if(i.length===0)return;let o=[rl,...i.map(d=>`/${d.relativePath}`),il].join(`
26
+ `)){let r=nl(n);r&&t.push(r)}return t}function nl(e){if(e.trim()==="")return null;let t;try{t=JSON.parse(e)}catch{return null}return Bg(t)?t:null}function Mg(e){let t=new Map;for(let n of e){let r=`${n.check}\0${n.findingId}\0${n.event}\0${n.commit??""}`,i=t.get(r);(!i||qn(n)>qn(i)||qn(n)===qn(i)&&n.ts<i.ts)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.ts-r.ts)}function qn(e){return+(e.comparisonBaseCommit!==void 0)+ +(e.verifiedAgainstCommit!==void 0)*2}var _g=["caught","resolved","suppressed","reopened"];function Bg(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.ts=="number"&&typeof t.check=="string"&&typeof t.findingId=="string"&&_g.includes(t.event)&&(t.commit===null||typeof t.commit=="string")&&(t.comparisonBaseCommit===void 0||typeof t.comparisonBaseCommit=="string")&&(t.verifiedAgainstCommit===void 0||t.event==="resolved"&&typeof t.verifiedAgainstCommit=="string")&&(t.symbol===void 0||typeof t.symbol=="string")}function Un(e,t,n={}){let r=(n.now??Date.now)(),i=Hg(t),o=Ea(e),s=e.config.projectRoot,a=n.headCommit?n.headCommit(s):nt(s)?.headCommit??null,c=n.resolveCommit?n.resolveCommit(s,t.base):Vg(s,t.base),l=qg({previous:o,observed:i,result:t,projectRoot:s,commit:a,comparisonBaseCommit:c,runtime:n}),d=ja(e,l.ledgerObserved,l.checksRun,r,l.retainedKeys);try{let p=new Map;for(let f of t.findings)f.symbol&&p.set(f.id,f.symbol);for(let f of t.suppressed)f.finding.symbol&&p.set(f.finding.id,f.finding.symbol);for(let[f,g]of l.replaySymbols)p.set(f,g);let m=Pa(o,d,p,a,r,{...c?{comparisonBaseCommit:c}:{},verifiedAgainstByFinding:l.verifiedAgainstByFinding});return(n.appendEvents??el)(s,m),{ledger:d,observed:i,now:r,...l.warning?{warning:l.warning}:{}}}catch(p){return{ledger:d,observed:i,now:r,warning:[l.warning,`outcome event ledger not updated: ${p instanceof Error?p.message:String(p)}`].filter(Boolean).join("; ")}}}function qg(e){let t=[...e.observed],n=new Set(e.result.checksRun),r=new Set,i=new Map,o=new Map,s=new Set(e.observed.map(h=>be(h.check,h.findingId))),a=new Set(e.result.checksRun),c=e.result.changedFiles.length===0&&!En(e.result)&&e.commit!==null&&e.comparisonBaseCommit!==null,l=e.previous.filter(h=>h.outcome!=="resolved"&&(a.has(h.check)||c)&&!s.has(be(h.check,h.findingId)));if(lt(`primary base=${String(e.comparisonBaseCommit)} head=${String(e.commit)} checks=${e.result.checksRun.join(",")} missing=${l.length}`),l.length===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let d;try{d=(e.runtime.readEvents??Gn)(e.projectRoot)}catch(h){for(let y of l)r.add(be(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,warning:`cross-HEAD outcome verification deferred: ${h instanceof Error?h.message:String(h)}`}}let p=new Map;for(let h of d){let y=be(h.check,h.findingId),S=p.get(y)??[];S.push(h),p.set(y,S)}let m=new Map;for(let h of l){let y=be(h.check,h.findingId),S=Gt(p.get(y)??[]),v=S?.comparisonBaseCommit??S?.commit;if(lt(`candidate ${y} anchor=${String(v)} current=${String(e.comparisonBaseCommit)}`),!S?.comparisonBaseCommit&&S?.commit&&S.commit===e.commit){n.add(h.check);continue}if(!v||!e.commit||!e.comparisonBaseCommit){r.add(y);continue}if(v===e.comparisonBaseCommit){n.add(h.check);continue}let k=m.get(v)??[];k.push(h),m.set(v,k)}if(m.size===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let f=e.runtime.worktreeIsClean?.(e.projectRoot)??nt(e.projectRoot)?.clean??!1;if(lt(`replay groups=${m.size} clean=${f} callback=${!!e.runtime.replayGate}`),!f||!e.runtime.replayGate){for(let h of m.values())for(let y of h)r.add(be(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o}}let g=[];for(let[h,y]of m){let S;try{S=e.runtime.replayGate(h),lt(`replay base=${h} checks=${S.checksRun.join(",")} findings=${S.findings.length} suppressed=${S.suppressed.length}`)}catch(R){for(let D of y)r.add(be(D.check,D.findingId));g.push(`cross-HEAD outcome verification deferred for ${h.slice(0,12)}: ${R instanceof Error?R.message:String(R)}`);continue}let v=new Set(S.checksRun),k=Wg(S);for(let R of y){let D=be(R.check,R.findingId);if(!v.has(R.check)){r.add(D);continue}n.add(R.check);let B=k.find(F=>F.key===D);if(B){lt(`replay retained exact ${D}`),t.push(B.observed),B.symbol&&o.set(B.observed.findingId,B.symbol);continue}let z=Gt(p.get(D)??[]),T=z?.symbol?k.find(F=>F.check===R.check&&F.symbol===z.symbol):void 0;if(T){lt(`replay moved ${D} -> ${T.key}`),t.push(T.observed),T.symbol&&o.set(T.observed.findingId,T.symbol);continue}i.set(D,h),lt(`replay verified ${D} against ${h}`)}}return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,...g.length>0?{warning:g.join("; ")}:{}}}function Vg(e,t){let n=Vt(e,["rev-parse","--verify",`${t}^{commit}`]);return n&&/^[0-9a-f]{40}$/.test(n)?n:null}function lt(e){process.env.SCIP_QUERY_DEBUG&&console.error(`outcome-verification: ${e}`)}function Hg(e){return[...e.findings.map(t=>({check:t.check,findingId:t.id,suppressed:!1})),...e.suppressed.map(t=>({check:t.finding.check,findingId:t.finding.id,suppressed:!0}))]}function Wg(e){return[...e.findings.map(t=>({key:be(t.check,t.id),check:t.check,observed:{check:t.check,findingId:t.id,suppressed:!1},...t.symbol?{symbol:t.symbol}:{}})),...e.suppressed.map(t=>({key:be(t.finding.check,t.finding.id),check:t.finding.check,observed:{check:t.finding.check,findingId:t.finding.id,suppressed:!0},...t.finding.symbol?{symbol:t.finding.symbol}:{}}))]}var ul="SCIP_QUERY_SKIP_HOOK_INSTALL",li="SCIP_QUERY_STOP_HOOK_MODE",Qg="scip-query hook-",Yg="scip-query diff-gate --hook",rl="# scip-query:local-hooks:begin",il="# scip-query:local-hooks:end",Kt=[{relativePath:".codex/hooks.json",label:".codex/hooks.json"},{relativePath:".claude/settings.local.json",label:".claude/settings.local.json"}];function Et(e,t={}){let n=pl(),r=t.env??process.env;if(th(r))return n.skipped.push({target:"project agent hooks",reason:`${ul}=1`}),n;let i=ch(e);return t.shared&&n.warnings.push("--shared is deprecated; project hooks are always checkout-local and will not be committed."),Zg(e,n,t.dryRun),t.remove?(sl(e,Kt[0],n,{dryRun:t.dryRun}),sl(e,Kt[1],n,{writeDeclinedTombstone:!0,dryRun:t.dryRun}),n):(ol(e,Kt[0],n,{provider:"codex",commandPrefix:i,force:t.force}),ol(e,Kt[1],n,{provider:"claude",commandPrefix:i,force:t.force}),t.removeLegacyUserHooks!==!1&&Xg({homeDir:t.homeDir,result:n}),n)}function Xg(e={}){let t=e.result??pl(),n=e.homeDir??Jg();return di({configPath:Qt(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),di({configPath:Qt(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function pl(){return{installed:[],updated:[],unchanged:[],removed:[],gitExcluded:[],warnings:[],skipped:[]}}function ol(e,t,n,r){if(pi(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook setup will not modify it"});return}let i=Qt(e,t.relativePath);rh({provider:r.provider,rootDir:zn(i),configPath:i,label:t.label,createRoot:!0,commandPrefix:r.commandPrefix,force:r.force,result:n})}function sl(e,t,n,r){if(pi(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook removal will not modify it"});return}ih({configPath:Qt(e,t.relativePath),label:t.label,result:n,writeDeclinedTombstone:r.writeDeclinedTombstone,dryRun:r.dryRun})}function Zg(e,t,n=!1){let r=eh(e);if(!r){t.warnings.push("Could not locate .git/info/exclude; local hook files may appear as untracked.");return}let i=Kt.filter(d=>!pi(e,d.relativePath));if(i.length===0)return;let o=[rl,...i.map(d=>`/${d.relativePath}`),il].join(`
27
27
  `),s=dt(r)?dl(r,"utf-8"):"",a=new RegExp(`${Le(rl)}[\\s\\S]*?${Le(il)}\\n?`,"g"),c=s.replace(a,"").replace(/\n*$/,""),l=`${c}${c?`
28
28
 
29
29
  `:""}${o}
@@ -41,9 +41,9 @@ ${r.message}`:""}var al=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
41
41
  `),console.log("Or download manually:")):Yt()==="win32"?(console.log("On Windows the scip binary ships via the npm sidecar package scip-query-scip-windows,"),console.log("installed automatically with scip-query. If it is missing:"),console.log(" npm install -g scip-query-scip-windows"),console.log(`Or set ${xl} to a local scip.exe path.
42
42
  `),console.log("Upstream release page:")):console.log("Download from:"),console.log(e?` ${e.url}
43
43
  `:` ${fi}/releases/tag/${vl}
44
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function Rl(e){if(Yt()==="darwin"&&ze("brew")){e("Installing scip CLI via Homebrew...");try{if(bl("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),ze("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`Homebrew install failed: ${n}`)}}if(ze("go")){e("Installing scip CLI via go install...");try{if(bl("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),ze("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`go install failed: ${n}`)}}return e("Could not auto-install scip CLI."),e(`Install manually from: ${fi}/releases`),!1}var Ah=jh()==="win32",Xn=["_shared","scip-query","scip-setup","scip-calibrate","scip-cleanup-audit","scip-cleanup-improve","scip-integrity-audit","scip-twin-drift","scip-claim-audit","scip-probe-reachability","scip-hyper-optimization","scip-api-impact","scip-concrete-plan","scip-conductor","scip-debug","scip-explore","scip-root-cause","scip-triage-issue","scip-diagram","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook","scip-tla-model-system"];function Zn(e={}){let t=e.quiet?()=>{}:console.log,n=wl(import.meta.url),r=Ye(Zt(n),"..","skills"),i=[Ie(Yn(),".claude","skills"),Ie(Yn(),".codex","skills"),Ie(Yn(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of i){let a=Zt(s);if(!Qn(a))continue;Ph(s,{recursive:!0});let c=Pl(s);Lh(s,r,c,o,t);for(let l of Xn){let d=Ie(r,l),p=Ie(s,l);if(!Qn(d)){o.skipped.push(`${c}/${l}`);continue}if(Qn(p)){try{let m=hi(p);if(Ye(m)===Ye(d)){o.alreadyLinked.push(`${c}/${l}`),t(` ok: ${l} \u2192 ${c} (already linked)`);continue}}catch{o.skipped.push(`${c}/${l}`),t(` skip: ${l} \u2192 ${c} (exists, not a symlink)`);continue}yi(p)}Th(d,p,Ah?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function Lh(e,t,n,r,i){let o=new Set(Xn);for(let s of kl(e)){if(o.has(s))continue;let a=Ie(e,s),c;try{c=Ye(Zt(a),hi(a))}catch{continue}Cl(c,t)&&(yi(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function $l(e={}){let t=wl(import.meta.url),n=Ye(Zt(t),"..","skills"),r=e.homeDir??Yn(),i=[Ie(r,".claude","skills"),Ie(r,".codex","skills"),Ie(r,".agents","skills")],o={removed:[],left:[],skipped:[]};for(let s of i){if(!Qn(s))continue;let a=Pl(s);for(let c of kl(s)){let l=Ie(s,c),d;try{let p=hi(l);d=Ye(Zt(l),p)}catch{o.left.push(`${a}/${c} (not a symlink)`);continue}if(!Cl(d,n)){o.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(o.removed.push(`${a}/${c}`),!e.dryRun)try{yi(l)}catch(p){o.skipped.push(`${a}/${c} (${p instanceof Error?p.message:String(p)})`)}}}return o}function Cl(e,t){let n=Ih(Ye(t),Ye(e));return n===""||!n.startsWith("..")&&!Eh(n)}function Pl(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as tp}from"child_process";import{performance as et}from"perf_hooks";import{existsSync as ke,readFileSync as fR,renameSync as gR,rmSync as hR,unlinkSync as yR,writeFileSync as bR}from"fs";import{dirname as wr,extname as SR,join as mt,resolve as vR}from"path";import{execFileSync as XS}from"child_process";import{createHash as ZS}from"crypto";import{closeSync as ev,copyFileSync as fr,existsSync as Re,mkdirSync as mr,mkdtempSync as tv,openSync as nv,readdirSync as ou,readFileSync as gr,renameSync as su,rmSync as Ge,statSync as rv,writeFileSync as iv}from"fs";import{basename as pr,dirname as _,extname as ov,join as ee,resolve as Xd}from"path";import{platform as sv}from"os";import Dh from"better-sqlite3";import{execFileSync as Fh}from"child_process";import{existsSync as Oh,readdirSync as Nh,readFileSync as Mh}from"fs";import{extname as er,join as Tl}from"path";function ut(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>tr({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function tr(e){let t=new Set((e.extensions??No).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Oh(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Rt(e.projectRoot),r=_h(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Dh(e.dbPath);try{let o=Bh(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
45
- VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let p=0;for(let m of d){if(o.has(m))continue;let f=Mh(Tl(e.projectRoot,m),"utf-8"),g=s.run(Vh(m),m,f);p+=Number(g.changes)}return p})(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 _h(e,t){let n=qh(e,t);if(n)return n;let r=[],i=o=>{let s=o?Tl(e,o):e,a;try{a=Nh(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Mo.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(er(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function qh(e,t){try{return Fh("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
46
- `).filter(r=>r&&t.has(er(r).toLowerCase())).sort()}catch{return null}}function Bh(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 Vh(e){return er(e).toLowerCase()===".vue"?"vue":er(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as Wh}from"crypto";import{appendFileSync as Gh,existsSync as Dl,mkdirSync as Uh,readFileSync as Jh,renameSync as zh,rmSync as Si,statSync as Kh}from"fs";import{dirname as Fl,join as El}from"path";function bi(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function nr(e,t,n){let r=e.changes.map(a=>a.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let i=new Set(n),o=bi(e),s=new Set(o.reasons);return r.some(a=>!i.has(a))&&s.add("changed-file-outside-project"),t===null?(s.add("dependency-graph-unavailable"),Il(r,i,s)):s.size>0?Il(r,i,s):{mode:"closure",changedFiles:r,affectedFiles:Hh(r,t,i),reasons:[]}}function Il(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function Hh(e,t,n){let r=new Map;for(let[s,a]of t)if(n.has(s))for(let c of a){if(!n.has(c))continue;let l=r.get(c)??new Set;l.add(s),r.set(c,l)}let i=new Set(e),o=[...e];for(let s=0;s<o.length;s+=1){let a=o[s];if(a!==void 0)for(let c of r.get(a)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}var Qh="<global-symbols>";function Yh(e){let t=[];for(let n of e.all(`
44
+ `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function Rl(e){if(Yt()==="darwin"&&ze("brew")){e("Installing scip CLI via Homebrew...");try{if(bl("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),ze("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`Homebrew install failed: ${n}`)}}if(ze("go")){e("Installing scip CLI via go install...");try{if(bl("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),ze("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`go install failed: ${n}`)}}return e("Could not auto-install scip CLI."),e(`Install manually from: ${fi}/releases`),!1}var Ah=jh()==="win32",Xn=["_shared","scip-query","scip-setup","scip-calibrate","scip-cleanup-audit","scip-cleanup-improve","scip-integrity-audit","scip-twin-drift","scip-claim-audit","scip-probe-reachability","scip-hyper-optimization","scip-api-impact","scip-concrete-plan","scip-conductor","scip-debug","scip-explore","scip-root-cause","scip-triage-issue","scip-diagram","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook","scip-tla-model-system"];function Zn(e={}){let t=e.quiet?()=>{}:console.log,n=wl(import.meta.url),r=Ye(Zt(n),"..","skills"),i=[Ie(Yn(),".claude","skills"),Ie(Yn(),".codex","skills"),Ie(Yn(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of i){let a=Zt(s);if(!Qn(a))continue;Ph(s,{recursive:!0});let c=Pl(s);Lh(s,r,c,o,t);for(let l of Xn){let d=Ie(r,l),p=Ie(s,l);if(!Qn(d)){o.skipped.push(`${c}/${l}`);continue}if(Qn(p)){try{let m=hi(p);if(Ye(m)===Ye(d)){o.alreadyLinked.push(`${c}/${l}`),t(` ok: ${l} \u2192 ${c} (already linked)`);continue}}catch{o.skipped.push(`${c}/${l}`),t(` skip: ${l} \u2192 ${c} (exists, not a symlink)`);continue}yi(p)}Th(d,p,Ah?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function Lh(e,t,n,r,i){let o=new Set(Xn);for(let s of kl(e)){if(o.has(s))continue;let a=Ie(e,s),c;try{c=Ye(Zt(a),hi(a))}catch{continue}Cl(c,t)&&(yi(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function $l(e={}){let t=wl(import.meta.url),n=Ye(Zt(t),"..","skills"),r=e.homeDir??Yn(),i=[Ie(r,".claude","skills"),Ie(r,".codex","skills"),Ie(r,".agents","skills")],o={removed:[],left:[],skipped:[]};for(let s of i){if(!Qn(s))continue;let a=Pl(s);for(let c of kl(s)){let l=Ie(s,c),d;try{let p=hi(l);d=Ye(Zt(l),p)}catch{o.left.push(`${a}/${c} (not a symlink)`);continue}if(!Cl(d,n)){o.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(o.removed.push(`${a}/${c}`),!e.dryRun)try{yi(l)}catch(p){o.skipped.push(`${a}/${c} (${p instanceof Error?p.message:String(p)})`)}}}return o}function Cl(e,t){let n=Ih(Ye(t),Ye(e));return n===""||!n.startsWith("..")&&!Eh(n)}function Pl(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as tp}from"child_process";import{performance as et}from"perf_hooks";import{existsSync as ke,readFileSync as fR,renameSync as gR,rmSync as hR,unlinkSync as yR,writeFileSync as bR}from"fs";import{dirname as wr,extname as SR,join as mt,resolve as vR}from"path";import{execFileSync as XS}from"child_process";import{createHash as ZS}from"crypto";import{closeSync as ev,copyFileSync as fr,existsSync as Re,mkdirSync as mr,mkdtempSync as tv,openSync as nv,readdirSync as ou,readFileSync as gr,renameSync as su,rmSync as Ge,statSync as rv,writeFileSync as iv}from"fs";import{basename as pr,dirname as _,extname as ov,join as ee,resolve as Xd}from"path";import{platform as sv}from"os";import Dh from"better-sqlite3";import{execFileSync as Fh}from"child_process";import{existsSync as Oh,readdirSync as Nh,readFileSync as Mh}from"fs";import{extname as er,join as Tl}from"path";function ut(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>tr({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function tr(e){let t=new Set((e.extensions??No).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Oh(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Rt(e.projectRoot),r=_h(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Dh(e.dbPath);try{let o=qh(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
45
+ VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let p=0;for(let m of d){if(o.has(m))continue;let f=Mh(Tl(e.projectRoot,m),"utf-8"),g=s.run(Vh(m),m,f);p+=Number(g.changes)}return p})(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 _h(e,t){let n=Bh(e,t);if(n)return n;let r=[],i=o=>{let s=o?Tl(e,o):e,a;try{a=Nh(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Mo.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(er(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function Bh(e,t){try{return Fh("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
46
+ `).filter(r=>r&&t.has(er(r).toLowerCase())).sort()}catch{return null}}function qh(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 Vh(e){return er(e).toLowerCase()===".vue"?"vue":er(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as Wh}from"crypto";import{appendFileSync as Gh,existsSync as Dl,mkdirSync as Uh,readFileSync as Jh,renameSync as zh,rmSync as Si,statSync as Kh}from"fs";import{dirname as Fl,join as El}from"path";function bi(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function nr(e,t,n){let r=e.changes.map(a=>a.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let i=new Set(n),o=bi(e),s=new Set(o.reasons);return r.some(a=>!i.has(a))&&s.add("changed-file-outside-project"),t===null?(s.add("dependency-graph-unavailable"),Il(r,i,s)):s.size>0?Il(r,i,s):{mode:"closure",changedFiles:r,affectedFiles:Hh(r,t,i),reasons:[]}}function Il(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function Hh(e,t,n){let r=new Map;for(let[s,a]of t)if(n.has(s))for(let c of a){if(!n.has(c))continue;let l=r.get(c)??new Set;l.add(s),r.set(c,l)}let i=new Set(e),o=[...e];for(let s=0;s<o.length;s+=1){let a=o[s];if(a!==void 0)for(let c of r.get(a)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}var Qh="<global-symbols>";function Yh(e){let t=[];for(let n of e.all(`
47
47
  SELECT relative_path, language, position_encoding, text
48
48
  FROM documents
49
49
  `))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
@@ -100,8 +100,8 @@ ${r.message}`:""}var al=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
100
100
  SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
101
101
  )
102
102
  `))t.push({relativePath:Qh,kind:"global-symbol",values:vi(n)});return Xh(t)}function Xh(e){let t=new Map;for(let r of e){let i=JSON.stringify([r.kind,r.values]),o=t.get(r.relativePath)??[];o.push(i),t.set(r.relativePath,o)}let n=new Map;for(let[r,i]of[...t].sort(([o],[s])=>o.localeCompare(s))){let o=Wh("sha256");for(let s of i.sort())o.update(String(Buffer.byteLength(s))),o.update(":"),o.update(s),o.update(`
103
- `);n.set(r,o.digest("hex"))}return n}function Zh(e,t){let n=[],r=[],i=[],o=[],s=new Set([...e.keys(),...t.keys()]);for(let a of[...s].sort()){let c=e.get(a),l=t.get(a);c===void 0?n.push(a):l===void 0?i.push(a):c!==l?r.push(a):o.push(a)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function xi(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),s=e.affectedFiles.filter(c=>!i.has(c)).sort(),a=t.changedFiles.length-o.length;return{passed:o.length===0,recall:t.changedFiles.length===0?1:a/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:o,extraFiles:s}}function Ri(e,t=iy){let n=t.now();if(!t.databaseExists(e.previousDbPath))return rr(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return rr(e.refreshResult,"candidate-index-unavailable",n,t.now());let r=null,i=null;try{r=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),i=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let o=[...new Set([...t.indexedPaths(r),...t.indexedPaths(i)])].sort(),s=$n(e.previousSnapshot,e.currentSnapshot),a=new Set(o),c=s.changes.length>0&&!bi(s).fullProject&&s.changes.every(m=>a.has(m.path)),l=nr(s,c?t.dependencyGraph(r):new Map,o),d=Zh(t.factDigests(r),t.factDigests(i)),p=t.now();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(p).toISOString(),durationMs:Math.max(0,p-n),manifest:s,plan:l,comparison:d,evaluation:xi(l,d,o.length)}}catch(o){return rr(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{jl(r),jl(i)}}function Ol(e,t,n,r=Date.now()){return rr(e,t,r,r,n)}function Nl(e){let t=Fl(e);return{latestPath:El(t,"affected-shadow-latest.json"),historyPath:El(t,"affected-shadow.jsonl")}}function Ml(e,t=n=>Jh(n,"utf-8")){let n=Nl(e),r;try{r=JSON.parse(t(n.latestPath))}catch(S){let v=ly(S),k=v?"telemetry-missing":cy(S);return Xe(n,k,v?void 0:S instanceof Error?S.message:String(S))}if(B(r)&&typeof r.version=="number"&&r.version!==1)return Xe(n,"unsupported-record-version",`Unsupported version ${r.version}.`);if(!sy(r))return Xe(n,"telemetry-malformed");if(r.status==="unavailable")return ay(r.reason)?{state:"unavailable",...n,reason:r.reason,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,...typeof r.error=="string"?{error:r.error}:{}}:Xe(n,"telemetry-malformed");if(r.status!=="evaluated")return Xe(n,"telemetry-malformed");let i=r.plan,o=r.comparison,s=r.evaluation;if(!B(r.manifest)||!B(i)||!B(o)||!B(s))return Xe(n,"telemetry-malformed");let a=i.mode,c=J(i.affectedFiles),l=J(i.reasons),d=J(o.changedFiles),p=J(s.predictedFiles),m=J(s.actualFiles),f=J(s.missingFiles),g=s.recall,h=s.affectedRatio;if(a!=="none"&&a!=="closure"&&a!=="full-project"||c===null||l===null||d===null||p===null||m===null||f===null||typeof s.passed!="boolean"||!Al(g)||!Al(h))return Xe(n,"telemetry-malformed");let y=m.length===0?1:(m.length-f.length)/m.length;return!Ll(c,p)||!Ll(d,m)||s.passed!==(f.length===0)||Math.abs(g-y)>Number.EPSILON||f.some(S=>!m.includes(S)||p.includes(S))?Xe(n,"telemetry-malformed"):{state:s.passed?"passing":"failing",...n,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,mode:a,recall:g,affectedRatio:h,predictedFiles:p,actualFiles:m,missingFiles:f,fallbackReasons:l}}function _l(e){if(e.state==="unavailable")return`unavailable (${e.reason})`;let t=e.missingFiles.length>0?`, ${e.missingFiles.length} missed`:"",n=e.fallbackReasons.length>0?`; fallback: ${e.fallbackReasons.join(", ")}`:"";return`${e.state}, ${(e.recall*100).toFixed(1)}% recall, ${e.predictedFiles.length} predicted / ${e.actualFiles.length} changed, ${(e.affectedRatio*100).toFixed(1)}% of project${t}${n}`}function ql(e,t,n=oy){let r=Nl(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var ey=8*1024*1024,ty=".previous";function ny(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function ry(e,t,n=ey){let r=`${JSON.stringify(ny(t))}
104
- `,i=Math.max(1,Math.floor(n)),o=`${e}${ty}`;if(Uh(Fl(e),{recursive:!0}),Dl(e)){let s=Kh(e).size;s>i?(Si(e,{force:!0}),Si(o,{force:!0})):s+Buffer.byteLength(r)>i&&(Si(o,{force:!0}),zh(e,o))}Gh(e,r)}function vi(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var iy={now:()=>Date.now(),databaseExists:e=>Dl(e),openDatabase:(e,t,n)=>new Oe({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>hn(e),dependencyGraph:e=>Sn(e),factDigests:e=>Yh(e)},oy={appendHistory:ry,writeLatest:(e,t)=>St(e,t,{spacing:2,trailingNewline:!0})};function rr(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(r).toISOString(),durationMs:Math.max(0,r-n),reason:t,...i?{error:i}:{}}}function jl(e){try{e?.close()}catch{}}function sy(e){return B(e)&&e.version===1&&typeof e.recordedAt=="string"&&(e.refreshResult==="rebuilt"||e.refreshResult==="reused")&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0}function ay(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="oracle-error"}function Al(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function Ll(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Xe(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function cy(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function ly(e){return e instanceof Error&&e.code==="ENOENT"}import{createHash as dy}from"crypto";import{copyFileSync as uy,existsSync as Bl,rmSync as Vl}from"fs";import{resolve as py}from"path";import Gl from"better-sqlite3";var my={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},fy={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Ul(e){let t=Date.now(),n=gy(e.affectedFiles);if(hy(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Vl(e.candidateDbPath,{force:!0}),!Bl(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Bl(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");Hl(e.previousDbPath,"previous SQLite generation",!1),Hl(e.miniDbPath,"incremental SQLite mini database"),uy(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new Gl(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),ki(r,"main","candidate SQLite generation"),ki(r,"incremental","incremental SQLite mini database"),yy(r,n),by(r,n.length);let i=wi(r,"main",!0),o=Ze(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{Sy(r),vy(r),xy(r),e.onStage?.("after-delete"),Ry(r),e.onStage?.("after-symbol-reconciliation"),ky(r),e.onStage?.("after-insert"),wy(r),$y(r,n.length,o),e.onStage?.("before-commit")}).immediate(),Jl(r,"main","candidate SQLite generation");let c=[...Cy(r)].filter(([l,d])=>i.get(l)!==d).map(([l])=>l).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:Date.now()-t}}catch(i){try{r?.close()}finally{Vl(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function gy(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function hy(e,t,n){let r=[e,t,n].map(i=>py(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Hl(e,t,n=!0){let r=new Gl(e,{readonly:!0,fileMustExist:!0});try{ki(r,"main",t),n&&Jl(r,"main",t)}finally{r.close()}}function ki(e,t,n){for(let[r,i]of Object.entries(my)){let s=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:a,type:c,notnull:l,pk:d})=>({name:a,type:c.toUpperCase(),notnull:l,pk:d}));if(JSON.stringify(s)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(fy)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),s=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(a=>a.name);if(o?.tbl_name!==i.table||JSON.stringify(s)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}Wl(e,t,"documents",["relative_path"],n),Wl(e,t,"global_symbols",["symbol"],n)}function Wl(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(a=>{if(a.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${a.name}')`).all().map(l=>l.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function Jl(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function yy(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let o of i)n.run(o)})(t)}function by(e,t){let n=Ze(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=Ze(e,`SELECT COUNT(*) AS value
103
+ `);n.set(r,o.digest("hex"))}return n}function Zh(e,t){let n=[],r=[],i=[],o=[],s=new Set([...e.keys(),...t.keys()]);for(let a of[...s].sort()){let c=e.get(a),l=t.get(a);c===void 0?n.push(a):l===void 0?i.push(a):c!==l?r.push(a):o.push(a)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function xi(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),s=e.affectedFiles.filter(c=>!i.has(c)).sort(),a=t.changedFiles.length-o.length;return{passed:o.length===0,recall:t.changedFiles.length===0?1:a/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:o,extraFiles:s}}function Ri(e,t=iy){let n=t.now();if(!t.databaseExists(e.previousDbPath))return rr(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return rr(e.refreshResult,"candidate-index-unavailable",n,t.now());let r=null,i=null;try{r=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),i=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let o=[...new Set([...t.indexedPaths(r),...t.indexedPaths(i)])].sort(),s=$n(e.previousSnapshot,e.currentSnapshot),a=new Set(o),c=s.changes.length>0&&!bi(s).fullProject&&s.changes.every(m=>a.has(m.path)),l=nr(s,c?t.dependencyGraph(r):new Map,o),d=Zh(t.factDigests(r),t.factDigests(i)),p=t.now();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(p).toISOString(),durationMs:Math.max(0,p-n),manifest:s,plan:l,comparison:d,evaluation:xi(l,d,o.length)}}catch(o){return rr(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{jl(r),jl(i)}}function Ol(e,t,n,r=Date.now()){return rr(e,t,r,r,n)}function Nl(e){let t=Fl(e);return{latestPath:El(t,"affected-shadow-latest.json"),historyPath:El(t,"affected-shadow.jsonl")}}function Ml(e,t=n=>Jh(n,"utf-8")){let n=Nl(e),r;try{r=JSON.parse(t(n.latestPath))}catch(S){let v=ly(S),k=v?"telemetry-missing":cy(S);return Xe(n,k,v?void 0:S instanceof Error?S.message:String(S))}if(q(r)&&typeof r.version=="number"&&r.version!==1)return Xe(n,"unsupported-record-version",`Unsupported version ${r.version}.`);if(!sy(r))return Xe(n,"telemetry-malformed");if(r.status==="unavailable")return ay(r.reason)?{state:"unavailable",...n,reason:r.reason,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,...typeof r.error=="string"?{error:r.error}:{}}:Xe(n,"telemetry-malformed");if(r.status!=="evaluated")return Xe(n,"telemetry-malformed");let i=r.plan,o=r.comparison,s=r.evaluation;if(!q(r.manifest)||!q(i)||!q(o)||!q(s))return Xe(n,"telemetry-malformed");let a=i.mode,c=J(i.affectedFiles),l=J(i.reasons),d=J(o.changedFiles),p=J(s.predictedFiles),m=J(s.actualFiles),f=J(s.missingFiles),g=s.recall,h=s.affectedRatio;if(a!=="none"&&a!=="closure"&&a!=="full-project"||c===null||l===null||d===null||p===null||m===null||f===null||typeof s.passed!="boolean"||!Al(g)||!Al(h))return Xe(n,"telemetry-malformed");let y=m.length===0?1:(m.length-f.length)/m.length;return!Ll(c,p)||!Ll(d,m)||s.passed!==(f.length===0)||Math.abs(g-y)>Number.EPSILON||f.some(S=>!m.includes(S)||p.includes(S))?Xe(n,"telemetry-malformed"):{state:s.passed?"passing":"failing",...n,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,mode:a,recall:g,affectedRatio:h,predictedFiles:p,actualFiles:m,missingFiles:f,fallbackReasons:l}}function _l(e){if(e.state==="unavailable")return`unavailable (${e.reason})`;let t=e.missingFiles.length>0?`, ${e.missingFiles.length} missed`:"",n=e.fallbackReasons.length>0?`; fallback: ${e.fallbackReasons.join(", ")}`:"";return`${e.state}, ${(e.recall*100).toFixed(1)}% recall, ${e.predictedFiles.length} predicted / ${e.actualFiles.length} changed, ${(e.affectedRatio*100).toFixed(1)}% of project${t}${n}`}function Bl(e,t,n=oy){let r=Nl(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var ey=8*1024*1024,ty=".previous";function ny(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function ry(e,t,n=ey){let r=`${JSON.stringify(ny(t))}
104
+ `,i=Math.max(1,Math.floor(n)),o=`${e}${ty}`;if(Uh(Fl(e),{recursive:!0}),Dl(e)){let s=Kh(e).size;s>i?(Si(e,{force:!0}),Si(o,{force:!0})):s+Buffer.byteLength(r)>i&&(Si(o,{force:!0}),zh(e,o))}Gh(e,r)}function vi(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var iy={now:()=>Date.now(),databaseExists:e=>Dl(e),openDatabase:(e,t,n)=>new Oe({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>hn(e),dependencyGraph:e=>Sn(e),factDigests:e=>Yh(e)},oy={appendHistory:ry,writeLatest:(e,t)=>St(e,t,{spacing:2,trailingNewline:!0})};function rr(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(r).toISOString(),durationMs:Math.max(0,r-n),reason:t,...i?{error:i}:{}}}function jl(e){try{e?.close()}catch{}}function sy(e){return q(e)&&e.version===1&&typeof e.recordedAt=="string"&&(e.refreshResult==="rebuilt"||e.refreshResult==="reused")&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0}function ay(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="oracle-error"}function Al(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function Ll(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Xe(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function cy(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function ly(e){return e instanceof Error&&e.code==="ENOENT"}import{createHash as dy}from"crypto";import{copyFileSync as uy,existsSync as ql,rmSync as Vl}from"fs";import{resolve as py}from"path";import Gl from"better-sqlite3";var my={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},fy={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Ul(e){let t=Date.now(),n=gy(e.affectedFiles);if(hy(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Vl(e.candidateDbPath,{force:!0}),!ql(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!ql(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");Hl(e.previousDbPath,"previous SQLite generation",!1),Hl(e.miniDbPath,"incremental SQLite mini database"),uy(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new Gl(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),ki(r,"main","candidate SQLite generation"),ki(r,"incremental","incremental SQLite mini database"),yy(r,n),by(r,n.length);let i=wi(r,"main",!0),o=Ze(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{Sy(r),vy(r),xy(r),e.onStage?.("after-delete"),Ry(r),e.onStage?.("after-symbol-reconciliation"),ky(r),e.onStage?.("after-insert"),wy(r),$y(r,n.length,o),e.onStage?.("before-commit")}).immediate(),Jl(r,"main","candidate SQLite generation");let c=[...Cy(r)].filter(([l,d])=>i.get(l)!==d).map(([l])=>l).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:Date.now()-t}}catch(i){try{r?.close()}finally{Vl(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function gy(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function hy(e,t,n){let r=[e,t,n].map(i=>py(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Hl(e,t,n=!0){let r=new Gl(e,{readonly:!0,fileMustExist:!0});try{ki(r,"main",t),n&&Jl(r,"main",t)}finally{r.close()}}function ki(e,t,n){for(let[r,i]of Object.entries(my)){let s=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:a,type:c,notnull:l,pk:d})=>({name:a,type:c.toUpperCase(),notnull:l,pk:d}));if(JSON.stringify(s)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(fy)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),s=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(a=>a.name);if(o?.tbl_name!==i.table||JSON.stringify(s)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}Wl(e,t,"documents",["relative_path"],n),Wl(e,t,"global_symbols",["symbol"],n)}function Wl(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(a=>{if(a.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${a.name}')`).all().map(l=>l.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function Jl(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function yy(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let o of i)n.run(o)})(t)}function by(e,t){let n=Ze(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=Ze(e,`SELECT COUNT(*) AS value
105
105
  FROM main.documents d
106
106
  JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
107
107
  FROM temp.incremental_affected_paths p
@@ -272,10 +272,10 @@ ${r.message}`:""}var al=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
272
272
  ${r}
273
273
  ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,p]of Object.entries({documents:i,chunks:o,definitions:s,mentions:a}))for(let m of p){let f=JSON.stringify([d,m]),g=c.get(m.relative_path)??[];g.push(f),c.set(m.relative_path,g)}let l=new Map;for(let[d,p]of[...c].sort(([m],[f])=>m.localeCompare(f))){let m=dy("sha256");for(let f of p.sort())m.update(f).update(`
274
274
  `);l.set(d,m.digest("hex"))}return l}function Ze(e,t){return e.prepare(t).get().value}import{readFileSync as Py,writeFileSync as Ty}from"fs";function pt(e,t){let n=Date.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:Date.now()-n,result:r}}function Kl(e){let t=e.readFingerprint(),n=Iy(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return Ey(e.cachePath,e.readFingerprint(),r),r}function Iy(e,t){try{let n=JSON.parse(Py(e,"utf-8"));return zl(n.fingerprint)===zl(t)?{result:n.result}:null}catch{return null}}function Ey(e,t,n){Ty(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
275
- `)}function zl(e){return JSON.stringify(e)}import{appendFileSync as jy,existsSync as Ay,mkdirSync as Ly,readFileSync as mT,renameSync as Dy,rmSync as Fy,statSync as Yl}from"fs";import{dirname as Xl,join as Oy}from"path";var ir="reindex-activity.jsonl",Ny=".previous",My=1024*1024,gT=1440*60*1e3,_y={appendFile:jy,exists:Ay,mkdir:e=>Ly(e,{recursive:!0}),rename:Dy,remove:e=>Fy(e,{force:!0}),size:e=>Yl(e).size};function $i(e){return Oy(Xl(e),ir)}function qy(e){if(e.reused)return 0;let t=Ql(e.indexPath)+Ql(e.dbPath);for(let n of e.shards??[])!n.reused&&n.outputBytes!==null&&(t+=n.outputBytes);return t}function Ci(e,t){let n=t.lastRefresh;n&&Pi($i(e),{version:1,event:"run",recordedAt:n.completedAt,trigger:n.trigger,result:n.result,durationMs:n.durationMs,estimatedLogicalOutputBytes:qy(t)})}function Zl(e,t){Pi($i(e),{version:1,event:"run",recordedAt:t.completedAt,trigger:t.trigger,result:"failed",durationMs:t.durationMs,estimatedLogicalOutputBytes:0})}function ed(e,t,n=new Date){Pi($i(e),{version:1,event:"suppressed",recordedAt:n.toISOString(),trigger:t,reason:"completed-index-is-fresh"})}function By(e,t,n=My,r=_y){let i=`${JSON.stringify(t)}
276
- `,o=Math.max(1,Math.floor(n)),s=`${e}${Ny}`;if(r.mkdir(Xl(e)),r.exists(e)){let a=r.size(e);a>o?(r.remove(e),r.remove(s)):a+Buffer.byteLength(i)>o&&(r.remove(s),r.rename(e,s))}r.appendFile(e,i)}function Pi(e,t){try{By(e,t)}catch{}}function Ql(e){try{return Yl(e).size}catch{return 0}}import{createHash as Vy}from"crypto";import{existsSync as Ti,readFileSync as Hy,readdirSync as Wy}from"fs";import{dirname as Ii,join as or,relative as Gy,resolve as Ei,sep as td}from"path";function nd(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let s=sd(o.path,t);s?r[s].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function rd(e,t){let n=new Map;for(let i of e){let o=t[i]?.packageName;o&&n.set(o,i)}let r=new Map;for(let i of e)r.set(i,new Set);for(let i of e){let o=t[i],s=r.get(i);if(!o||o.parseFailed){for(let a of e)a!==i&&s.add(a);continue}for(let a of o.dependencyNames){let c=n.get(a);c&&c!==i&&s.add(c)}for(let a of[...o.pathsTargets,...o.referencesPaths]){let c=sd(a,e);c&&c!==i&&s.add(c)}}return Uy(e,r)}function id(e,t,n){let r={};for(let i of e){let o=new Map;for(let s of t.files[i]??[])o.set(s.path,s);for(let s of n[i]??[])for(let a of t.files[s]??[])o.set(a.path,a);for(let s of t.shared)o.set(s.path,s);r[i]={files:[...o.values()].sort((s,a)=>s.path.localeCompare(a.path))}}return r}function ji(e){if(e===".")return"root";let t=Vy("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function od(e,t){let n=Ei(e),r={};for(let i of t)r[i]=Jy(n,i);return r}function sd(e,t){let n;for(let r of t)r!=="."&&(e===r||e.startsWith(`${r}/`))&&(!n||r.length>n.length)&&(n=r);return n}function Uy(e,t){let n={};for(let r of e){let i=new Set,o=[...t.get(r)??[]];for(;o.length>0;){let s=o.pop();if(!(s===r||i.has(s))){i.add(s);for(let a of t.get(s)??[])a!==r&&!i.has(a)&&o.push(a)}}n[r]=[...i].sort((s,a)=>s.localeCompare(a))}return n}function Jy(e,t){let n=t==="."?e:or(e,t),r=zy(n),i=Ky(n),o=i?Qy(i,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:r.name,dependencyNames:r.dependencyNames,pathsTargets:o.pathsTargets,referencesPaths:o.referencesPaths,parseFailed:r.failed||o.failed}}function zy(e){let t=or(e,"package.json");if(!Ti(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Ai(t);if(!n.ok)return{name:void 0,dependencyNames:[],failed:!0};let r=typeof n.value.name=="string"?n.value.name:void 0,i=new Set;for(let o of["dependencies","devDependencies","peerDependencies"]){let s=n.value[o];if(s&&typeof s=="object"&&!Array.isArray(s))for(let a of Object.keys(s))i.add(a)}return{name:r,dependencyNames:[...i],failed:!1}}function Ky(e){let t=or(e,"tsconfig.json");if(Ti(t))return t;let n;try{n=Wy(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?or(e,n[0]):void 0}function Qy(e,t){let n=Ai(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Yy(n.value,e,t),i=ad(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Yy(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=Ii(t),o=new Set;for(let s of r){if(!s||typeof s!="object")continue;let a=s.path;if(typeof a!="string"||a.trim()==="")continue;let c=cd(a,i,n);c&&o.add(c)}return[...o]}function ad(e,t,n,r){let i=Xy(t);if(i)return{pathsTargets:Zy(i,Ii(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=eb(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let s=Ai(o);return s.ok?ad(o,s.value,n,r+1):{pathsTargets:[],failed:!0}}function Xy(e){let t=e.compilerOptions;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.paths;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Zy(e,t,n){let r=new Set;for(let i of Object.values(e))if(Array.isArray(i))for(let o of i){if(typeof o!="string")continue;let s=cd(o,t,n);s&&r.add(s)}return[...r]}function eb(e,t,n){let r=Array.isArray(e)?e.at(-1):e;if(typeof r!="string"||r.trim()===""||!r.startsWith(".")&&!r.startsWith("/"))return;let i=Ei(Ii(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(td).includes("node_modules")&&pe(n,i)&&Ti(i))return i}function cd(e,t,n){let r=e.replace(/\/?\*+$/,""),i=Ei(t,r===""?".":r);if(!pe(n,i))return;let s=Gy(n,i).split(td).join("/");return s===""?".":s}function tb(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let o=e[n];if(r){if(t+=o,o==="\\"&&n+1<i){t+=e[n+1],n+=2;continue}o==='"'&&(r=!1),n+=1;continue}if(o==='"'){r=!0,t+=o,n+=1;continue}if(o==="/"&&e[n+1]==="/"){for(n+=2;n<i&&e[n]!==`
277
- `;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function Ai(e){try{let t=Hy(e,"utf-8"),n=JSON.parse(tb(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{existsSync as nb,readFileSync as rb,readdirSync as ib,statSync as ob}from"fs";import ne from"path";var sb=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function en(e,t=[]){let n=ne.resolve(e),r=t.flatMap(c=>cb(n,c));if(r.length>0)return ld(n,dd(r));let i=ab(n),o=dd(i),s=db(n,o)?[n,...o]:o,a=s.length>0?s:[n];return ld(n,a)}function ld(e,t){return[...new Set(t.map(n=>pb(e,n)))].sort((n,r)=>n.localeCompare(r))}function ab(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=ib(r,{withFileTypes:!0})}catch{continue}for(let o of i){let s=ne.join(r,o.name);if(o.isDirectory()){!sb.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&lb(s)&&t.push(ne.dirname(s))}}return t}function cb(e,t){let n=t.trim();if(!n)return[];let r=ne.resolve(e,n);if(!pe(e,r))return[];try{let i=ob(r);if(i.isDirectory())return[r];if(i.isFile()&&ud(ne.basename(r)))return[ne.dirname(r)]}catch{return[]}return[]}function lb(e){if(!ud(ne.basename(e)))return!1;let t=pd(e);return t?ne.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function ud(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function dd(e){let t=[...new Set(e.map(n=>ne.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&mb(n,r)))}function db(e,t){if(t.length===0||t.some(r=>ne.resolve(r)===e))return!1;let n=ne.join(e,"tsconfig.json");return nb(n)&&ub(n)}function ub(e){let n=pd(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!ne.extname(r))):!1}function pd(e){try{let t=JSON.parse(rb(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function pb(e,t){let n=ne.relative(e,t);return n?n.split(ne.sep).join("/"):"."}function mb(e,t){let n=ne.relative(e,t);return!!n&&!n.startsWith("..")&&!ne.isAbsolute(n)}import{createHash as Db}from"crypto";import{existsSync as Di,readFileSync as $d,statSync as Fb,writeFileSync as Fi}from"fs";import{join as Ob}from"path";import{readFileSync as md}from"fs";import{createRequire as fb}from"module";import{dirname as gb,isAbsolute as IT,relative as ET,resolve as jT,sep as AT}from"path";var fd=fb(import.meta.url),hb=1,gd="0.4.0";function Li(){let e=yb();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function yb(){try{let e=fd.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(md(e,"utf8"));if(t.version!==gd)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${gd}`};let n=gb(e),r=fd.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(md(r,"utf8"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:bb(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function bb(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${hb}`}import{createHash as Sb}from"crypto";import{readFileSync as vb}from"fs";import{dirname as xb,join as sr}from"path";var ar=2,Rb="typescript-index";function hd(e){let t=sr(e,Rb);return{rootDir:t,requestDir:sr(t,"requests"),responseDir:sr(t,"responses")}}function yd(e){try{let t=JSON.parse(vb(sr(xb(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:Sb("sha256").update(JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages})).digest("hex")}catch{return null}}import{randomUUID as kb}from"crypto";import{existsSync as wb,mkdirSync as bd,readFileSync as $b,rmSync as Sd}from"fs";import{resolve as vd}from"path";var Cb=12e4,Pb=5,cr=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=os(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Ab(),this.runtime=n.runtime??Lb}request(t){let n=Tn(this.cacheDir),r=hd(this.cacheDir),i=Vr(n.statePath);if(!xd(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),s=vd(r.requestDir,`${o}.json`),a=vd(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;bd(r.requestDir,{recursive:!0}),bd(r.responseDir,{recursive:!0}),St(s,{protocolVersion:ar,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(wb(a))return Tb($b(a,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=Vr(n.statePath);if(!xd(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Pb)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{Sd(s,{force:!0}),Sd(a,{force:!0})}}};function xd(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=ts,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===ar&&n.isProcessAlive(e.pid)&&(r||i)}function Tb(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==ar||o.id!==t||o.ok===!0&&o.baseGeneration!==n)throw new Error("TypeScript index service wrote an incompatible response.");if(o.ok!==!0)throw new Error(typeof o.error=="string"?o.error:"TypeScript index service request failed.");let s=Ib(o.response,r),a=[...new Set(i)].sort(),c=s.fragments.map(l=>l.relativePath).sort();if(JSON.stringify(c)!==JSON.stringify(a))throw new Error("TypeScript index service omitted or added an affected document.");return s}function Ib(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(o=>{if(!o||typeof o.relativePath!="string"||o.bytesBase64!==null&&typeof o.bytesBase64!="string"||typeof o.occurrences!="number"||!Number.isInteger(o.occurrences)||o.occurrences<0||typeof o.symbols!="number"||!Number.isInteger(o.symbols)||o.symbols<0||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(Eb)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let s=o.bytesBase64===null?null:jb(o.bytesBase64);return{relativePath:o.relativePath,bytes:s,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function Eb(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function jb(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Ab(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Cb}var Lb={now:Date.now,randomId:kb,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:bt};function Nb(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."];if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let n=$n(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};if(n.changes.some(l=>l.kind!=="modified"||l.inputKind!=="source"||!Ht(l.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=nr(n,e.graph,e.projectFiles);if(r.mode!=="closure"||r.affectedFiles.length===0)return{eligible:!1,reason:r.reasons.length>0?`affected set widened: ${r.reasons.join(", ")}`:"empty affected set"};let i=Mb([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=Rd(e.currentSnapshot,e.projectFiles,e.producerIdentity),s=Rd(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==s)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let a=wd(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!a)return{eligible:!1,reason:"prior document identity unavailable"};let c=wd(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:kd(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:kd(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:a,nextDocumentIdentities:c,tsconfigPath:i==="."?"tsconfig.json":`${i}/tsconfig.json`,projectArgument:i}:{eligible:!1,reason:"next document identity unavailable"}}function Mb(e,t){let n=null;for(let r of e){let i=t.filter(o=>o==="."||r===o||r.startsWith(`${o}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function Cd(e){let t=Date.now();try{if(!Di(e.previousDbPath)||!Di(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Li();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new Oe({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),s,a;try{s=hn(o,{includeIgnored:!1}).filter(Ht).sort(),a=Sn(o)}finally{o.close()}let c=performance.now()-n,l=Nb({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?en(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:s,graph:a,producerIdentity:r.producerIdentity,rootTsconfigExists:Di(Ob(e.projectRoot,"tsconfig.json"))});if(!l.eligible)throw new Error(l.reason);let d=yd(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let m=new cr({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:l.tsconfigPath,projectArgument:l.projectArgument,projectIdentity:l.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:l.plan.changedFiles,affectedFiles:l.plan.affectedFiles}),f=performance.now()-n,g=Fb(e.previousShardPath).size>=Qa;n=performance.now();let h=g?null:$d(e.previousShardPath),y=g?{completeIndexBytes:null,affectedIndexBytes:Ua(m.fragments)}:Ka({packageVersion:r.packageVersion,baseIndexBytes:h,fragments:m.fragments}),S=performance.now()-n;n=performance.now(),g?Ya({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,nextGenerationIdentity:l.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:m.fragments}):(Ja({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:h,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.previousFragmentGeneration,documentIdentities:l.previousDocumentIdentities,allowUntrackedDocuments:!0}),za({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.nextFragmentGeneration,fragments:m.fragments,documentIdentities:l.nextDocumentIdentities}));let v=performance.now()-n;n=performance.now(),y.completeIndexBytes&&Fi(e.candidateShardPath,y.completeIndexBytes),Fi(e.candidateAffectedScipPath,y.affectedIndexBytes);let k=performance.now()-n,R={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:Date.now()-t,cold:m.cold,changedFiles:l.plan.changedFiles,affectedFiles:l.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:l.previousFragmentGeneration,nextFragmentGeneration:l.nextFragmentGeneration,manifest:l.manifest,plan:l.plan,projectFileCount:s.length,referenceFragmentsByFile:new Map(m.fragments.map(D=>[D.relativePath,D.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:f,serviceMs:m.durationMs,assemblyMs:S,fragmentStoreMs:v,writeMs:k}};return e.onStatus(`Incremental TypeScript index emitted ${R.affectedFiles.length} affected document(s) in ${(R.durationMs/1e3).toFixed(3)}s (${R.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${f.toFixed(0)}ms, assembly ${S.toFixed(0)}ms, fragments ${v.toFixed(0)}ms, write ${k.toFixed(0)}ms).`),R}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function Pd(e){let t=Li();if(!t.available)throw new Error(t.reason);let n=Xa({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:$d(e.baseShardPath),packageVersion:t.packageVersion});Fi(e.candidateShardPath,n)}function Rd(e,t,n){let r=e.files.filter(i=>Yo(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return Oi(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function kd(e,t){return Oi(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function wd(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),s=us({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),a=new Map;for(let c of i){let l=s.identityFor(c,"typescript-scip-document-v1");if(l.key){a.set(c,l.key);continue}if(o.has(c))return null;a.set(c,Oi(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return a}function Oi(e){return Db("sha256").update(e).digest("hex")}import{execFile as _b}from"child_process";import{existsSync as lr,renameSync as Mi,rmSync as _i,statSync as qb}from"fs";import{cpus as Bb}from"os";import{join as Td}from"path";function Vb(e,t,n){if(!e.defaultOutputPath)return;let r=Td(t,e.defaultOutputPath);n!==r&&lr(r)&&Mi(r,n)}function Hb(e,t,n){if(!e.defaultOutputPath)return null;let r=Td(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return _i(i,{force:!0}),lr(r)?(Mi(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Wb(e){e&&(_i(e.defaultOutputPath,{force:!0}),e.backupPath&&lr(e.backupPath)&&Mi(e.backupPath,e.defaultOutputPath))}function Gb(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,Bb().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Id(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=Gb(o.length,r),c=await Jb(o,a,l=>Ni(l,t,n));if(a>1){let l=new Map;for(let d of c.filter(p=>p.skipped)){let p=o.find(m=>m.id===d.id);p&&(n(`Retrying ${p.label} indexer serially after parallel failure...`),l.set(p.id,await Ni(p,t,n)))}s.push(...c.map(d=>l.get(d.id)??d))}else s.push(...c);for(let l of i)s.push(await Ni(l,t,n));return s.sort((l,d)=>e.findIndex(p=>p.id===l.id)-e.findIndex(p=>p.id===d.id))}async function Ni(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),_i(e.scipPath,{force:!0});let r=Hb(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{let a=Uo(e.binary,e.args);await Ub(a.binary,a.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),Vb(e.config,t,e.scipPath)}catch(a){let c=a instanceof Error?a.message:String(a),l=`${e.resolvedBinary} indexer failed: ${c.split(`
278
- `)[0]}`,d=e.label===e.language?l:`${e.label}: ${l}`;return n(`Skipping ${e.label}: ${l}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:d}}}finally{Wb(r)}if(!lr(e.scipPath)){let a=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,c=e.label===e.language?a:`${e.label}: ${a}`;return n(`Skipping ${e.label}: ${a}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:c}}}let s;try{s=qb(e.scipPath).size}catch{s=void 0}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,outputBytes:s}}function Ub(e,t,n){return new Promise((r,i)=>{_b(e,[...t],n,o=>{o?i(o):r()})})}async function Jb(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 zb}from"child_process";import{platform as Kb}from"os";function dr(e,t){let n=e.installMethods,r=Rn(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(ze(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{zb(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:Kb()==="win32"});let o=kn(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}import ES from"better-sqlite3";import{existsSync as jS}from"fs";import{dirname as AS,join as LS,resolve as DS}from"path";import{readFileSync as Yb,rmSync as Xb,statSync as Zb,mkdtempSync as eS}from"fs";import{tmpdir as tS}from"os";import{join as qi}from"path";import{Worker as nS}from"worker_threads";function Qb(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function jt(){return{skippedReferences:0,skippedReferenceReasons:Qb(),skippedReferenceSamples:[]}}function ur(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let r of t.skippedReferenceSamples.filter(i=>i.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===r.sourceFile).length<2&&e.skippedReferenceSamples.push(r)}}function Ed(e){return e.length>=8&&Ad(e.length)>1}function jd(e){let t=Ad(e.vueFiles.length),n=iS(e.vueFiles),r=sS(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=eS(qi(tS(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=rS(),l=Date.now();try{for(let m=0;m<r.length;m++)new nS(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[m],resultPath:qi(o,`${m}.json`),sharedBuffer:s}});for(;Atomics.load(a,0)<r.length;){if(Date.now()-l>c)throw new Error(`Vue reference workers timed out after ${(c/1e3).toFixed(0)}s`);Atomics.wait(a,0,Atomics.load(a,0),100)}let d=r.map((m,f)=>{let g=JSON.parse(Yb(qi(o,`${f}.json`),"utf-8"));if(!g.ok)throw new Error(`Vue reference worker failed: ${g.error}`);return g.result}),p={occurrences:d.flatMap(m=>m.occurrences),...jt()};for(let m of d)ur(p,m);return p}finally{Xb(o,{recursive:!0,force:!0})}}function Ad(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function rS(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function iS(e){let t=oS(),n=[];for(let r of e){let i=Ld(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 oS(){return Number.POSITIVE_INFINITY}function sS(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:aS(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 aS(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Ld(e.fileName)-e.startOffset)}function Ld(e){try{return Zb(e).size}catch{return 1}}import{createRequire as cS}from"module";import{existsSync as lS,readFileSync as Vi}from"fs";import{dirname as Dd,extname as dS,join as Fd,relative as uS,resolve as pS}from"path";import{pathToFileURL as mS}from"url";function fS(e){e.transaction(()=>{e.prepare(`
275
+ `)}function zl(e){return JSON.stringify(e)}import{appendFileSync as jy,existsSync as Ay,mkdirSync as Ly,readFileSync as mT,renameSync as Dy,rmSync as Fy,statSync as Yl}from"fs";import{dirname as Xl,join as Oy}from"path";var ir="reindex-activity.jsonl",Ny=".previous",My=1024*1024,gT=1440*60*1e3,_y={appendFile:jy,exists:Ay,mkdir:e=>Ly(e,{recursive:!0}),rename:Dy,remove:e=>Fy(e,{force:!0}),size:e=>Yl(e).size};function $i(e){return Oy(Xl(e),ir)}function By(e){if(e.reused)return 0;let t=Ql(e.indexPath)+Ql(e.dbPath);for(let n of e.shards??[])!n.reused&&n.outputBytes!==null&&(t+=n.outputBytes);return t}function Ci(e,t){let n=t.lastRefresh;n&&Pi($i(e),{version:1,event:"run",recordedAt:n.completedAt,trigger:n.trigger,result:n.result,durationMs:n.durationMs,estimatedLogicalOutputBytes:By(t)})}function Zl(e,t){Pi($i(e),{version:1,event:"run",recordedAt:t.completedAt,trigger:t.trigger,result:"failed",durationMs:t.durationMs,estimatedLogicalOutputBytes:0})}function ed(e,t,n=new Date){Pi($i(e),{version:1,event:"suppressed",recordedAt:n.toISOString(),trigger:t,reason:"completed-index-is-fresh"})}function qy(e,t,n=My,r=_y){let i=`${JSON.stringify(t)}
276
+ `,o=Math.max(1,Math.floor(n)),s=`${e}${Ny}`;if(r.mkdir(Xl(e)),r.exists(e)){let a=r.size(e);a>o?(r.remove(e),r.remove(s)):a+Buffer.byteLength(i)>o&&(r.remove(s),r.rename(e,s))}r.appendFile(e,i)}function Pi(e,t){try{qy(e,t)}catch{}}function Ql(e){try{return Yl(e).size}catch{return 0}}import{createHash as Vy}from"crypto";import{existsSync as Ti,readFileSync as Hy,readdirSync as Wy}from"fs";import{dirname as Ii,join as or,relative as Gy,resolve as Ei,sep as td}from"path";function nd(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let s=sd(o.path,t);s?r[s].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function rd(e,t){let n=new Map;for(let i of e){let o=t[i]?.packageName;o&&n.set(o,i)}let r=new Map;for(let i of e)r.set(i,new Set);for(let i of e){let o=t[i],s=r.get(i);if(!o||o.parseFailed){for(let a of e)a!==i&&s.add(a);continue}for(let a of o.dependencyNames){let c=n.get(a);c&&c!==i&&s.add(c)}for(let a of[...o.pathsTargets,...o.referencesPaths]){let c=sd(a,e);c&&c!==i&&s.add(c)}}return Uy(e,r)}function id(e,t,n){let r={};for(let i of e){let o=new Map;for(let s of t.files[i]??[])o.set(s.path,s);for(let s of n[i]??[])for(let a of t.files[s]??[])o.set(a.path,a);for(let s of t.shared)o.set(s.path,s);r[i]={files:[...o.values()].sort((s,a)=>s.path.localeCompare(a.path))}}return r}function ji(e){if(e===".")return"root";let t=Vy("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function od(e,t){let n=Ei(e),r={};for(let i of t)r[i]=Jy(n,i);return r}function sd(e,t){let n;for(let r of t)r!=="."&&(e===r||e.startsWith(`${r}/`))&&(!n||r.length>n.length)&&(n=r);return n}function Uy(e,t){let n={};for(let r of e){let i=new Set,o=[...t.get(r)??[]];for(;o.length>0;){let s=o.pop();if(!(s===r||i.has(s))){i.add(s);for(let a of t.get(s)??[])a!==r&&!i.has(a)&&o.push(a)}}n[r]=[...i].sort((s,a)=>s.localeCompare(a))}return n}function Jy(e,t){let n=t==="."?e:or(e,t),r=zy(n),i=Ky(n),o=i?Qy(i,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:r.name,dependencyNames:r.dependencyNames,pathsTargets:o.pathsTargets,referencesPaths:o.referencesPaths,parseFailed:r.failed||o.failed}}function zy(e){let t=or(e,"package.json");if(!Ti(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Ai(t);if(!n.ok)return{name:void 0,dependencyNames:[],failed:!0};let r=typeof n.value.name=="string"?n.value.name:void 0,i=new Set;for(let o of["dependencies","devDependencies","peerDependencies"]){let s=n.value[o];if(s&&typeof s=="object"&&!Array.isArray(s))for(let a of Object.keys(s))i.add(a)}return{name:r,dependencyNames:[...i],failed:!1}}function Ky(e){let t=or(e,"tsconfig.json");if(Ti(t))return t;let n;try{n=Wy(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?or(e,n[0]):void 0}function Qy(e,t){let n=Ai(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Yy(n.value,e,t),i=ad(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Yy(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=Ii(t),o=new Set;for(let s of r){if(!s||typeof s!="object")continue;let a=s.path;if(typeof a!="string"||a.trim()==="")continue;let c=cd(a,i,n);c&&o.add(c)}return[...o]}function ad(e,t,n,r){let i=Xy(t);if(i)return{pathsTargets:Zy(i,Ii(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=eb(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let s=Ai(o);return s.ok?ad(o,s.value,n,r+1):{pathsTargets:[],failed:!0}}function Xy(e){let t=e.compilerOptions;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.paths;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Zy(e,t,n){let r=new Set;for(let i of Object.values(e))if(Array.isArray(i))for(let o of i){if(typeof o!="string")continue;let s=cd(o,t,n);s&&r.add(s)}return[...r]}function eb(e,t,n){let r=Array.isArray(e)?e.at(-1):e;if(typeof r!="string"||r.trim()===""||!r.startsWith(".")&&!r.startsWith("/"))return;let i=Ei(Ii(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(td).includes("node_modules")&&pe(n,i)&&Ti(i))return i}function cd(e,t,n){let r=e.replace(/\/?\*+$/,""),i=Ei(t,r===""?".":r);if(!pe(n,i))return;let s=Gy(n,i).split(td).join("/");return s===""?".":s}function tb(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let o=e[n];if(r){if(t+=o,o==="\\"&&n+1<i){t+=e[n+1],n+=2;continue}o==='"'&&(r=!1),n+=1;continue}if(o==='"'){r=!0,t+=o,n+=1;continue}if(o==="/"&&e[n+1]==="/"){for(n+=2;n<i&&e[n]!==`
277
+ `;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function Ai(e){try{let t=Hy(e,"utf-8"),n=JSON.parse(tb(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{existsSync as nb,readFileSync as rb,readdirSync as ib,statSync as ob}from"fs";import ne from"path";var sb=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function en(e,t=[]){let n=ne.resolve(e),r=t.flatMap(c=>cb(n,c));if(r.length>0)return ld(n,dd(r));let i=ab(n),o=dd(i),s=db(n,o)?[n,...o]:o,a=s.length>0?s:[n];return ld(n,a)}function ld(e,t){return[...new Set(t.map(n=>pb(e,n)))].sort((n,r)=>n.localeCompare(r))}function ab(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=ib(r,{withFileTypes:!0})}catch{continue}for(let o of i){let s=ne.join(r,o.name);if(o.isDirectory()){!sb.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&lb(s)&&t.push(ne.dirname(s))}}return t}function cb(e,t){let n=t.trim();if(!n)return[];let r=ne.resolve(e,n);if(!pe(e,r))return[];try{let i=ob(r);if(i.isDirectory())return[r];if(i.isFile()&&ud(ne.basename(r)))return[ne.dirname(r)]}catch{return[]}return[]}function lb(e){if(!ud(ne.basename(e)))return!1;let t=pd(e);return t?ne.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function ud(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function dd(e){let t=[...new Set(e.map(n=>ne.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&mb(n,r)))}function db(e,t){if(t.length===0||t.some(r=>ne.resolve(r)===e))return!1;let n=ne.join(e,"tsconfig.json");return nb(n)&&ub(n)}function ub(e){let n=pd(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!ne.extname(r))):!1}function pd(e){try{let t=JSON.parse(rb(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function pb(e,t){let n=ne.relative(e,t);return n?n.split(ne.sep).join("/"):"."}function mb(e,t){let n=ne.relative(e,t);return!!n&&!n.startsWith("..")&&!ne.isAbsolute(n)}import{createHash as Db}from"crypto";import{existsSync as Di,readFileSync as $d,statSync as Fb,writeFileSync as Fi}from"fs";import{join as Ob}from"path";import{readFileSync as md}from"fs";import{createRequire as fb}from"module";import{dirname as gb,isAbsolute as IT,relative as ET,resolve as jT,sep as AT}from"path";var fd=fb(import.meta.url),hb=1,gd="0.4.0";function Li(){let e=yb();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function yb(){try{let e=fd.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(md(e,"utf8"));if(t.version!==gd)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${gd}`};let n=gb(e),r=fd.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(md(r,"utf8"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:bb(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function bb(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${hb}`}import{createHash as Sb}from"crypto";import{readFileSync as vb}from"fs";import{dirname as xb,join as sr}from"path";var ar=2,Rb="typescript-index";function hd(e){let t=sr(e,Rb);return{rootDir:t,requestDir:sr(t,"requests"),responseDir:sr(t,"responses")}}function yd(e){try{let t=JSON.parse(vb(sr(xb(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:Sb("sha256").update(JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages})).digest("hex")}catch{return null}}import{randomUUID as kb}from"crypto";import{existsSync as wb,mkdirSync as bd,readFileSync as $b,rmSync as Sd}from"fs";import{resolve as vd}from"path";var Cb=12e4,Pb=5,cr=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=os(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Ab(),this.runtime=n.runtime??Lb}request(t){let n=Tn(this.cacheDir),r=hd(this.cacheDir),i=Vr(n.statePath);if(!xd(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),s=vd(r.requestDir,`${o}.json`),a=vd(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;bd(r.requestDir,{recursive:!0}),bd(r.responseDir,{recursive:!0}),St(s,{protocolVersion:ar,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(wb(a))return Tb($b(a,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=Vr(n.statePath);if(!xd(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Pb)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{Sd(s,{force:!0}),Sd(a,{force:!0})}}};function xd(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=ts,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===ar&&n.isProcessAlive(e.pid)&&(r||i)}function Tb(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==ar||o.id!==t||o.ok===!0&&o.baseGeneration!==n)throw new Error("TypeScript index service wrote an incompatible response.");if(o.ok!==!0)throw new Error(typeof o.error=="string"?o.error:"TypeScript index service request failed.");let s=Ib(o.response,r),a=[...new Set(i)].sort(),c=s.fragments.map(l=>l.relativePath).sort();if(JSON.stringify(c)!==JSON.stringify(a))throw new Error("TypeScript index service omitted or added an affected document.");return s}function Ib(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(o=>{if(!o||typeof o.relativePath!="string"||o.bytesBase64!==null&&typeof o.bytesBase64!="string"||typeof o.occurrences!="number"||!Number.isInteger(o.occurrences)||o.occurrences<0||typeof o.symbols!="number"||!Number.isInteger(o.symbols)||o.symbols<0||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(Eb)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let s=o.bytesBase64===null?null:jb(o.bytesBase64);return{relativePath:o.relativePath,bytes:s,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function Eb(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function jb(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Ab(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Cb}var Lb={now:Date.now,randomId:kb,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:bt};function Nb(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."];if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let n=$n(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};if(n.changes.some(l=>l.kind!=="modified"||l.inputKind!=="source"||!Ht(l.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=nr(n,e.graph,e.projectFiles);if(r.mode!=="closure"||r.affectedFiles.length===0)return{eligible:!1,reason:r.reasons.length>0?`affected set widened: ${r.reasons.join(", ")}`:"empty affected set"};let i=Mb([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=Rd(e.currentSnapshot,e.projectFiles,e.producerIdentity),s=Rd(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==s)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let a=wd(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!a)return{eligible:!1,reason:"prior document identity unavailable"};let c=wd(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:kd(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:kd(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:a,nextDocumentIdentities:c,tsconfigPath:i==="."?"tsconfig.json":`${i}/tsconfig.json`,projectArgument:i}:{eligible:!1,reason:"next document identity unavailable"}}function Mb(e,t){let n=null;for(let r of e){let i=t.filter(o=>o==="."||r===o||r.startsWith(`${o}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function Cd(e){let t=Date.now();try{if(!Di(e.previousDbPath)||!Di(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Li();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new Oe({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),s,a;try{s=hn(o,{includeIgnored:!1}).filter(Ht).sort(),a=Sn(o)}finally{o.close()}let c=performance.now()-n,l=Nb({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?en(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:s,graph:a,producerIdentity:r.producerIdentity,rootTsconfigExists:Di(Ob(e.projectRoot,"tsconfig.json"))});if(!l.eligible)throw new Error(l.reason);let d=yd(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let m=new cr({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:l.tsconfigPath,projectArgument:l.projectArgument,projectIdentity:l.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:l.plan.changedFiles,affectedFiles:l.plan.affectedFiles}),f=performance.now()-n,g=Fb(e.previousShardPath).size>=Qa;n=performance.now();let h=g?null:$d(e.previousShardPath),y=g?{completeIndexBytes:null,affectedIndexBytes:Ua(m.fragments)}:Ka({packageVersion:r.packageVersion,baseIndexBytes:h,fragments:m.fragments}),S=performance.now()-n;n=performance.now(),g?Ya({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,nextGenerationIdentity:l.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:m.fragments}):(Ja({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:h,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.previousFragmentGeneration,documentIdentities:l.previousDocumentIdentities,allowUntrackedDocuments:!0}),za({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.nextFragmentGeneration,fragments:m.fragments,documentIdentities:l.nextDocumentIdentities}));let v=performance.now()-n;n=performance.now(),y.completeIndexBytes&&Fi(e.candidateShardPath,y.completeIndexBytes),Fi(e.candidateAffectedScipPath,y.affectedIndexBytes);let k=performance.now()-n,R={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:Date.now()-t,cold:m.cold,changedFiles:l.plan.changedFiles,affectedFiles:l.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:l.previousFragmentGeneration,nextFragmentGeneration:l.nextFragmentGeneration,manifest:l.manifest,plan:l.plan,projectFileCount:s.length,referenceFragmentsByFile:new Map(m.fragments.map(D=>[D.relativePath,D.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:f,serviceMs:m.durationMs,assemblyMs:S,fragmentStoreMs:v,writeMs:k}};return e.onStatus(`Incremental TypeScript index emitted ${R.affectedFiles.length} affected document(s) in ${(R.durationMs/1e3).toFixed(3)}s (${R.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${f.toFixed(0)}ms, assembly ${S.toFixed(0)}ms, fragments ${v.toFixed(0)}ms, write ${k.toFixed(0)}ms).`),R}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function Pd(e){let t=Li();if(!t.available)throw new Error(t.reason);let n=Xa({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:$d(e.baseShardPath),packageVersion:t.packageVersion});Fi(e.candidateShardPath,n)}function Rd(e,t,n){let r=e.files.filter(i=>Yo(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return Oi(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function kd(e,t){return Oi(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function wd(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),s=us({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),a=new Map;for(let c of i){let l=s.identityFor(c,"typescript-scip-document-v1");if(l.key){a.set(c,l.key);continue}if(o.has(c))return null;a.set(c,Oi(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return a}function Oi(e){return Db("sha256").update(e).digest("hex")}import{execFile as _b}from"child_process";import{existsSync as lr,renameSync as Mi,rmSync as _i,statSync as Bb}from"fs";import{cpus as qb}from"os";import{join as Td}from"path";function Vb(e,t,n){if(!e.defaultOutputPath)return;let r=Td(t,e.defaultOutputPath);n!==r&&lr(r)&&Mi(r,n)}function Hb(e,t,n){if(!e.defaultOutputPath)return null;let r=Td(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return _i(i,{force:!0}),lr(r)?(Mi(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Wb(e){e&&(_i(e.defaultOutputPath,{force:!0}),e.backupPath&&lr(e.backupPath)&&Mi(e.backupPath,e.defaultOutputPath))}function Gb(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,qb().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Id(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=Gb(o.length,r),c=await Jb(o,a,l=>Ni(l,t,n));if(a>1){let l=new Map;for(let d of c.filter(p=>p.skipped)){let p=o.find(m=>m.id===d.id);p&&(n(`Retrying ${p.label} indexer serially after parallel failure...`),l.set(p.id,await Ni(p,t,n)))}s.push(...c.map(d=>l.get(d.id)??d))}else s.push(...c);for(let l of i)s.push(await Ni(l,t,n));return s.sort((l,d)=>e.findIndex(p=>p.id===l.id)-e.findIndex(p=>p.id===d.id))}async function Ni(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),_i(e.scipPath,{force:!0});let r=Hb(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{let a=Uo(e.binary,e.args);await Ub(a.binary,a.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),Vb(e.config,t,e.scipPath)}catch(a){let c=a instanceof Error?a.message:String(a),l=`${e.resolvedBinary} indexer failed: ${c.split(`
278
+ `)[0]}`,d=e.label===e.language?l:`${e.label}: ${l}`;return n(`Skipping ${e.label}: ${l}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:d}}}finally{Wb(r)}if(!lr(e.scipPath)){let a=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,c=e.label===e.language?a:`${e.label}: ${a}`;return n(`Skipping ${e.label}: ${a}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:c}}}let s;try{s=Bb(e.scipPath).size}catch{s=void 0}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,outputBytes:s}}function Ub(e,t,n){return new Promise((r,i)=>{_b(e,[...t],n,o=>{o?i(o):r()})})}async function Jb(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 zb}from"child_process";import{platform as Kb}from"os";function dr(e,t){let n=e.installMethods,r=Rn(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(ze(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{zb(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:Kb()==="win32"});let o=kn(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}import ES from"better-sqlite3";import{existsSync as jS}from"fs";import{dirname as AS,join as LS,resolve as DS}from"path";import{readFileSync as Yb,rmSync as Xb,statSync as Zb,mkdtempSync as eS}from"fs";import{tmpdir as tS}from"os";import{join as Bi}from"path";import{Worker as nS}from"worker_threads";function Qb(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function jt(){return{skippedReferences:0,skippedReferenceReasons:Qb(),skippedReferenceSamples:[]}}function ur(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let r of t.skippedReferenceSamples.filter(i=>i.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===r.sourceFile).length<2&&e.skippedReferenceSamples.push(r)}}function Ed(e){return e.length>=8&&Ad(e.length)>1}function jd(e){let t=Ad(e.vueFiles.length),n=iS(e.vueFiles),r=sS(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=eS(Bi(tS(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=rS(),l=Date.now();try{for(let m=0;m<r.length;m++)new nS(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[m],resultPath:Bi(o,`${m}.json`),sharedBuffer:s}});for(;Atomics.load(a,0)<r.length;){if(Date.now()-l>c)throw new Error(`Vue reference workers timed out after ${(c/1e3).toFixed(0)}s`);Atomics.wait(a,0,Atomics.load(a,0),100)}let d=r.map((m,f)=>{let g=JSON.parse(Yb(Bi(o,`${f}.json`),"utf-8"));if(!g.ok)throw new Error(`Vue reference worker failed: ${g.error}`);return g.result}),p={occurrences:d.flatMap(m=>m.occurrences),...jt()};for(let m of d)ur(p,m);return p}finally{Xb(o,{recursive:!0,force:!0})}}function Ad(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function rS(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function iS(e){let t=oS(),n=[];for(let r of e){let i=Ld(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 oS(){return Number.POSITIVE_INFINITY}function sS(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:aS(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 aS(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Ld(e.fileName)-e.startOffset)}function Ld(e){try{return Zb(e).size}catch{return 1}}import{createRequire as cS}from"module";import{existsSync as lS,readFileSync as Vi}from"fs";import{dirname as Dd,extname as dS,join as Fd,relative as uS,resolve as pS}from"path";import{pathToFileURL as mS}from"url";function fS(e){e.transaction(()=>{e.prepare(`
279
279
  DELETE FROM mentions
280
280
  WHERE chunk_id IN (
281
281
  SELECT c.id
@@ -295,7 +295,7 @@ ${r.message}`:""}var al=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
295
295
  FROM documents
296
296
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
297
297
  ORDER BY relative_path
298
- `).all().map(r=>pS(t,r.relativePath))}function Nd(e,t){let{vueCore:n,ts:r,volarTs:i}=gS(e),{parsed:o,vueOptions:s}=hS(n,r,t),a=Dd(t),c=n.createVueLanguagePlugin(r,o.options,s,f=>f),l=yS(n,r,c),d=bS(a,o),{languageServiceHost:p}=i.createLanguageServiceHost(r,r.sys,l,f=>f,d),m=r.createLanguageService(p);return{ts:r,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function gS(e){let t=cS(mS(Fd(e,"package.json")).href);return{vueCore:Bi(t,"@vue/language-core",e),ts:Bi(t,"typescript",e),volarTs:Bi(t,"@volar/typescript",e)}}function hS(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,Dd(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function yS(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!lS(o))return;let s=Vi(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??wS(o))});return r.current=i,i}function bS(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Bi(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 Md(e,t,n){let r=SS(e);return i=>{if(!i.name)return null;let o=He(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.starts.find(p=>p.line===a.line&&p.displayName===i.name);if(l)return l.symbolId;let d=c.containingByLine.get(a.line);return d&&d.displayName===i.name?d.symbolId:vS(c.starts,a.line,2,i.name)}}function SS(e){let t=e.prepare(`
298
+ `).all().map(r=>pS(t,r.relativePath))}function Nd(e,t){let{vueCore:n,ts:r,volarTs:i}=gS(e),{parsed:o,vueOptions:s}=hS(n,r,t),a=Dd(t),c=n.createVueLanguagePlugin(r,o.options,s,f=>f),l=yS(n,r,c),d=bS(a,o),{languageServiceHost:p}=i.createLanguageServiceHost(r,r.sys,l,f=>f,d),m=r.createLanguageService(p);return{ts:r,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function gS(e){let t=cS(mS(Fd(e,"package.json")).href);return{vueCore:qi(t,"@vue/language-core",e),ts:qi(t,"typescript",e),volarTs:qi(t,"@volar/typescript",e)}}function hS(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,Dd(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function yS(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!lS(o))return;let s=Vi(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??wS(o))});return r.current=i,i}function bS(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function qi(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 Md(e,t,n){let r=SS(e);return i=>{if(!i.name)return null;let o=He(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.starts.find(p=>p.line===a.line&&p.displayName===i.name);if(l)return l.symbolId;let d=c.containingByLine.get(a.line);return d&&d.displayName===i.name?d.symbolId:vS(c.starts,a.line,2,i.name)}}function SS(e){let t=e.prepare(`
299
299
  SELECT
300
300
  d.relative_path AS relativePath,
301
301
  der.start_line AS startLine,
@@ -309,19 +309,19 @@ ${r.message}`:""}var al=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
309
309
  `).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,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function vS(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let a=Math.floor((i+o)/2);e[a].line<t?i=a+1:o=a-1}let s=null;for(let a of[o,i]){let c=e[a];if(!c||c.displayName!==r)continue;let l=Math.abs(c.line-t);l>n||(!s||l<s.distance)&&(s={distance:l,symbolId:c.symbolId})}return s?.symbolId??null}function _d(e,t,n){let r=PS(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
310
310
  INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
311
311
  VALUES (?, ?, ?, ?)
312
- `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let d=He(t,l),p=zd(r.name,r.version,d);o.run(p,"default",7,`Vue component|${d}`);let m=TS(i,r,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function qd(e,t,n,r,i){return e.transaction(()=>(fS(e),xS(e,t,n,r),RS(e,i)))()}function xS(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
312
+ `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let d=He(t,l),p=zd(r.name,r.version,d);o.run(p,"default",7,`Vue component|${d}`);let m=TS(i,r,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Bd(e,t,n,r,i){return e.transaction(()=>(fS(e),xS(e,t,n,r),RS(e,i)))()}function xS(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
313
313
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
314
314
  VALUES (?, ?, ?, ?, X'00')
315
315
  `),s=e.prepare(`
316
316
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
317
317
  VALUES (?, ?, 1)
318
- `);for(let a of n){let c=r.get(a);if(!c)continue;let l=He(t,a),d=i.get(l);if(!d)continue;let p=o.run(d.id,-1,0,0);s.run(Number(p.lastInsertRowid),c)}}function Bd(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(Hi(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Vd(e){let t=new Set,n=[];for(let r of e){let i=Hd(r);t.has(i)||(t.add(i),n.push(r))}return n}function Hd(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function RS(e,t){let n=CS(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
318
+ `);for(let a of n){let c=r.get(a);if(!c)continue;let l=He(t,a),d=i.get(l);if(!d)continue;let p=o.run(d.id,-1,0,0);s.run(Number(p.lastInsertRowid),c)}}function qd(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(Hi(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Vd(e){let t=new Set,n=[];for(let r of e){let i=Hd(r);t.has(i)||(t.add(i),n.push(r))}return n}function Hd(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function RS(e,t){let n=CS(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
319
319
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
320
320
  VALUES (?, ?, ?, ?, X'00')
321
321
  `),i=e.prepare(`
322
322
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
323
323
  VALUES (?, ?, 0)
324
- `),o=new Set,s=0,a=0;for(let c of t){let l=Hd(c);if(o.has(l))continue;o.add(l);let d=n.get(c.sourceFile);if(!d)continue;let p=r.run(d,a++,c.sourceLine,c.sourceLine),m=i.run(Number(p.lastInsertRowid),c.symbolId);s+=Number(m.changes)}return s}function*Wd(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 Gd(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Hi(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function kS(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 Ud(e,t){return He(e,t).startsWith("node_modules/")}function He(e,t){return uS(e,t).replaceAll("\\","/")}function wS(e){switch(dS(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 Jd(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Vi(t,"utf-8"),r={text:n,lineStarts:$S(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:kS}}function $S(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function CS(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 PS(e){try{let t=JSON.parse(Vi(Fd(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 TS(e,t,n,r){let i=He(n,r),o=zd(t.name,t.version,i);return e.get(o)?.id??null}function zd(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Qd(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>FS({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Ui(e){return pt(ut(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),pt(Qd({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function FS(e){let t=DS(e.projectRoot,e.tsconfig);if(!jS(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new ES(e.dbPath);try{let r=Od(n,e.projectRoot),i=LS(AS(e.dbPath),"augment-vue-meta.json");return Kl({cachePath:i,readFingerprint:()=>MS(n,e.projectRoot,e.tsconfig),compute:()=>OS({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function OS(e){let t=_d(e.db,e.projectRoot,e.vueFiles),n=NS(e,t),r=Vd(n.occurrences),i=qd(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:JS(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:US(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function NS(e,t){if(Ed(e.vueFiles))return jd({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=_S({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return qS({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function MS(e,t,n){let r=e.prepare(`
324
+ `),o=new Set,s=0,a=0;for(let c of t){let l=Hd(c);if(o.has(l))continue;o.add(l);let d=n.get(c.sourceFile);if(!d)continue;let p=r.run(d,a++,c.sourceLine,c.sourceLine),m=i.run(Number(p.lastInsertRowid),c.symbolId);s+=Number(m.changes)}return s}function*Wd(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 Gd(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Hi(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function kS(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 Ud(e,t){return He(e,t).startsWith("node_modules/")}function He(e,t){return uS(e,t).replaceAll("\\","/")}function wS(e){switch(dS(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 Jd(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Vi(t,"utf-8"),r={text:n,lineStarts:$S(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:kS}}function $S(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function CS(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 PS(e){try{let t=JSON.parse(Vi(Fd(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 TS(e,t,n,r){let i=He(n,r),o=zd(t.name,t.version,i);return e.get(o)?.id??null}function zd(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Qd(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>FS({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Ui(e){return pt(ut(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),pt(Qd({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function FS(e){let t=DS(e.projectRoot,e.tsconfig);if(!jS(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new ES(e.dbPath);try{let r=Od(n,e.projectRoot),i=LS(AS(e.dbPath),"augment-vue-meta.json");return Kl({cachePath:i,readFingerprint:()=>MS(n,e.projectRoot,e.tsconfig),compute:()=>OS({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function OS(e){let t=_d(e.db,e.projectRoot,e.vueFiles),n=NS(e,t),r=Vd(n.occurrences),i=Bd(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:JS(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:US(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function NS(e,t){if(Ed(e.vueFiles))return jd({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=_S({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return BS({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function MS(e,t,n){let r=e.prepare(`
325
325
  SELECT
326
326
  (SELECT COUNT(*) FROM documents) AS documents,
327
327
  (SELECT COUNT(*) FROM global_symbols) AS symbols,
@@ -330,17 +330,17 @@ ${r.message}`:""}var al=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
330
330
  (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
331
331
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
332
332
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
333
- `).get();return{version:3,tsconfig:n,files:Cn(t),db:r}}function _S(e){let t=Jd();return{projectRoot:e.projectRoot,context:Nd(e.projectRoot,e.configPath),symbolLookup:Md(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function qS(e){let t=[],n=jt(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=BS(e,i);t.push(...o.occurrences),ur(n,o)}return{occurrences:t,...n}}function BS(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Kd(e.projectRoot,t,"missing-source-file");let r=e.context.language.scripts.get(t.fileName),i=r?.generated?.languagePlugin.typescript?.getServiceScript(r.generated.root)?.code;if(!r||!i)return Kd(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),s=He(e.projectRoot,t.fileName),a=[...Wd(n.text)],c={tokens:a.filter(l=>l.start>=t.startOffset&&l.start<t.endOffset),tokenByStart:new Map(a.map(l=>[l.start,l])),tokenTextCounts:KS(a),processedStarts:new Set};return VS({...e,fileName:t.fileName,sourceInfo:n,sourceFile:s,map:o,tokenContext:c})}function VS(e){let t=[],n=jt();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||HS(e.sourceInfo.text,r.start))continue;let i=Gd(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!Ud(e.projectRoot,d.fileName));if(!s){Wi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let a=He(e.projectRoot,s.fileName),c=WS(e.sourceFile,r.text,a);if(c){Wi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let l=Bd(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(l===null){Wi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}Yd(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a,l),e.tokenContext.processedStarts.add(r.start),zS(t,e,r,i,a,l)}return{occurrences:t,...n}}function HS(e,t){let n=e.lastIndexOf(`
334
- `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function WS(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Kd(e,t,n){let r=jt();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:He(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Wi(e,t,n,r,i,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(a=>a.reason===o&&a.sourceFile===r).length>=2)return;let s=t.positionAt(n,i.start);e.skippedReferenceSamples.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,token:i.text,reason:o})}function Gi(e,t){let n=new Map;for(let o of e){let s=n.get(o.sourceFile)??[];s.push(o),n.set(o.sourceFile,s)}let r=[...n.keys()].sort(),i=[];for(let o=0;i.length<t;o++){let s=!1;for(let a of r){let c=n.get(a)?.[o];if(c&&(i.push(c),s=!0,i.length===t))break}if(!s)break}return i}function GS(e,t){let n=Gi(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),r=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),i=Gi(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function US(e,t){let n=[...new Set(e.map(i=>i.reason))].sort(),r=[];for(let[i,o]of n.entries()){let s=n.length-i,a=Math.ceil((t-r.length)/s);r.push(...Gi(e.filter(c=>c.reason===o),a))}return r.slice(0,t)}function JS(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return GS(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function zS(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of QS(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(s))continue;let a=t.tokenContext.tokenByStart.get(s);a&&(Yd(e,t.sourceReader,t.sourceInfo,t.sourceFile,a,i,o),t.tokenContext.processedStarts.add(s))}}function Yd(e,t,n,r,i,o,s){let a=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+i.text.length,sourceToken:i.text,definitionFile:o,symbolId:s})}function KS(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function QS(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 d=YS(r,l.textSpan.start,o,i.text);d!==null&&a.push(d)}return a}function YS(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Hi(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function At(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=cv(e),s=Date.now();mr(_(o.outputScip),{recursive:!0}),mr(_(o.outputDb),{recursive:!0});let a=e.languages??rt(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=Mt("reindex.fingerprint",()=>es(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:a.length}),l,d;if(e.skipIfUnchanged!==!1&&!rc(t,o.outputDb)&&Xd(o.outputScip)===Xd(ee(_(o.outputDb),"index.scip"))){let g=nt(t);if(l=g?An(g,c):void 0,l){let h=Ln(l);if(h){if(!av(o,c))try{Gr({snapshot:l,manifest:h,targetCacheDir:_(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${l.generationId.slice(0,12)}`)}catch(y){r(`Shared generation attach failed; continuing locally: ${nn(y)}`)}}else{let y=await sc(l);if(y.kind==="owner")d=y.release;else if(y.kind==="generation-ready"){let S=Ln(l);if(S)try{Gr({snapshot:l,manifest:S,targetCacheDir:_(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${l.generationId.slice(0,12)} after waiting`)}catch(v){r(`Shared generation attach failed after waiting; continuing locally: ${nn(v)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=Ga(ee(_(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!p)throw d?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${_(o.outputDb)}.`);let m;try{m=await _t("reindex.lock",()=>Fv(ee(_(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:a.length})}catch(g){throw p.release(),d?.(),g}let f=null;try{let g=pv(_(o.outputDb));g.removed>0&&r(`Removed ${g.removed} abandoned reindex workspace(s)`);for(let R of g.errors)r(`Could not remove abandoned reindex workspace: ${R}`);let h=null,y=Mt("reindex.reuse-check",()=>(h=lv({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r}),h),()=>({languages:a.length,reused:h!==null}));if(y)return Zd({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),Ci(o.outputDb,y),y;await _t("reindex.scip-cli-ready",()=>Pv(i,r));let S=uv(o);f=S.runDir;let v,k=await _t("reindex.fresh",async()=>(v=await mv({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:S,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),v),()=>({languages:a.length,reused:v?.reused,skipped:v?.skipped.length}));return Zd({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),Ci(o.outputDb,k),k}catch(g){let h=yr({trigger:e.trigger,result:"failed",start:s,error:g instanceof Error?g.message:String(g)});throw hu(o.metaPath,h),Zl(o.outputDb,h),g}finally{f&&Ge(f,{recursive:!0,force:!0}),m(),p.release(),d?.()}}function Zd(e){if(e.snapshot){if(Ln(e.snapshot)){Ur(e.snapshot,_(e.paths.outputDb),"local-fresh");return}try{let t=nt(e.projectRoot),n=t?An(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}oc({snapshot:e.snapshot,sourceCacheDir:_(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=nt(e.projectRoot);return(r?An(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),Ur(e.snapshot,_(e.paths.outputDb),"built"),e.onStatus(`Published shared generation ${e.snapshot.generationId.slice(0,12)}`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${nn(t)}`)}}}function av(e,t){if(!Re(e.outputScip)||!Re(e.outputDb)||!gu(e.metaPath,t))return!1;let n=it(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function nn(e){return e instanceof Error?e.message:String(e)}function cv(e){let t=e.outputScip??ee(e.projectRoot,"index.scip"),n=e.outputDb??ee(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:ee(_(n),"meta.json")}}function lv(e){let t=it(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!Re(e.paths.outputScip)||!Re(e.paths.outputDb)||!gu(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;pt(ut(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=yr({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return hu(e.paths.metaPath,r),e.onStatus(`Index unchanged; reused existing SQLite index in ${(n/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:n,reused:!0,skipped:[],lastRefresh:r,shards:dv(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function dv(e,t,n,r){let i=mu(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:tn(i[o]),outputBytes:rn(Ki(e.outputDb,o)),durationMs:0}))}function uv(e){let t=tv(ee(_(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:ee(t,pr(e.outputScip)),tempOutputDb:ee(t,pr(e.outputDb)),tempMetaPath:ee(t,pr(e.metaPath))}}function pv(e){let t=[],n;try{n=ou(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[nn(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{Ge(ee(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${nn(o)}`)}return{removed:r,errors:t}}async function mv(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await _t("reindex.language-indexers",async()=>(n=await gv(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:s,languageFingerprints:a,shards:c,typescriptProjectShardContext:l,incrementalTypeScript:d}=r;if(s.length>0&&e.onStatus(`Reused ${s.length} cached language shard(s): ${s.join(", ")}`),fv({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:s})){let f=Mt("reindex.publish",()=>wv(e,i,o,s,a,l),{mode:"metadata-only",languages:i.length,reused:s.length}),g=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(h=>h.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:f,shards:c}}let p=Mt("reindex.publish",()=>kv(e,t,i,o,s,a,l,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:s.length,skipped:o.length}),m=p.durationMs;return e.onStatus(`Done in ${(m/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:m,reused:!1,skipped:o,lastRefresh:p,shards:c}}function fv(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!Re(e.run.paths.outputScip)||!Re(e.run.paths.outputDb))return!1;let t=it(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(i=>i.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(i=>n.has(i)&&r.has(i))}async function gv(e,t){let n=vv({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),r=[],i=new Set;for(let[F,Z]of n)Z.reused&&(r.push({language:F,scipPath:Z.scipPath}),i.add(F));for(let F of i)e.onStatus(`Reusing cached ${F} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),s=it(e.paths.outputDb,e.paths.metaPath),a=sn(e.paths.metaPath),c=s.state==="legacy"||s.state==="current",l=a?.scipCompanion!=="deferred"&&(s.state!=="current"||s.generation.publication?.scipCompanion!=="deferred"),d=o&&!o.reused&&c?Cd({projectRoot:e.projectRoot,cacheDir:_(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:on(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:on(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:zi(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(d?["typescript"]:[]),m=d?void 0:hv(e,n),{preparedRuns:f,skippedLanguages:g,languageOutputScipPaths:h}=Tv({languages:e.languages.filter(F=>!i.has(F)&&!p.has(F)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:m?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),y=m?f.filter(F=>F.language!=="typescript"||m.missedProjectIds.has(F.id)):f,S=await Id(y,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),v=[];if(m){bv(e.paths.outputDb,S);let F=h.typescript??e.tempPaths.tempOutputScip;v=Sv({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:F,reusedProjects:m.reusedProjects})}let k=[...S,...v],{indexedOutputs:R}=Ev(k,g),D=d?[{language:"typescript",scipPath:d.scipPath}]:[],q=[...r,...D,...R];jv(q,g,e.languages,e.opts.allowPartial,e.onStatus);let z=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:rn(d.scipPath)??void 0}]:[],T=xv(n,[...S,...z],m?{outputDb:e.paths.outputDb,classification:m.classification}:void 0);return{indexedOutputs:q,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Rv(n,e.languages),shards:T,typescriptProjectShardContext:m?{projects:m.allProjects,fingerprints:m.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function hv(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=en(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=od(e.projectRoot,r),o=nd(n.fingerprint.files,r),s=rd(r,i),a=id(r,o,s),c=sn(e.paths.metaPath),d=yv(c,a,g=>Re(hr(e.paths.outputDb,g))),p=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),m=new Set(p),f=new Set(r.filter(g=>!m.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:a,classification:d,reusedProjects:p,missedProjectIds:f}}function yv(e,t,n){let r=new Map;for(let i of Object.keys(t)){let o=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let s=e.typescriptProjectShards?.[i];if(!s){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(We(s)!==We(o)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}r.set(i,{reused:!0,fingerprint:o})}return r}function bv(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=hr(e,r);mr(_(i),{recursive:!0}),fr(n.scipPath,i)}}function Sv(e){return e.reusedProjects.map((t,n)=>{let r=hr(e.outputDb,t),i=on(e.tempOutputScip,"typescript-project-cached",n);return fr(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:rn(i)??void 0}})}function vv(e){let t=sn(e.paths.metaPath),n=mu(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Ki(e.paths.outputDb,i),s=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:s,scipPath:o});continue}if(t.version!==3){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:o});continue}if(i==="typescript"&&t.scipCompanion==="deferred"){r.set(i,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:s,scipPath:o});continue}if(!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:s,scipPath:o});continue}let a=t.languageFingerprints[i];if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:s,scipPath:o});continue}if(!Re(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:o});continue}if(We(a)!==We(s)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:s,scipPath:o});continue}r.set(i,{reused:!0,fingerprint:s,scipPath:o})}return r}function xv(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:tn(o.fingerprint),outputBytes:rn(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),s=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,a=s?n.classification.get(s):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:a?.reason??o?.reason??i.skipped?.reason,fingerprint:a?tn(a.fingerprint):o?tn(o.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,o]of n.classification)o.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:tn(o.fingerprint),outputBytes:rn(hr(n.outputDb,i)),durationMs:0});return r}function tn(e){return ZS("sha256").update(We(e)).digest("hex").slice(0,16)}function rn(e){try{return rv(e).size}catch{return null}}function Rv(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function kv(e,t,n,r,i,o,s,a){let c=!a||a.completeScipUpdated,l=!1;c&&(eu(e.paths.outputDb,n),l=tu(n,e.tempPaths.tempOutputScip,e.onStatus));let d=Av({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:a,completeScipAvailable:c,completeScipSanitized:l,materializeFullFallback:()=>{if(!a||a.completeScipUpdated)return l;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Pd({cacheDir:_(e.paths.outputDb),generationIdentity:a.nextFragmentGeneration,baseShardPath:a.scipPath,candidateShardPath:a.candidateScipPath});let v=n.map(k=>k.language==="typescript"?{language:k.language,scipPath:a.candidateScipPath}:k);return eu(e.paths.outputDb,v),l=tu(v,e.tempPaths.tempOutputScip,e.onStatus),l}});if(pt(ut(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&a){let v=null,k=null;try{v=new Oe({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),k=new Oe({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let R=ps(v,e.fingerprint,a.referenceFragmentsByFile,k);e.onStatus(`Cached exact TypeScript reference fragments for ${R} affected document(s).`)}catch(R){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${R instanceof Error?R.message:String(R)}.`)}finally{v?.close(),k?.close()}}let p=zi(e.paths.metaPath),m=d.mode==="incremental"&&a?Dv(a,d.changedDocumentPaths):Ri({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:p,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),f=yr({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(v=>v.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",h={...o};g&&delete h.typescript;let{metadata:y,pruneProjects:S}=cu({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:h,typescriptProjectShardContext:s,lastRefresh:f});return y.scipCompanion=g?"deferred":"current",lu(e.paths.outputDb,S),Qi(e.tempPaths.tempMetaPath,y),Ha({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:d.mode==="incremental"&&d.scipCompanion==="deferred",publication:d.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:d.converterDurationMs,affectedDocumentCount:a?.affectedFiles.length,changedDocumentCount:d.changedDocumentPaths.length,producerDurationMs:a?.timings.serviceMs,materializationDurationMs:a?.durationMs,patchDurationMs:d.patchDurationMs,scipCompanion:d.scipCompanion,...d.scipCompanion==="deferred"&&a?{typescriptOverlayGeneration:a.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:d.converterDurationMs,scipCompanion:"current",...d.fallbackReason?{fallbackReason:d.fallbackReason}:{}}}),Za(_(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[a.nextFragmentGeneration]:[]),au(e.paths.outputDb,m,e.onStatus),f}function wv(e,t,n,r,i,o){let s=zi(e.paths.metaPath),a=null;try{fr(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(p){a=Ol("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}pt(ut(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),a??=Ri({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:s,currentSnapshot:e.fingerprint,refreshResult:"reused"});let c=yr({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=cu({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return lu(e.paths.outputDb,d),Qi(e.paths.metaPath,l),Wa(e.paths.outputDb,e.paths.metaPath),au(e.paths.outputDb,a,e.onStatus),c}function zi(e){return Xo(sn(e)?.fingerprint)}function au(e,t,n){try{ql(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function cu(e){let t=$v({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:3,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function $v(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=sn(e.metaPath)?.typescriptProjectShards;return{field:t,pruneProjects:t?Object.keys(t):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function lu(e,t){let n=fu(e);if(t===null){Ge(n,{recursive:!0,force:!0});return}let r;try{r=ou(n)}catch{return}for(let i of Cv(r,t))Ge(ee(n,i),{force:!0})}function Cv(e,t){let n=new Set(t.map(r=>`${ji(r)}.scip`));return e.filter(r=>!n.has(r))}function eu(e,t){for(let n of t){let r=Ki(e,n.language);mr(_(r),{recursive:!0}),n.scipPath!==r&&fr(n.scipPath,r)}}async function Pv(e,t){if(!Kn()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
333
+ `).get();return{version:3,tsconfig:n,files:Cn(t),db:r}}function _S(e){let t=Jd();return{projectRoot:e.projectRoot,context:Nd(e.projectRoot,e.configPath),symbolLookup:Md(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function BS(e){let t=[],n=jt(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=qS(e,i);t.push(...o.occurrences),ur(n,o)}return{occurrences:t,...n}}function qS(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Kd(e.projectRoot,t,"missing-source-file");let r=e.context.language.scripts.get(t.fileName),i=r?.generated?.languagePlugin.typescript?.getServiceScript(r.generated.root)?.code;if(!r||!i)return Kd(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),s=He(e.projectRoot,t.fileName),a=[...Wd(n.text)],c={tokens:a.filter(l=>l.start>=t.startOffset&&l.start<t.endOffset),tokenByStart:new Map(a.map(l=>[l.start,l])),tokenTextCounts:KS(a),processedStarts:new Set};return VS({...e,fileName:t.fileName,sourceInfo:n,sourceFile:s,map:o,tokenContext:c})}function VS(e){let t=[],n=jt();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||HS(e.sourceInfo.text,r.start))continue;let i=Gd(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!Ud(e.projectRoot,d.fileName));if(!s){Wi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let a=He(e.projectRoot,s.fileName),c=WS(e.sourceFile,r.text,a);if(c){Wi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let l=qd(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(l===null){Wi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}Yd(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a,l),e.tokenContext.processedStarts.add(r.start),zS(t,e,r,i,a,l)}return{occurrences:t,...n}}function HS(e,t){let n=e.lastIndexOf(`
334
+ `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function WS(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Kd(e,t,n){let r=jt();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:He(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Wi(e,t,n,r,i,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(a=>a.reason===o&&a.sourceFile===r).length>=2)return;let s=t.positionAt(n,i.start);e.skippedReferenceSamples.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,token:i.text,reason:o})}function Gi(e,t){let n=new Map;for(let o of e){let s=n.get(o.sourceFile)??[];s.push(o),n.set(o.sourceFile,s)}let r=[...n.keys()].sort(),i=[];for(let o=0;i.length<t;o++){let s=!1;for(let a of r){let c=n.get(a)?.[o];if(c&&(i.push(c),s=!0,i.length===t))break}if(!s)break}return i}function GS(e,t){let n=Gi(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),r=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),i=Gi(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function US(e,t){let n=[...new Set(e.map(i=>i.reason))].sort(),r=[];for(let[i,o]of n.entries()){let s=n.length-i,a=Math.ceil((t-r.length)/s);r.push(...Gi(e.filter(c=>c.reason===o),a))}return r.slice(0,t)}function JS(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return GS(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function zS(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of QS(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(s))continue;let a=t.tokenContext.tokenByStart.get(s);a&&(Yd(e,t.sourceReader,t.sourceInfo,t.sourceFile,a,i,o),t.tokenContext.processedStarts.add(s))}}function Yd(e,t,n,r,i,o,s){let a=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+i.text.length,sourceToken:i.text,definitionFile:o,symbolId:s})}function KS(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function QS(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 d=YS(r,l.textSpan.start,o,i.text);d!==null&&a.push(d)}return a}function YS(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Hi(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function At(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=cv(e),s=Date.now();mr(_(o.outputScip),{recursive:!0}),mr(_(o.outputDb),{recursive:!0});let a=e.languages??rt(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=Mt("reindex.fingerprint",()=>es(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:a.length}),l,d;if(e.skipIfUnchanged!==!1&&!rc(t,o.outputDb)&&Xd(o.outputScip)===Xd(ee(_(o.outputDb),"index.scip"))){let g=nt(t);if(l=g?An(g,c):void 0,l){let h=Ln(l);if(h){if(!av(o,c))try{Gr({snapshot:l,manifest:h,targetCacheDir:_(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${l.generationId.slice(0,12)}`)}catch(y){r(`Shared generation attach failed; continuing locally: ${nn(y)}`)}}else{let y=await sc(l);if(y.kind==="owner")d=y.release;else if(y.kind==="generation-ready"){let S=Ln(l);if(S)try{Gr({snapshot:l,manifest:S,targetCacheDir:_(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${l.generationId.slice(0,12)} after waiting`)}catch(v){r(`Shared generation attach failed after waiting; continuing locally: ${nn(v)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=Ga(ee(_(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!p)throw d?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${_(o.outputDb)}.`);let m;try{m=await _t("reindex.lock",()=>Fv(ee(_(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:a.length})}catch(g){throw p.release(),d?.(),g}let f=null;try{let g=pv(_(o.outputDb));g.removed>0&&r(`Removed ${g.removed} abandoned reindex workspace(s)`);for(let R of g.errors)r(`Could not remove abandoned reindex workspace: ${R}`);let h=null,y=Mt("reindex.reuse-check",()=>(h=lv({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r}),h),()=>({languages:a.length,reused:h!==null}));if(y)return Zd({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),Ci(o.outputDb,y),y;await _t("reindex.scip-cli-ready",()=>Pv(i,r));let S=uv(o);f=S.runDir;let v,k=await _t("reindex.fresh",async()=>(v=await mv({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:S,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),v),()=>({languages:a.length,reused:v?.reused,skipped:v?.skipped.length}));return Zd({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),Ci(o.outputDb,k),k}catch(g){let h=yr({trigger:e.trigger,result:"failed",start:s,error:g instanceof Error?g.message:String(g)});throw hu(o.metaPath,h),Zl(o.outputDb,h),g}finally{f&&Ge(f,{recursive:!0,force:!0}),m(),p.release(),d?.()}}function Zd(e){if(e.snapshot){if(Ln(e.snapshot)){Ur(e.snapshot,_(e.paths.outputDb),"local-fresh");return}try{let t=nt(e.projectRoot),n=t?An(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}oc({snapshot:e.snapshot,sourceCacheDir:_(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=nt(e.projectRoot);return(r?An(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),Ur(e.snapshot,_(e.paths.outputDb),"built"),e.onStatus(`Published shared generation ${e.snapshot.generationId.slice(0,12)}`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${nn(t)}`)}}}function av(e,t){if(!Re(e.outputScip)||!Re(e.outputDb)||!gu(e.metaPath,t))return!1;let n=it(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function nn(e){return e instanceof Error?e.message:String(e)}function cv(e){let t=e.outputScip??ee(e.projectRoot,"index.scip"),n=e.outputDb??ee(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:ee(_(n),"meta.json")}}function lv(e){let t=it(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!Re(e.paths.outputScip)||!Re(e.paths.outputDb)||!gu(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;pt(ut(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=yr({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return hu(e.paths.metaPath,r),e.onStatus(`Index unchanged; reused existing SQLite index in ${(n/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:n,reused:!0,skipped:[],lastRefresh:r,shards:dv(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function dv(e,t,n,r){let i=mu(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:tn(i[o]),outputBytes:rn(Ki(e.outputDb,o)),durationMs:0}))}function uv(e){let t=tv(ee(_(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:ee(t,pr(e.outputScip)),tempOutputDb:ee(t,pr(e.outputDb)),tempMetaPath:ee(t,pr(e.metaPath))}}function pv(e){let t=[],n;try{n=ou(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[nn(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{Ge(ee(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${nn(o)}`)}return{removed:r,errors:t}}async function mv(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await _t("reindex.language-indexers",async()=>(n=await gv(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:s,languageFingerprints:a,shards:c,typescriptProjectShardContext:l,incrementalTypeScript:d}=r;if(s.length>0&&e.onStatus(`Reused ${s.length} cached language shard(s): ${s.join(", ")}`),fv({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:s})){let f=Mt("reindex.publish",()=>wv(e,i,o,s,a,l),{mode:"metadata-only",languages:i.length,reused:s.length}),g=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(h=>h.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:f,shards:c}}let p=Mt("reindex.publish",()=>kv(e,t,i,o,s,a,l,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:s.length,skipped:o.length}),m=p.durationMs;return e.onStatus(`Done in ${(m/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:m,reused:!1,skipped:o,lastRefresh:p,shards:c}}function fv(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!Re(e.run.paths.outputScip)||!Re(e.run.paths.outputDb))return!1;let t=it(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(i=>i.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(i=>n.has(i)&&r.has(i))}async function gv(e,t){let n=vv({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),r=[],i=new Set;for(let[F,Z]of n)Z.reused&&(r.push({language:F,scipPath:Z.scipPath}),i.add(F));for(let F of i)e.onStatus(`Reusing cached ${F} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),s=it(e.paths.outputDb,e.paths.metaPath),a=sn(e.paths.metaPath),c=s.state==="legacy"||s.state==="current",l=a?.scipCompanion!=="deferred"&&(s.state!=="current"||s.generation.publication?.scipCompanion!=="deferred"),d=o&&!o.reused&&c?Cd({projectRoot:e.projectRoot,cacheDir:_(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:on(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:on(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:zi(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(d?["typescript"]:[]),m=d?void 0:hv(e,n),{preparedRuns:f,skippedLanguages:g,languageOutputScipPaths:h}=Tv({languages:e.languages.filter(F=>!i.has(F)&&!p.has(F)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:m?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),y=m?f.filter(F=>F.language!=="typescript"||m.missedProjectIds.has(F.id)):f,S=await Id(y,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),v=[];if(m){bv(e.paths.outputDb,S);let F=h.typescript??e.tempPaths.tempOutputScip;v=Sv({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:F,reusedProjects:m.reusedProjects})}let k=[...S,...v],{indexedOutputs:R}=Ev(k,g),D=d?[{language:"typescript",scipPath:d.scipPath}]:[],B=[...r,...D,...R];jv(B,g,e.languages,e.opts.allowPartial,e.onStatus);let z=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:rn(d.scipPath)??void 0}]:[],T=xv(n,[...S,...z],m?{outputDb:e.paths.outputDb,classification:m.classification}:void 0);return{indexedOutputs:B,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Rv(n,e.languages),shards:T,typescriptProjectShardContext:m?{projects:m.allProjects,fingerprints:m.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function hv(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=en(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=od(e.projectRoot,r),o=nd(n.fingerprint.files,r),s=rd(r,i),a=id(r,o,s),c=sn(e.paths.metaPath),d=yv(c,a,g=>Re(hr(e.paths.outputDb,g))),p=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),m=new Set(p),f=new Set(r.filter(g=>!m.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:a,classification:d,reusedProjects:p,missedProjectIds:f}}function yv(e,t,n){let r=new Map;for(let i of Object.keys(t)){let o=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let s=e.typescriptProjectShards?.[i];if(!s){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(We(s)!==We(o)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}r.set(i,{reused:!0,fingerprint:o})}return r}function bv(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=hr(e,r);mr(_(i),{recursive:!0}),fr(n.scipPath,i)}}function Sv(e){return e.reusedProjects.map((t,n)=>{let r=hr(e.outputDb,t),i=on(e.tempOutputScip,"typescript-project-cached",n);return fr(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:rn(i)??void 0}})}function vv(e){let t=sn(e.paths.metaPath),n=mu(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Ki(e.paths.outputDb,i),s=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:s,scipPath:o});continue}if(t.version!==3){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:o});continue}if(i==="typescript"&&t.scipCompanion==="deferred"){r.set(i,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:s,scipPath:o});continue}if(!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:s,scipPath:o});continue}let a=t.languageFingerprints[i];if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:s,scipPath:o});continue}if(!Re(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:o});continue}if(We(a)!==We(s)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:s,scipPath:o});continue}r.set(i,{reused:!0,fingerprint:s,scipPath:o})}return r}function xv(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:tn(o.fingerprint),outputBytes:rn(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),s=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,a=s?n.classification.get(s):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:a?.reason??o?.reason??i.skipped?.reason,fingerprint:a?tn(a.fingerprint):o?tn(o.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,o]of n.classification)o.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:tn(o.fingerprint),outputBytes:rn(hr(n.outputDb,i)),durationMs:0});return r}function tn(e){return ZS("sha256").update(We(e)).digest("hex").slice(0,16)}function rn(e){try{return rv(e).size}catch{return null}}function Rv(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function kv(e,t,n,r,i,o,s,a){let c=!a||a.completeScipUpdated,l=!1;c&&(eu(e.paths.outputDb,n),l=tu(n,e.tempPaths.tempOutputScip,e.onStatus));let d=Av({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:a,completeScipAvailable:c,completeScipSanitized:l,materializeFullFallback:()=>{if(!a||a.completeScipUpdated)return l;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Pd({cacheDir:_(e.paths.outputDb),generationIdentity:a.nextFragmentGeneration,baseShardPath:a.scipPath,candidateShardPath:a.candidateScipPath});let v=n.map(k=>k.language==="typescript"?{language:k.language,scipPath:a.candidateScipPath}:k);return eu(e.paths.outputDb,v),l=tu(v,e.tempPaths.tempOutputScip,e.onStatus),l}});if(pt(ut(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&a){let v=null,k=null;try{v=new Oe({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),k=new Oe({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let R=ps(v,e.fingerprint,a.referenceFragmentsByFile,k);e.onStatus(`Cached exact TypeScript reference fragments for ${R} affected document(s).`)}catch(R){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${R instanceof Error?R.message:String(R)}.`)}finally{v?.close(),k?.close()}}let p=zi(e.paths.metaPath),m=d.mode==="incremental"&&a?Dv(a,d.changedDocumentPaths):Ri({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:p,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),f=yr({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(v=>v.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",h={...o};g&&delete h.typescript;let{metadata:y,pruneProjects:S}=cu({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:h,typescriptProjectShardContext:s,lastRefresh:f});return y.scipCompanion=g?"deferred":"current",lu(e.paths.outputDb,S),Qi(e.tempPaths.tempMetaPath,y),Ha({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:d.mode==="incremental"&&d.scipCompanion==="deferred",publication:d.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:d.converterDurationMs,affectedDocumentCount:a?.affectedFiles.length,changedDocumentCount:d.changedDocumentPaths.length,producerDurationMs:a?.timings.serviceMs,materializationDurationMs:a?.durationMs,patchDurationMs:d.patchDurationMs,scipCompanion:d.scipCompanion,...d.scipCompanion==="deferred"&&a?{typescriptOverlayGeneration:a.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:d.converterDurationMs,scipCompanion:"current",...d.fallbackReason?{fallbackReason:d.fallbackReason}:{}}}),Za(_(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[a.nextFragmentGeneration]:[]),au(e.paths.outputDb,m,e.onStatus),f}function wv(e,t,n,r,i,o){let s=zi(e.paths.metaPath),a=null;try{fr(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(p){a=Ol("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}pt(ut(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),a??=Ri({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:s,currentSnapshot:e.fingerprint,refreshResult:"reused"});let c=yr({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=cu({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return lu(e.paths.outputDb,d),Qi(e.paths.metaPath,l),Wa(e.paths.outputDb,e.paths.metaPath),au(e.paths.outputDb,a,e.onStatus),c}function zi(e){return Xo(sn(e)?.fingerprint)}function au(e,t,n){try{Bl(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function cu(e){let t=$v({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:3,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function $v(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=sn(e.metaPath)?.typescriptProjectShards;return{field:t,pruneProjects:t?Object.keys(t):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function lu(e,t){let n=fu(e);if(t===null){Ge(n,{recursive:!0,force:!0});return}let r;try{r=ou(n)}catch{return}for(let i of Cv(r,t))Ge(ee(n,i),{force:!0})}function Cv(e,t){let n=new Set(t.map(r=>`${ji(r)}.scip`));return e.filter(r=>!n.has(r))}function eu(e,t){for(let n of t){let r=Ki(e,n.language);mr(_(r),{recursive:!0}),n.scipPath!==r&&fr(n.scipPath,r)}}async function Pv(e,t){if(!Kn()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
335
335
  Install from: https://github.com/sourcegraph/scip/releases`);if(sv()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall with optional dependencies enabled, run 'npm install -g scip-query-scip-windows', or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(t("scip CLI not found on PATH. Attempting auto-install..."),!Rl(t))throw new Error(`The scip CLI is required but could not be installed.
336
336
  Install manually from: https://github.com/sourcegraph/scip/releases`)}}function Tv(e){let t=[],n=[],r=e.languages.map((o,s)=>({language:o,scipPath:e.languages.length>1?on(e.tempOutputScip,o,s):e.tempOutputScip})),i=Object.fromEntries(r.map(({language:o,scipPath:s})=>[o,s]));for(let{language:o,scipPath:s}of r){let a=Iv({...e,language:o,scipPath:s});for(let c of a)"skipped"in c?du(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function Iv(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Ji({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??en(e.projectRoot,e.typescriptProjects);return t.length===0?[Ji({...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)=>Ji({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:on(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Ji(e){let t=st(e.language),n=Rn(t),r=zo(t,e.projectRoot);if(!r&&!Jo(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...`),!dr(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??kn(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,configPath:e.language==="clojure"?e.clojureConfigPath:void 0});return{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:i,binary:o,args:s,env:Ko(t,e.env,i)}}}function Ev(e,t){let n=new Map;for(let i of e)if(i.skipped)du(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)tc(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&su(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function du(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 jv(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
337
337
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
338
338
  `+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.
339
339
  `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
340
- `))}function tu(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=nc(e.map(o=>o.scipPath),t);return pu(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&su(e[0].scipPath,t);return!1}function Av(e){let t;if(Lv(e)){let i=ee(e.run.tempPaths.runDir,"typescript-affected.db");try{uu(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();nu(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let s=Ul({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles});return e.run.onStatus(`Patched ${s.affectedDocumentCount} SQLite document(s) in ${(s.durationMs/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:s.changedDocumentPaths,patchDurationMs:s.durationMs,converterDurationMs:performance.now()-o,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(o){t=o instanceof Error?o.message:String(o),Ge(i,{force:!0}),Ge(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}}let n=e.completeScipSanitized;e.completeScipAvailable||(n=e.materializeFullFallback());let r=performance.now();return nu(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function Lv(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!Re(e.run.paths.outputDb)||!Re(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function Dv(e,t){let n=Date.now(),r=[...t].sort(),i=new Set(r),o={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(s=>!i.has(s)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:Date.now()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:xi(e.plan,o,e.projectFileCount)}}function nu(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!Re(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||uu(e,r);let o=Kn();if(!o)throw new Error("scip CLI is not available");XS(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Failed to convert SCIP index to SQLite: ${s}`,{cause:o})}}function uu(e,t){let n=ec(e);pu(n,t)}function pu(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function on(e,t,n){let r=ov(e)||".scip",i=pr(e,r);return ee(_(e),`${i}.${n+1}.${t}${r}`)}async function Fv(e,t){for(let n=0;n<2;n++){let r=Ov(e,t);if(r)return r;let i=Nv(e);if(i&&Mv(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await qv(i.pid))throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${_(e)}; refusing to steal an active lock.`);Ge(e,{force:!0});continue}if(i&&!bt(i.pid)){Ge(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${_(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${_(e)}.`)}function Ov(e,t){let n;try{n=nv(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 iv(n,JSON.stringify(r)+`
341
- `),()=>{try{ev(n)}finally{Ge(e,{force:!0})}}}function Nv(e){try{let t=JSON.parse(gr(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:_(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function Mv(e,t){return e?.kind==="manual-cli"&&_v(t?.trigger)}function _v(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function qv(e){return ru(e,"SIGTERM"),await iu(e,2e3)?!0:(ru(e,"SIGKILL"),iu(e,1e3))}function ru(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function iu(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!bt(e))return!0;await Bv(50)}return!bt(e)}function Bv(e){return new Promise(t=>setTimeout(t,e))}function mu(e,t,n){return Object.fromEntries(t.map(r=>{let i=st(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Zo(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},s=r==="clojure"?Vv(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Hv(n),...o,clojureConfigPath:s,files:Cn(e,{language:r,markerFiles:i})}]}))}function Vv(e){return e?.trim()||void 0}function Hv(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Ki(e,t){return ee(_(e),"language-indexes",`${t}.scip`)}function fu(e){return ee(_(e),"language-indexes","typescript-projects")}function hr(e,t){return ee(fu(e),`${ji(t)}.scip`)}function sn(e){try{return JSON.parse(gr(e,"utf-8"))}catch{return null}}function gu(e,t){try{let n=JSON.parse(gr(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&We(n.fingerprint)===We(t)&&We([...n.indexedLanguages??[]].sort())===We(t.languages)}catch{return!1}}function Qi(e,t){St(e,t,{spacing:2,trailingNewline:!0})}function hu(e,t){try{let n=JSON.parse(gr(e,"utf-8"));if(n.version!==2&&n.version!==3)return;Qi(e,{...n,lastRefresh:t})}catch{}}function yr(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 We(e){return JSON.stringify(e)}var Yi=864e5;function yu(e,t={}){let r=[...t.check?e.filter(l=>l.check===t.check):[...e]].sort((l,d)=>l.ts-d.ts),i=new Map;for(let l of r){let d=`${l.check}\0${l.findingId}`,p=i.get(d);p||(p={check:l.check,findingId:l.findingId,caughtAt:l.ts,events:[]},i.set(d,p)),p.events.push(l)}let o=[...i.values()].filter(l=>t.sinceMs===void 0||l.caughtAt>=t.sinceMs),s=Wv(r),a=new Map;for(let l of o){let d=a.get(l.check)??[];d.push(l),a.set(l.check,d)}let c=[];for(let[l,d]of a){let p=0,m=0,f=0,g=0,h=0,y=0,S=[];for(let k of d){f+=k.events.filter(q=>q.event==="reopened").length;let R=k.events[k.events.length-1],D=`${k.check}\0${k.findingId}`;if(R.event==="resolved"&&s.has(D))g+=1;else if(R.event==="resolved"){let q=Gt(k.events.slice(0,-1)),z=q?.comparisonBaseCommit??q?.commit,T=R.comparisonBaseCommit??R.commit;z&&(T===z||R.verifiedAgainstCommit===z)?(p+=1,S.push((R.ts-k.caughtAt)/Yi)):h+=1}else R.event==="suppressed"?m+=1:y+=1}let v=p+m;c.push({check:l,caught:d.length,fixed:p,suppressed:m,reopened:f,moved:g,unverified:h,open:y,precision:v>0?p/v:null,medianDaysToFix:S.length>0?Gv(S):null})}return{totalEvents:r.length,windowStart:t.sinceMs??null,checks:c.sort((l,d)=>l.check.localeCompare(d.check))}}function Wv(e){let t=new Map;for(let i of e){if(i.event!=="caught"||!i.commit||!i.symbol)continue;let o=t.get(i.commit)??[];o.push(i),t.set(i.commit,o)}let n=new Map;for(let i of e)i.event==="caught"&&i.symbol&&n.set(`${i.check}\0${i.findingId}`,i.symbol);let r=new Set;for(let i of e){if(i.event!=="resolved"||!i.commit)continue;let o=`${i.check}\0${i.findingId}`,s=i.symbol??n.get(o);if(!s)continue;(t.get(i.commit)??[]).some(c=>c.check===i.check&&c.symbol===s&&c.findingId!==i.findingId)&&r.add(o)}return r}function bu(e,t){let n=/^(\d+)([dw])$/.exec(e.trim());if(n){let i=Number(n[1]),o=n[2]==="w"?7*Yi:Yi;return t-i*o}let r=Date.parse(e);return Number.isNaN(r)?null:r}function Gv(e){let t=[...e].sort((r,i)=>r-i),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}import{fork as Uv}from"child_process";import{statSync as Jv}from"fs";import{isAbsolute as zv,join as Kv,relative as Qv}from"path";import{watch as Yv}from"chokidar";import Xv from"ignore";var br=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onRefreshSuppressed;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Ce(t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onRefreshSuppressed=t.onRefreshSuppressed??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=Rt(t.projectRoot),this.extraIgnore=Xv(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(t,n={}){if(!n.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(t);return}this.pendingTrigger=Su(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}startSourceWatcher(t=!1){let n=Yv(this.projectRoot,{ignoreInitial:!0,ignored:(r,i)=>this.isIgnoredWatchPath(r,i?.isDirectory()??!1),usePolling:t,...t?{interval:500,binaryInterval:1e3}:{}});n.on("all",(r,i)=>{this.stopped||this.handleFileChange(i)}),n.on("error",r=>this.handleSourceWatcherError(n,r,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,r){if(r||this.sourcePollingFallbackStarted||!Zv(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==t),t.close();try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(t,n){let r=this.relativeWatchPath(t);if(!r)return!1;let i=n?`${r}/`:r;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(t){let n=this.relativeWatchPath(t);!n||n===".."||n.startsWith("../")||n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||n.endsWith("index.db")||n.endsWith("index.scip")||n.endsWith("index.db.tmp")||n.endsWith(ir)||n.endsWith(`${ir}.previous`)||this.scheduleReindex({kind:"watch-source",detail:n})}relativeWatchPath(t){let n=zv(t)?t:Kv(this.projectRoot,t);return Qv(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=Su(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=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now();let o=!1;try{o=this.onReindexComplete(i)===!0}catch(s){this.onError(s instanceof Error?s:new Error(String(s)))}if(this.dirty&&!this.stopped){if(o){let a=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(a),this.setStatus({state:"idle"});return}let s=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:s,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=me(this.projectRoot),s=Object.keys(o).length>0?o:this.config,a=Fe(this.projectRoot,s),c=s.indexer?.typescript,l=s.indexer?.clojure,d=Uv(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:a.indexPath,SCIP_REINDEX_OUTPUT_DB:a.dbPath,SCIP_REINDEX_LANGUAGES:(s.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(s.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:t.kind,SCIP_REINDEX_TRIGGER_DETAIL:t.detail??""},stdio:"pipe"});d.on("exit",p=>{p===0?n(Date.now()-i):r(new Error(`Reindex worker exited with code ${p}`))}),d.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=Vt(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n=is(this.projectRoot,t),r={head:Vt(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:n};try{let i=Jv(n);r.indexMtimeMs=i.mtimeMs,r.indexSize=i.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Su(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}function Zv(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}import{existsSync as xx}from"fs";import{existsSync as xu,mkdirSync as Ru,readFileSync as ku,writeFileSync as wu}from"fs";import{homedir as ex}from"os";import{dirname as $u,isAbsolute as tx,join as Xi,relative as vu,resolve as nx}from"path";function Cu(e,t={}){let n=t.dossierDir?nx(e.projectRoot,t.dossierDir):Xi(e.projectRoot,"docs","scip-query"),r={markdownPath:Xi(n,"health-dossier.md"),jsonPath:Xi(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},i=ux({...e,generatedAt:new Date().toISOString(),healthDossier:r},e.projectRoot);try{return cx(r.markdownPath,rx(i),r),lx(r.jsonPath,i,r),r}catch(o){return{...r,status:"failed",error:o instanceof Error?o.message:String(o)}}}function rx(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${eo(e.health)}`,"","## Items That Need Attention","",...ix(e),"","## Blocked Or Unavailable Checks","",...ox(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","",...sx(e),"","## JSON","",`Machine-readable report: \`${ax(e)}\``,""].join(`
340
+ `))}function tu(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=nc(e.map(o=>o.scipPath),t);return pu(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&su(e[0].scipPath,t);return!1}function Av(e){let t;if(Lv(e)){let i=ee(e.run.tempPaths.runDir,"typescript-affected.db");try{uu(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();nu(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let s=Ul({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles});return e.run.onStatus(`Patched ${s.affectedDocumentCount} SQLite document(s) in ${(s.durationMs/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:s.changedDocumentPaths,patchDurationMs:s.durationMs,converterDurationMs:performance.now()-o,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(o){t=o instanceof Error?o.message:String(o),Ge(i,{force:!0}),Ge(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}}let n=e.completeScipSanitized;e.completeScipAvailable||(n=e.materializeFullFallback());let r=performance.now();return nu(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function Lv(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!Re(e.run.paths.outputDb)||!Re(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function Dv(e,t){let n=Date.now(),r=[...t].sort(),i=new Set(r),o={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(s=>!i.has(s)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:Date.now()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:xi(e.plan,o,e.projectFileCount)}}function nu(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!Re(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||uu(e,r);let o=Kn();if(!o)throw new Error("scip CLI is not available");XS(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Failed to convert SCIP index to SQLite: ${s}`,{cause:o})}}function uu(e,t){let n=ec(e);pu(n,t)}function pu(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function on(e,t,n){let r=ov(e)||".scip",i=pr(e,r);return ee(_(e),`${i}.${n+1}.${t}${r}`)}async function Fv(e,t){for(let n=0;n<2;n++){let r=Ov(e,t);if(r)return r;let i=Nv(e);if(i&&Mv(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await Bv(i.pid))throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${_(e)}; refusing to steal an active lock.`);Ge(e,{force:!0});continue}if(i&&!bt(i.pid)){Ge(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${_(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${_(e)}.`)}function Ov(e,t){let n;try{n=nv(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 iv(n,JSON.stringify(r)+`
341
+ `),()=>{try{ev(n)}finally{Ge(e,{force:!0})}}}function Nv(e){try{let t=JSON.parse(gr(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:_(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function Mv(e,t){return e?.kind==="manual-cli"&&_v(t?.trigger)}function _v(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function Bv(e){return ru(e,"SIGTERM"),await iu(e,2e3)?!0:(ru(e,"SIGKILL"),iu(e,1e3))}function ru(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function iu(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!bt(e))return!0;await qv(50)}return!bt(e)}function qv(e){return new Promise(t=>setTimeout(t,e))}function mu(e,t,n){return Object.fromEntries(t.map(r=>{let i=st(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Zo(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},s=r==="clojure"?Vv(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Hv(n),...o,clojureConfigPath:s,files:Cn(e,{language:r,markerFiles:i})}]}))}function Vv(e){return e?.trim()||void 0}function Hv(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Ki(e,t){return ee(_(e),"language-indexes",`${t}.scip`)}function fu(e){return ee(_(e),"language-indexes","typescript-projects")}function hr(e,t){return ee(fu(e),`${ji(t)}.scip`)}function sn(e){try{return JSON.parse(gr(e,"utf-8"))}catch{return null}}function gu(e,t){try{let n=JSON.parse(gr(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&We(n.fingerprint)===We(t)&&We([...n.indexedLanguages??[]].sort())===We(t.languages)}catch{return!1}}function Qi(e,t){St(e,t,{spacing:2,trailingNewline:!0})}function hu(e,t){try{let n=JSON.parse(gr(e,"utf-8"));if(n.version!==2&&n.version!==3)return;Qi(e,{...n,lastRefresh:t})}catch{}}function yr(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 We(e){return JSON.stringify(e)}var Yi=864e5;function yu(e,t={}){let r=[...t.check?e.filter(l=>l.check===t.check):[...e]].sort((l,d)=>l.ts-d.ts),i=new Map;for(let l of r){let d=`${l.check}\0${l.findingId}`,p=i.get(d);p||(p={check:l.check,findingId:l.findingId,caughtAt:l.ts,events:[]},i.set(d,p)),p.events.push(l)}let o=[...i.values()].filter(l=>t.sinceMs===void 0||l.caughtAt>=t.sinceMs),s=Wv(r),a=new Map;for(let l of o){let d=a.get(l.check)??[];d.push(l),a.set(l.check,d)}let c=[];for(let[l,d]of a){let p=0,m=0,f=0,g=0,h=0,y=0,S=[];for(let k of d){f+=k.events.filter(B=>B.event==="reopened").length;let R=k.events[k.events.length-1],D=`${k.check}\0${k.findingId}`;if(R.event==="resolved"&&s.has(D))g+=1;else if(R.event==="resolved"){let B=Gt(k.events.slice(0,-1)),z=B?.comparisonBaseCommit??B?.commit,T=R.comparisonBaseCommit??R.commit;z&&(T===z||R.verifiedAgainstCommit===z)?(p+=1,S.push((R.ts-k.caughtAt)/Yi)):h+=1}else R.event==="suppressed"?m+=1:y+=1}let v=p+m;c.push({check:l,caught:d.length,fixed:p,suppressed:m,reopened:f,moved:g,unverified:h,open:y,precision:v>0?p/v:null,medianDaysToFix:S.length>0?Gv(S):null})}return{totalEvents:r.length,windowStart:t.sinceMs??null,checks:c.sort((l,d)=>l.check.localeCompare(d.check))}}function Wv(e){let t=new Map;for(let i of e){if(i.event!=="caught"||!i.commit||!i.symbol)continue;let o=t.get(i.commit)??[];o.push(i),t.set(i.commit,o)}let n=new Map;for(let i of e)i.event==="caught"&&i.symbol&&n.set(`${i.check}\0${i.findingId}`,i.symbol);let r=new Set;for(let i of e){if(i.event!=="resolved"||!i.commit)continue;let o=`${i.check}\0${i.findingId}`,s=i.symbol??n.get(o);if(!s)continue;(t.get(i.commit)??[]).some(c=>c.check===i.check&&c.symbol===s&&c.findingId!==i.findingId)&&r.add(o)}return r}function bu(e,t){let n=/^(\d+)([dw])$/.exec(e.trim());if(n){let i=Number(n[1]),o=n[2]==="w"?7*Yi:Yi;return t-i*o}let r=Date.parse(e);return Number.isNaN(r)?null:r}function Gv(e){let t=[...e].sort((r,i)=>r-i),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}import{fork as Uv}from"child_process";import{statSync as Jv}from"fs";import{isAbsolute as zv,join as Kv,relative as Qv}from"path";import{watch as Yv}from"chokidar";import Xv from"ignore";var br=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onRefreshSuppressed;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Ce(t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=t.config.indexer?.typescript?.projectMode,this.typescriptProjects=t.config.indexer?.typescript?.projects,this.clojureConfigPath=t.config.indexer?.clojure?.configPath,this.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onRefreshSuppressed=t.onRefreshSuppressed??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=Rt(t.projectRoot),this.extraIgnore=Xv(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(t,n={}){if(!n.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(t);return}this.pendingTrigger=Su(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}startSourceWatcher(t=!1){let n=Yv(this.projectRoot,{ignoreInitial:!0,ignored:(r,i)=>this.isIgnoredWatchPath(r,i?.isDirectory()??!1),usePolling:t,...t?{interval:500,binaryInterval:1e3}:{}});n.on("all",(r,i)=>{this.stopped||this.handleFileChange(i)}),n.on("error",r=>this.handleSourceWatcherError(n,r,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,r){if(r||this.sourcePollingFallbackStarted||!Zv(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==t),t.close();try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(t,n){let r=this.relativeWatchPath(t);if(!r)return!1;let i=n?`${r}/`:r;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(t){let n=this.relativeWatchPath(t);!n||n===".."||n.startsWith("../")||n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||n.endsWith("index.db")||n.endsWith("index.scip")||n.endsWith("index.db.tmp")||n.endsWith(ir)||n.endsWith(`${ir}.previous`)||this.scheduleReindex({kind:"watch-source",detail:n})}relativeWatchPath(t){let n=zv(t)?t:Kv(this.projectRoot,t);return Qv(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=Su(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=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now();let o=!1;try{o=this.onReindexComplete(i)===!0}catch(s){this.onError(s instanceof Error?s:new Error(String(s)))}if(this.dirty&&!this.stopped){if(o){let a=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(a),this.setStatus({state:"idle"});return}let s=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:s,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=me(this.projectRoot),s=Object.keys(o).length>0?o:this.config,a=Fe(this.projectRoot,s),c=s.indexer?.typescript,l=s.indexer?.clojure,d=Uv(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:a.indexPath,SCIP_REINDEX_OUTPUT_DB:a.dbPath,SCIP_REINDEX_LANGUAGES:(s.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(s.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:t.kind,SCIP_REINDEX_TRIGGER_DETAIL:t.detail??""},stdio:"pipe"});d.on("exit",p=>{p===0?n(Date.now()-i):r(new Error(`Reindex worker exited with code ${p}`))}),d.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=Vt(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n=is(this.projectRoot,t),r={head:Vt(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:n};try{let i=Jv(n);r.indexMtimeMs=i.mtimeMs,r.indexSize=i.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Su(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}function Zv(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}import{existsSync as xx}from"fs";import{existsSync as xu,mkdirSync as Ru,readFileSync as ku,writeFileSync as wu}from"fs";import{homedir as ex}from"os";import{dirname as $u,isAbsolute as tx,join as Xi,relative as vu,resolve as nx}from"path";function Cu(e,t={}){let n=t.dossierDir?nx(e.projectRoot,t.dossierDir):Xi(e.projectRoot,"docs","scip-query"),r={markdownPath:Xi(n,"health-dossier.md"),jsonPath:Xi(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},i=ux({...e,generatedAt:new Date().toISOString(),healthDossier:r},e.projectRoot);try{return cx(r.markdownPath,rx(i),r),lx(r.jsonPath,i,r),r}catch(o){return{...r,status:"failed",error:o instanceof Error?o.message:String(o)}}}function rx(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${eo(e.health)}`,"","## Items That Need Attention","",...ix(e),"","## Blocked Or Unavailable Checks","",...ox(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","",...sx(e),"","## JSON","",`Machine-readable report: \`${ax(e)}\``,""].join(`
342
342
  `)}`}function ix(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 ox(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 sx(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 eo(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function ax(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function cx(e,t,n){if(Ru($u(e),{recursive:!0}),(xu(e)?ku(e,"utf-8"):null)===t){n.unchanged.push(e);return}wu(e,t),n.written.push(e)}function lx(e,t,n){Ru($u(e),{recursive:!0});let r=`${JSON.stringify(t,null,2)}
343
- `,i=xu(e)?ku(e,"utf-8"):null;if(i&&dx(i,r)){n.unchanged.push(e);return}wu(e,r),n.written.push(e)}function dx(e,t){try{let n=JSON.parse(e),r=JSON.parse(t);return delete n.generatedAt,delete r.generatedAt,JSON.stringify(n)===JSON.stringify(r)}catch{return e===t}}function ux(e,t){return Zi(e,t)}function Zi(e,t){return typeof e=="string"?px(e,t):Array.isArray(e)?e.map(n=>Zi(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Zi(r,t)])):e}function px(e,t){if(e===t)return".";if(!tx(e))return e;let n=vu(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let r=vu(ex(),e).replace(/\\/g,"/");return r&&!r.startsWith("..")?`~/${r}`:e}return n}import{spawnSync as mx}from"child_process";import{readFileSync as Tu}from"fs";import{dirname as Pu,join as fx,resolve as gx}from"path";import{fileURLToPath as hx}from"url";var Sr={typescript:{ast:"typescript",packages:["tree-sitter-typescript"]},javascript:{ast:"javascript",packages:["tree-sitter-javascript"]},java:{ast:"java",packages:["tree-sitter-java"]},scala:{ast:"scala",packages:["tree-sitter-scala"]},kotlin:{ast:"kotlin",packages:["tree-sitter-kotlin"]},rust:{ast:"rust",packages:["tree-sitter-rust"]},python:{ast:"python",packages:["tree-sitter-python"]},ruby:{ast:"ruby",packages:["tree-sitter-ruby"]},cpp:{ast:"cpp",packages:["tree-sitter-cpp"]},c:{ast:"c",packages:["tree-sitter-c"]},csharp:{ast:"csharp",packages:["tree-sitter-c-sharp"]},php:{ast:"php",packages:["tree-sitter-php"]}};function yx(e,t){let n=new Set(["tree-sitter"]);for(let r of e)for(let i of Sr[r]?.packages??[])n.add(i);return[...n].filter(r=>t[r]).sort().map(r=>`${r}@${t[r]}`)}function to(e){return[...new Set(e.filter(t=>Sr[t]!==void 0))].sort()}function Iu(e,t={}){let n=t.runtime??vx,r=t.packageRoot??bx(),i=to(e),o=i.filter(p=>n.probe(Sr[p].ast)),s=i.filter(p=>!o.includes(p));if(s.length===0)return{supportedLanguages:i,availableBefore:o,installed:[],availableAfter:o,unavailable:[],attempted:!1};let a=Sx(r),c=yx(s,a),l=n.install(r,c);l.ok&&n.resetProbe();let d=i.filter(p=>n.probe(Sr[p].ast));return{supportedLanguages:i,availableBefore:o,installed:l.ok?c:[],availableAfter:d,unavailable:i.filter(p=>!d.includes(p)),attempted:!0,...l.error?{error:l.error}:{}}}function bx(){let e=Pu(hx(import.meta.url));for(;;){let t=fx(e,"package.json");try{if(JSON.parse(Tu(t,"utf8")).name==="scip-query")return e}catch{}let n=Pu(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function Sx(e){return JSON.parse(Tu(gx(e,"package.json"),"utf8")).optionalDependencies??{}}var vx={probe:e=>bn(e)==="ast",resetProbe:Fo,install:(e,t)=>{let n=mx(process.env.npm_execpath?process.execPath:"npm",[...process.env.npm_execpath?[process.env.npm_execpath]:[],"install","--no-save","--no-package-lock","--include=optional",...t],{cwd:e,encoding:"utf8"});return n.status===0?{ok:!0}:{ok:!1,error:(n.stderr||n.stdout||n.error?.message||"npm install failed").trim()}}};function Au(e){let t=[];e.watchEnabled||t.push({id:"enable-automatic-refresh",scope:"repository",label:"Enable automatic incremental indexing",recommended:!0,requiresConsent:!0,reason:"A demand-started project service keeps indexes current and exits after a clean idle period.",command:"scip-query setup"}),e.files.agentsMd||e.files.claudeMd?t.push({id:"update-agent-guidance",scope:"repository",label:"Update project agent guidance",recommended:!0,requiresConsent:!0,reason:"Existing AGENTS.md or CLAUDE.md guidance can be updated in place.",command:"scip-query setup-agent"}):t.push({id:"create-agent-guidance",scope:"repository",label:"Create project agent guidance",recommended:!1,requiresConsent:!0,reason:"No AGENTS.md or CLAUDE.md file exists, so setup should ask before creating one.",command:"scip-query setup-agent"}),(!e.files.codexHooks||!e.files.claudeSettings)&&t.push({id:"install-project-hooks",scope:"checkout",label:"Install project agent hooks",recommended:!0,requiresConsent:!0,reason:"Project hooks help agents check freshness and route through scip-query before editing.",command:"scip-query setup-hooks"});let n=e.readiness.indexers.filter(r=>!r.runnable);return n.length>0&&t.push({id:"install-indexers",scope:"user",label:"Install missing language indexers",recommended:!0,requiresConsent:!0,reason:`${n.length} detected language indexer(s) are not runnable.`,command:"scip-query setup"}),{actions:t}}async function Lu(e={}){let t=[],n=Me(),{projectRoot:r,paths:i,dbPath:o}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,a=e.languages?Ba(r,n.config,e.languages):null,c=a?.config??n.config,l=kt(c,{projectRoot:r}),d=l.filter(j=>j.level==="error"),p=null,m=null;if(d.length===0&&c.watch?.enabled!==s)try{p=Va(r,c,s)}catch(j){m=Lt(j)}let f=p?.config??c,g=Xt();N(t,{id:"automatic-indexing-config",label:"Automatic indexing config",status:m!==null?"failed":d.length>0||!s?"skipped":"ok",message:m??(d.length>0?"Skipped because the existing project config has validation errors.":s?p?.changed?"Enabled demand-started automatic incremental indexing for this project.":"Demand-started automatic incremental indexing is already enabled.":"Automatic incremental indexing remains explicitly disabled for this project."),...p?{details:[p.configPath]}:{}}),N(t,{id:"scip-cli",label:"scip CLI",status:g?"ok":"warn",message:g?"scip CLI is available.":"scip CLI is not available; reindex may attempt install."});let h=e.installSkills===!1?{installed:[],skipped:[],alreadyLinked:[],pruned:[]}:Zn({quiet:!0});N(t,{id:"skills",label:"Agent skills",status:e.installSkills===!1?"skipped":h.skipped.length>0?"warn":"ok",message:e.installSkills===!1?"Skipped by setup choice.":`${h.installed.length} installed, ${h.alreadyLinked.length} already linked, ${h.pruned.length} pruned, ${h.skipped.length} skipped.`,details:[...h.pruned.map(j=>`Pruned ${j}`),...h.skipped.map(j=>`Skipped ${j}`)]});let y=p?kt(f,{projectRoot:r}):l,S=y.filter(j=>j.level==="error");N(t,{id:"config",label:"Project config",status:S.length>0?"failed":y.length>0?"warn":"ok",message:y.length===0?"Config OK.":`${y.length} diagnostic(s), ${S.length} error(s).`,details:y.map(j=>`${j.level.toUpperCase()} ${j.path}: ${j.message}`)});let v=ge(r,f);N(t,{id:"readiness",label:"Indexer readiness",status:v.languages.length===0?"failed":v.indexers.some(j=>!j.runnable)?"warn":"ok",message:v.languages.length===0?"No supported project languages detected.":`Detected languages: ${v.languages.join(", ")}`,details:v.indexers.map(j=>`${j.runnable?"OK":j.installed?"WARN":"MISSING"} ${j.language}: ${j.binaryLabel}${j.note?` - ${j.note}`:""}`)});let k=e.installAstParsers===!1?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:Iu(v.languages);N(t,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers===!1?"skipped":k.unavailable.length>0?"warn":"ok",message:e.installAstParsers===!1?"Skipped by setup choice.":k.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${k.availableAfter.length}/${k.supportedLanguages.length} selected language parser(s) available${k.installed.length>0?`; installed ${k.installed.join(", ")}`:""}.`,details:[...k.unavailable.length>0?[`Unavailable: ${k.unavailable.join(", ")}`]:[],...k.error?[k.error]:[]]});let R=e.installIndexers??!0,D=R?Ax(r,v,t):[];R||N(t,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped by guided setup choice."});let q=ge(r,f),z=await Rx({projectRoot:r,paths:i,config:f,readiness:q,configHasErrors:S.length>0,steps:t,onStatus:e.onStatus}),T=z.reindexResult,F=z.freshness,Z=Ce(f),O=kx({projectRoot:r,cacheDir:i.cacheDir,watchConfig:Z,readiness:q,configHasErrors:S.length>0,reindexResult:T,postReindexFreshness:F,steps:t}),H=ge(r,f),fn=Qe(H),Ao=Pe(r,f,i);N(t,{id:"capabilities",label:"Capability matrix",status:Mx(fn),message:_x(fn)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let Lo=e.runHealth===!1?Fx(t):await Dx(i.dbPath,t),we=H.languages.includes("rust")?Pn(r,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;N(t,{id:"rust-semantic-session",label:"Rust semantic session",status:we===null?"skipped":we.valid?"ok":"failed",message:we===null?"Skipped because Rust was not detected.":`${we.transport}/${we.state} selected from ${we.source}; ${we.fallback} fallback; opt out with ${we.optOut}.`});let te=null;try{e.noHooks?N(t,{id:"project-hooks",label:"Project agent hooks",status:"skipped",message:"Skipped by --no-hooks."}):(te=Et(r),N(t,{id:"project-hooks",label:"Project agent hooks",status:te.skipped.length>0?"warn":"ok",message:`${te.installed.length} installed, ${te.updated.length} updated, ${te.unchanged.length} already configured, ${te.removed.length} hook config(s) cleaned up, ${te.skipped.length} skipped.`,details:[...te.gitExcluded.map(j=>`Checkout-local Git exclude: ${j}`),...te.removed.map(j=>`Removed ${j}`),...te.skipped.map(j=>`Skipped ${j.target}: ${j.reason}`),...te.warnings]}))}catch(j){N(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:Lt(j)})}let ye=null;try{e.noAgentGuidance?N(t,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(ye=qn(r,{gitHook:e.gitHook}),N(t,{id:"agent-guidance",label:"Project agent guidance",status:ye.skipped.length>0?"warn":"ok",message:`${ye.written.length} written, ${ye.unchanged.length} already wired, ${ye.skipped.length} skipped.`,details:ye.skipped.map(j=>`Skipped ${j.target}: ${j.reason}`)}))}catch(j){N(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:Lt(j)})}let gn=wx({reindexResult:T,readiness:H,capabilities:fn,freshness:Ao,health:Lo,hooksResult:te,agentResult:ye,watchConfig:Z,watchService:O,rustSemanticSession:we,steps:t});N(t,{id:"smoke-tests",label:"Setup smoke tests",status:$x(gn),message:Cx(gn),details:gn.map(j=>`${j.command}: ${j.status} - ${j.evidence}`)});let If={repository:[...a?.changed?[a.configPath]:[],...p?.changed?[p.configPath]:[],...ye?.written.filter(j=>!j.startsWith(".git/hooks/"))??[]],checkout:[...new Set([...te?.installed??[],...te?.updated??[],...te?.gitExcluded??[],...ye?.written.filter(j=>j.startsWith(".git/hooks/"))??[]])],user:[...h.installed,...k.installed,...D.filter(j=>j.attempted).map(j=>`${j.binaryLabel} installer`)]},Ae={projectRoot:r,dbPath:o,configuredDbPath:i.dbPath,scipCliInstalled:g,languages:H.languages,steps:t,skills:h,astParsers:k,initialReadiness:v,indexerRemediation:D,readiness:H,capabilities:fn,freshness:Ao,reindex:T,automaticRefreshConfig:p,watchService:O,rustSemanticSession:we,health:Lo,smokeTests:gn,healthDossier:null,hooks:te,setupAgent:ye,changeScopes:If,filesWritten:ye?.written??[],verdict:ro(t,H)};if(e.runHealth===!1)return N(t,{id:"health-dossier",label:"Health dossier",status:"skipped",message:"Skipped because the optional health audit was not selected."}),Ae.verdict=ro(t,H),Ae;let $e=Cu(Ae,{dossierDir:e.dossierDir});return Ae.healthDossier=$e,Ae.changeScopes.repository.push(...$e.written),Ae.filesWritten=[...Ae.filesWritten,...$e.written],N(t,{id:"health-dossier",label:"Health dossier",status:$e.status==="failed"?"failed":"ok",message:$e.status==="failed"?$e.error:`${$e.written.length} written, ${$e.unchanged.length} unchanged.`,details:[$e.markdownPath,$e.jsonPath]}),Ae.verdict=ro(t,H),Ae}async function Rx(e){if(e.readiness.languages.length===0||e.configHasErrors)return N(e.steps,{id:"reindex",label:"Index refresh",status:"skipped",message:e.readiness.languages.length===0?"Skipped because no supported languages were detected.":"Skipped because config validation has errors."}),{reindexResult:null,freshness:null};let t=[],n=null,r=null;try{let i=0,o=!1;for(let s=0;s<2;s+=1){if(n=await At({projectRoot:e.projectRoot,languages:e.readiness.languages,outputScip:e.paths.indexPath,outputDb:e.paths.dbPath,pnpmWorkspaces:e.config.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.config.indexer?.typescript?.projectMode,typescriptProjects:e.config.indexer?.typescript?.projects,clojureConfigPath:e.config.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:e.config.indexerConcurrency,trigger:{kind:"setup",detail:"scip-query setup"},onStatus:a=>{t.push(a),e.onStatus?.(a)}}),i+=n.durationMs,o||=!n.reused,r=Pe(e.projectRoot,e.config,e.paths),s===0&&n.skipped.length===0&&r.state==="stale"){t.push(`Index inputs changed during the first build (${r.reason}); running one settling refresh.`);continue}break}if(!n)throw new Error("Setup index refresh produced no result.");N(e.steps,{id:"reindex",label:"Index refresh",status:n.skipped.length>0?"warn":"ok",message:`${o?"Indexed":"Reused"} ${n.languages.join(", ")} in ${(i/1e3).toFixed(1)}s.`,details:[...t,...n.skipped.map(s=>`Skipped ${s.language}: ${s.reason}`)]})}catch(i){N(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:Lt(i),details:t})}return{reindexResult:n,freshness:r}}function kx(e){let t=e.readiness.languages.length===0?"Skipped because no supported languages were detected.":e.configHasErrors?"Skipped because config validation has errors.":e.watchConfig.enabled?e.reindexResult===null||e.reindexResult.skipped.length>0||e.postReindexFreshness?.state!=="fresh"?"Skipped because the initial refresh did not produce a complete fresh generation.":null:"Disabled by watch.enabled=false; setup left the explicit opt-out unchanged.";if(t!==null)return N(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",message:t}),null;try{let n=Nn({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:Ne,watchOverrides:e.watchConfig});if(e.watchConfig.idleTimeoutMs>0&&n.state.idleDeadlineAt===void 0)throw new Error("Automatic indexing service did not publish its configured clean-idle deadline.");let r=e.watchConfig.idleTimeoutMs===0?"configured to remain running":`clean-idle exit scheduled for ${n.state.idleDeadlineAt}`;return N(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"ok",message:`${n.disposition} pid ${n.state.pid}; ${r}.`,details:[`watcher=${n.state.watcher.state}`,`autoRefresh=${e.watchConfig.autoRefresh}`,`gitPollMs=${e.watchConfig.gitPollMs}`]}),n}catch(n){return N(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:Lt(n)}),null}}function Du(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${eo(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("Change scopes:"),no("Repository records (commit)",e.changeScopes.repository),no("Checkout preferences (do not commit)",e.changeScopes.checkout),no("User environment",e.changeScopes.user),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 no(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function wx(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==="fresh"?"pass":"fail",evidence:`Index freshness is ${e.freshness.state}: ${e.freshness.reason}`},{id:"config-validate",command:"scip-query config-validate",status:Px(e.steps),evidence:Tx(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?Ix(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:Eu(e.readiness,e.freshness),evidence:ju(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:Eu(e.readiness,e.freshness),evidence:ju(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:Ex(e.capabilities),evidence:jx(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:"scip-query status --json",status:i?.status==="failed"?"fail":e.watchConfig.enabled&&e.watchService?"pass":"unavailable",evidence:i?.message??"Watch refresh policy was not evaluated."},{id:"rust-semantic-session",command:"scip-query status --json",status:e.rustSemanticSession===null?"unavailable":e.rustSemanticSession.valid?"pass":"fail",evidence:e.rustSemanticSession===null?"Rust was not detected.":`${e.rustSemanticSession.transport}/${e.rustSemanticSession.state}; ${e.rustSemanticSession.fallback} fallback; ${e.rustSemanticSession.optOut}.`},{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 $x(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function Cx(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 Px(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function Tx(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function Ix(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 Eu(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function ju(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 Ex(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function jx(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 Ax(e,t,n){let r=[];if(t.languages.length===0)return N(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=st(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,d=!1;l?d=dr(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 p=Lx(wn(a,e));r.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:d,before:s,after:p,messages:c,recovery:p.runnable?void 0:p.note??p.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(r.length===0)return N(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 N(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 Lx(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function Dx(e,t){if(!xx(e)){let n="Skipped because no SQLite index database exists yet.";return N(t,{id:"health",label:"Health audit",status:"skipped",message:n}),io(n)}try{let n=await Fn({full:!0,json:!0});return N(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),Ox(n)}catch(n){let r=Lt(n);return N(t,{id:"health",label:"Health audit",status:"failed",message:r}),io(r)}}function Fx(e){let t="Skipped by setup choice; run `scip-query health --full` when wanted.";return N(e,{id:"health",label:"Health audit",status:"skipped",message:t}),io(t)}function Ox(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(Nx),warnings:e.warnings??[]}}function Nx(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-cleanup-audit to confirm this signal; use scip-cleanup-improve when the user wants confirmed issues fixed autonomously."}}function io(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function ro(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 Mx(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 _x(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 N(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function Lt(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as qx}from"readline";function Bx(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function Vx(e,t,n){if(n.length===0)return e;if(t==="up")return{...e,cursor:(e.cursor-1+n.length)%n.length};if(t==="down")return{...e,cursor:(e.cursor+1)%n.length};let r=n[e.cursor]?.id;if(!r)return e;let i=new Set(e.selected);return i.has(r)?i.delete(r):i.add(r),{...e,selected:i}}async function Fu(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let r=Bx(e);qx(t);let i=t.isRaw;t.setRawMode(!0),t.resume();let o=(s=!1)=>{s||n.write(`\x1B[${e.length+3}A`),n.write(`scip-query setup
343
+ `,i=xu(e)?ku(e,"utf-8"):null;if(i&&dx(i,r)){n.unchanged.push(e);return}wu(e,r),n.written.push(e)}function dx(e,t){try{let n=JSON.parse(e),r=JSON.parse(t);return delete n.generatedAt,delete r.generatedAt,JSON.stringify(n)===JSON.stringify(r)}catch{return e===t}}function ux(e,t){return Zi(e,t)}function Zi(e,t){return typeof e=="string"?px(e,t):Array.isArray(e)?e.map(n=>Zi(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Zi(r,t)])):e}function px(e,t){if(e===t)return".";if(!tx(e))return e;let n=vu(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let r=vu(ex(),e).replace(/\\/g,"/");return r&&!r.startsWith("..")?`~/${r}`:e}return n}import{spawnSync as mx}from"child_process";import{readFileSync as Tu}from"fs";import{dirname as Pu,join as fx,resolve as gx}from"path";import{fileURLToPath as hx}from"url";var Sr={typescript:{ast:"typescript",packages:["tree-sitter-typescript"]},javascript:{ast:"javascript",packages:["tree-sitter-javascript"]},java:{ast:"java",packages:["tree-sitter-java"]},scala:{ast:"scala",packages:["tree-sitter-scala"]},kotlin:{ast:"kotlin",packages:["tree-sitter-kotlin"]},rust:{ast:"rust",packages:["tree-sitter-rust"]},python:{ast:"python",packages:["tree-sitter-python"]},ruby:{ast:"ruby",packages:["tree-sitter-ruby"]},cpp:{ast:"cpp",packages:["tree-sitter-cpp"]},c:{ast:"c",packages:["tree-sitter-c"]},csharp:{ast:"csharp",packages:["tree-sitter-c-sharp"]},php:{ast:"php",packages:["tree-sitter-php"]}};function yx(e,t){let n=new Set(["tree-sitter"]);for(let r of e)for(let i of Sr[r]?.packages??[])n.add(i);return[...n].filter(r=>t[r]).sort().map(r=>`${r}@${t[r]}`)}function to(e){return[...new Set(e.filter(t=>Sr[t]!==void 0))].sort()}function Iu(e,t={}){let n=t.runtime??vx,r=t.packageRoot??bx(),i=to(e),o=i.filter(p=>n.probe(Sr[p].ast)),s=i.filter(p=>!o.includes(p));if(s.length===0)return{supportedLanguages:i,availableBefore:o,installed:[],availableAfter:o,unavailable:[],attempted:!1};let a=Sx(r),c=yx(s,a),l=n.install(r,c);l.ok&&n.resetProbe();let d=i.filter(p=>n.probe(Sr[p].ast));return{supportedLanguages:i,availableBefore:o,installed:l.ok?c:[],availableAfter:d,unavailable:i.filter(p=>!d.includes(p)),attempted:!0,...l.error?{error:l.error}:{}}}function bx(){let e=Pu(hx(import.meta.url));for(;;){let t=fx(e,"package.json");try{if(JSON.parse(Tu(t,"utf8")).name==="scip-query")return e}catch{}let n=Pu(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function Sx(e){return JSON.parse(Tu(gx(e,"package.json"),"utf8")).optionalDependencies??{}}var vx={probe:e=>bn(e)==="ast",resetProbe:Fo,install:(e,t)=>{let n=mx(process.env.npm_execpath?process.execPath:"npm",[...process.env.npm_execpath?[process.env.npm_execpath]:[],"install","--no-save","--no-package-lock","--include=optional",...t],{cwd:e,encoding:"utf8"});return n.status===0?{ok:!0}:{ok:!1,error:(n.stderr||n.stdout||n.error?.message||"npm install failed").trim()}}};function Au(e){let t=[];e.watchEnabled||t.push({id:"enable-automatic-refresh",scope:"repository",label:"Enable automatic incremental indexing",recommended:!0,requiresConsent:!0,reason:"A demand-started project service keeps indexes current and exits after a clean idle period.",command:"scip-query setup"}),e.files.agentsMd||e.files.claudeMd?t.push({id:"update-agent-guidance",scope:"repository",label:"Update project agent guidance",recommended:!0,requiresConsent:!0,reason:"Existing AGENTS.md or CLAUDE.md guidance can be updated in place.",command:"scip-query setup-agent"}):t.push({id:"create-agent-guidance",scope:"repository",label:"Create project agent guidance",recommended:!1,requiresConsent:!0,reason:"No AGENTS.md or CLAUDE.md file exists, so setup should ask before creating one.",command:"scip-query setup-agent"}),(!e.files.codexHooks||!e.files.claudeSettings)&&t.push({id:"install-project-hooks",scope:"checkout",label:"Install project agent hooks",recommended:!0,requiresConsent:!0,reason:"Project hooks help agents check freshness and route through scip-query before editing.",command:"scip-query setup-hooks"});let n=e.readiness.indexers.filter(r=>!r.runnable);return n.length>0&&t.push({id:"install-indexers",scope:"user",label:"Install missing language indexers",recommended:!0,requiresConsent:!0,reason:`${n.length} detected language indexer(s) are not runnable.`,command:"scip-query setup"}),{actions:t}}async function Lu(e={}){let t=[],n=Me(),{projectRoot:r,paths:i,dbPath:o}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,a=e.languages?qa(r,n.config,e.languages):null,c=a?.config??n.config,l=kt(c,{projectRoot:r}),d=l.filter(j=>j.level==="error"),p=null,m=null;if(d.length===0&&c.watch?.enabled!==s)try{p=Va(r,c,s)}catch(j){m=Lt(j)}let f=p?.config??c,g=Xt();N(t,{id:"automatic-indexing-config",label:"Automatic indexing config",status:m!==null?"failed":d.length>0||!s?"skipped":"ok",message:m??(d.length>0?"Skipped because the existing project config has validation errors.":s?p?.changed?"Enabled demand-started automatic incremental indexing for this project.":"Demand-started automatic incremental indexing is already enabled.":"Automatic incremental indexing remains explicitly disabled for this project."),...p?{details:[p.configPath]}:{}}),N(t,{id:"scip-cli",label:"scip CLI",status:g?"ok":"warn",message:g?"scip CLI is available.":"scip CLI is not available; reindex may attempt install."});let h=e.installSkills===!1?{installed:[],skipped:[],alreadyLinked:[],pruned:[]}:Zn({quiet:!0});N(t,{id:"skills",label:"Agent skills",status:e.installSkills===!1?"skipped":h.skipped.length>0?"warn":"ok",message:e.installSkills===!1?"Skipped by setup choice.":`${h.installed.length} installed, ${h.alreadyLinked.length} already linked, ${h.pruned.length} pruned, ${h.skipped.length} skipped.`,details:[...h.pruned.map(j=>`Pruned ${j}`),...h.skipped.map(j=>`Skipped ${j}`)]});let y=p?kt(f,{projectRoot:r}):l,S=y.filter(j=>j.level==="error");N(t,{id:"config",label:"Project config",status:S.length>0?"failed":y.length>0?"warn":"ok",message:y.length===0?"Config OK.":`${y.length} diagnostic(s), ${S.length} error(s).`,details:y.map(j=>`${j.level.toUpperCase()} ${j.path}: ${j.message}`)});let v=ge(r,f);N(t,{id:"readiness",label:"Indexer readiness",status:v.languages.length===0?"failed":v.indexers.some(j=>!j.runnable)?"warn":"ok",message:v.languages.length===0?"No supported project languages detected.":`Detected languages: ${v.languages.join(", ")}`,details:v.indexers.map(j=>`${j.runnable?"OK":j.installed?"WARN":"MISSING"} ${j.language}: ${j.binaryLabel}${j.note?` - ${j.note}`:""}`)});let k=e.installAstParsers===!1?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:Iu(v.languages);N(t,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers===!1?"skipped":k.unavailable.length>0?"warn":"ok",message:e.installAstParsers===!1?"Skipped by setup choice.":k.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${k.availableAfter.length}/${k.supportedLanguages.length} selected language parser(s) available${k.installed.length>0?`; installed ${k.installed.join(", ")}`:""}.`,details:[...k.unavailable.length>0?[`Unavailable: ${k.unavailable.join(", ")}`]:[],...k.error?[k.error]:[]]});let R=e.installIndexers??!0,D=R?Ax(r,v,t):[];R||N(t,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped by guided setup choice."});let B=ge(r,f),z=await Rx({projectRoot:r,paths:i,config:f,readiness:B,configHasErrors:S.length>0,steps:t,onStatus:e.onStatus}),T=z.reindexResult,F=z.freshness,Z=Ce(f),O=kx({projectRoot:r,cacheDir:i.cacheDir,watchConfig:Z,readiness:B,configHasErrors:S.length>0,reindexResult:T,postReindexFreshness:F,steps:t}),H=ge(r,f),fn=Qe(H),Ao=Pe(r,f,i);N(t,{id:"capabilities",label:"Capability matrix",status:Mx(fn),message:_x(fn)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let Lo=e.runHealth===!1?Fx(t):await Dx(i.dbPath,t),we=H.languages.includes("rust")?Pn(r,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;N(t,{id:"rust-semantic-session",label:"Rust semantic session",status:we===null?"skipped":we.valid?"ok":"failed",message:we===null?"Skipped because Rust was not detected.":`${we.transport}/${we.state} selected from ${we.source}; ${we.fallback} fallback; opt out with ${we.optOut}.`});let te=null;try{e.noHooks?N(t,{id:"project-hooks",label:"Project agent hooks",status:"skipped",message:"Skipped by --no-hooks."}):(te=Et(r),N(t,{id:"project-hooks",label:"Project agent hooks",status:te.skipped.length>0?"warn":"ok",message:`${te.installed.length} installed, ${te.updated.length} updated, ${te.unchanged.length} already configured, ${te.removed.length} hook config(s) cleaned up, ${te.skipped.length} skipped.`,details:[...te.gitExcluded.map(j=>`Checkout-local Git exclude: ${j}`),...te.removed.map(j=>`Removed ${j}`),...te.skipped.map(j=>`Skipped ${j.target}: ${j.reason}`),...te.warnings]}))}catch(j){N(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:Lt(j)})}let ye=null;try{e.noAgentGuidance?N(t,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(ye=Bn(r,{gitHook:e.gitHook}),N(t,{id:"agent-guidance",label:"Project agent guidance",status:ye.skipped.length>0?"warn":"ok",message:`${ye.written.length} written, ${ye.unchanged.length} already wired, ${ye.skipped.length} skipped.`,details:ye.skipped.map(j=>`Skipped ${j.target}: ${j.reason}`)}))}catch(j){N(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:Lt(j)})}let gn=wx({reindexResult:T,readiness:H,capabilities:fn,freshness:Ao,health:Lo,hooksResult:te,agentResult:ye,watchConfig:Z,watchService:O,rustSemanticSession:we,steps:t});N(t,{id:"smoke-tests",label:"Setup smoke tests",status:$x(gn),message:Cx(gn),details:gn.map(j=>`${j.command}: ${j.status} - ${j.evidence}`)});let If={repository:[...a?.changed?[a.configPath]:[],...p?.changed?[p.configPath]:[],...ye?.written.filter(j=>!j.startsWith(".git/hooks/"))??[]],checkout:[...new Set([...te?.installed??[],...te?.updated??[],...te?.gitExcluded??[],...ye?.written.filter(j=>j.startsWith(".git/hooks/"))??[]])],user:[...h.installed,...k.installed,...D.filter(j=>j.attempted).map(j=>`${j.binaryLabel} installer`)]},Ae={projectRoot:r,dbPath:o,configuredDbPath:i.dbPath,scipCliInstalled:g,languages:H.languages,steps:t,skills:h,astParsers:k,initialReadiness:v,indexerRemediation:D,readiness:H,capabilities:fn,freshness:Ao,reindex:T,automaticRefreshConfig:p,watchService:O,rustSemanticSession:we,health:Lo,smokeTests:gn,healthDossier:null,hooks:te,setupAgent:ye,changeScopes:If,filesWritten:ye?.written??[],verdict:ro(t,H)};if(e.runHealth===!1)return N(t,{id:"health-dossier",label:"Health dossier",status:"skipped",message:"Skipped because the optional health audit was not selected."}),Ae.verdict=ro(t,H),Ae;let $e=Cu(Ae,{dossierDir:e.dossierDir});return Ae.healthDossier=$e,Ae.changeScopes.repository.push(...$e.written),Ae.filesWritten=[...Ae.filesWritten,...$e.written],N(t,{id:"health-dossier",label:"Health dossier",status:$e.status==="failed"?"failed":"ok",message:$e.status==="failed"?$e.error:`${$e.written.length} written, ${$e.unchanged.length} unchanged.`,details:[$e.markdownPath,$e.jsonPath]}),Ae.verdict=ro(t,H),Ae}async function Rx(e){if(e.readiness.languages.length===0||e.configHasErrors)return N(e.steps,{id:"reindex",label:"Index refresh",status:"skipped",message:e.readiness.languages.length===0?"Skipped because no supported languages were detected.":"Skipped because config validation has errors."}),{reindexResult:null,freshness:null};let t=[],n=null,r=null;try{let i=0,o=!1;for(let s=0;s<2;s+=1){if(n=await At({projectRoot:e.projectRoot,languages:e.readiness.languages,outputScip:e.paths.indexPath,outputDb:e.paths.dbPath,pnpmWorkspaces:e.config.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.config.indexer?.typescript?.projectMode,typescriptProjects:e.config.indexer?.typescript?.projects,clojureConfigPath:e.config.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:e.config.indexerConcurrency,trigger:{kind:"setup",detail:"scip-query setup"},onStatus:a=>{t.push(a),e.onStatus?.(a)}}),i+=n.durationMs,o||=!n.reused,r=Pe(e.projectRoot,e.config,e.paths),s===0&&n.skipped.length===0&&r.state==="stale"){t.push(`Index inputs changed during the first build (${r.reason}); running one settling refresh.`);continue}break}if(!n)throw new Error("Setup index refresh produced no result.");N(e.steps,{id:"reindex",label:"Index refresh",status:n.skipped.length>0?"warn":"ok",message:`${o?"Indexed":"Reused"} ${n.languages.join(", ")} in ${(i/1e3).toFixed(1)}s.`,details:[...t,...n.skipped.map(s=>`Skipped ${s.language}: ${s.reason}`)]})}catch(i){N(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:Lt(i),details:t})}return{reindexResult:n,freshness:r}}function kx(e){let t=e.readiness.languages.length===0?"Skipped because no supported languages were detected.":e.configHasErrors?"Skipped because config validation has errors.":e.watchConfig.enabled?e.reindexResult===null||e.reindexResult.skipped.length>0||e.postReindexFreshness?.state!=="fresh"?"Skipped because the initial refresh did not produce a complete fresh generation.":null:"Disabled by watch.enabled=false; setup left the explicit opt-out unchanged.";if(t!==null)return N(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",message:t}),null;try{let n=Nn({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:Ne,watchOverrides:e.watchConfig});if(e.watchConfig.idleTimeoutMs>0&&n.state.idleDeadlineAt===void 0)throw new Error("Automatic indexing service did not publish its configured clean-idle deadline.");let r=e.watchConfig.idleTimeoutMs===0?"configured to remain running":`clean-idle exit scheduled for ${n.state.idleDeadlineAt}`;return N(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"ok",message:`${n.disposition} pid ${n.state.pid}; ${r}.`,details:[`watcher=${n.state.watcher.state}`,`autoRefresh=${e.watchConfig.autoRefresh}`,`gitPollMs=${e.watchConfig.gitPollMs}`]}),n}catch(n){return N(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:Lt(n)}),null}}function Du(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${eo(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("Change scopes:"),no("Repository records (commit)",e.changeScopes.repository),no("Checkout preferences (do not commit)",e.changeScopes.checkout),no("User environment",e.changeScopes.user),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 no(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function wx(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==="fresh"?"pass":"fail",evidence:`Index freshness is ${e.freshness.state}: ${e.freshness.reason}`},{id:"config-validate",command:"scip-query config-validate",status:Px(e.steps),evidence:Tx(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?Ix(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:Eu(e.readiness,e.freshness),evidence:ju(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:Eu(e.readiness,e.freshness),evidence:ju(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:Ex(e.capabilities),evidence:jx(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:"scip-query status --json",status:i?.status==="failed"?"fail":e.watchConfig.enabled&&e.watchService?"pass":"unavailable",evidence:i?.message??"Watch refresh policy was not evaluated."},{id:"rust-semantic-session",command:"scip-query status --json",status:e.rustSemanticSession===null?"unavailable":e.rustSemanticSession.valid?"pass":"fail",evidence:e.rustSemanticSession===null?"Rust was not detected.":`${e.rustSemanticSession.transport}/${e.rustSemanticSession.state}; ${e.rustSemanticSession.fallback} fallback; ${e.rustSemanticSession.optOut}.`},{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 $x(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function Cx(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 Px(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function Tx(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function Ix(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 Eu(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function ju(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 Ex(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function jx(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 Ax(e,t,n){let r=[];if(t.languages.length===0)return N(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=st(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,d=!1;l?d=dr(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 p=Lx(wn(a,e));r.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:d,before:s,after:p,messages:c,recovery:p.runnable?void 0:p.note??p.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(r.length===0)return N(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 N(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 Lx(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function Dx(e,t){if(!xx(e)){let n="Skipped because no SQLite index database exists yet.";return N(t,{id:"health",label:"Health audit",status:"skipped",message:n}),io(n)}try{let n=await Fn({full:!0,json:!0});return N(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),Ox(n)}catch(n){let r=Lt(n);return N(t,{id:"health",label:"Health audit",status:"failed",message:r}),io(r)}}function Fx(e){let t="Skipped by setup choice; run `scip-query health --full` when wanted.";return N(e,{id:"health",label:"Health audit",status:"skipped",message:t}),io(t)}function Ox(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(Nx),warnings:e.warnings??[]}}function Nx(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-cleanup-audit to confirm this signal; use scip-cleanup-improve when the user wants confirmed issues fixed autonomously."}}function io(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function ro(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 Mx(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 _x(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 N(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function Lt(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as Bx}from"readline";function qx(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function Vx(e,t,n){if(n.length===0)return e;if(t==="up")return{...e,cursor:(e.cursor-1+n.length)%n.length};if(t==="down")return{...e,cursor:(e.cursor+1)%n.length};let r=n[e.cursor]?.id;if(!r)return e;let i=new Set(e.selected);return i.has(r)?i.delete(r):i.add(r),{...e,selected:i}}async function Fu(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let r=qx(e);Bx(t);let i=t.isRaw;t.setRawMode(!0),t.resume();let o=(s=!1)=>{s||n.write(`\x1B[${e.length+3}A`),n.write(`scip-query setup
344
344
  `),n.write(`Use \u2191/\u2193 to move, space to toggle, enter to start. Ctrl-C cancels.
345
345
 
346
346
  `),e.forEach((a,c)=>{let l=c===r.cursor?"\u203A":" ",d=r.selected.has(a.id)?"\u25CF":"\u25CB";n.write(`${l} ${d} ${a.label} [${a.scope}]\x1B[K
@@ -373,34 +373,34 @@ ${e.hasNpmProject?` - run: npm ci
373
373
  `)+`
374
374
  `} - run: npx ${t} reindex
375
375
  - run: npx ${t} diff-gate --base "origin/\${{ github.base_ref }}"
376
- `}import{existsSync as Jx}from"fs";import{join as vr}from"path";function _u(e){let t=e.global===!0,n=e.project===!0,r=!t&&!n,i=t||r,o=n||r,s={dryRun:e.dryRun===!0};return i&&(s.global=$l({dryRun:e.dryRun,homeDir:e.homeDir})),o&&(s.project=zx(e.projectRoot,{dryRun:e.dryRun})),s}function zx(e,t={}){return{hooks:Et(e,{remove:!0,dryRun:t.dryRun}),agentSetup:Kc(e,{dryRun:t.dryRun}),left:Kx(e)}}function Kx(e){return[[".scipquery.json",vr(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",vr(e,".scipquery","suppressions")],[".scipquery/ledger/ (repository records)",vr(e,".scipquery","ledger")],["docs/scip-query/",vr(e,"docs","scip-query")]].filter(([,t])=>Jx(t)).map(([t])=>t)}import{existsSync as Qx,readFileSync as Yx}from"fs";import{createRequire as Xx}from"module";import Rr from"path";import{performance as xr}from"perf_hooks";var Zx=Xx(import.meta.url),an;function Wu(e){let t=eR();if(!t)return In("typescript is not installed");let n=cs(e);if(n.length===0)return In("no tsconfig found");try{return new oo(e.config.projectRoot,t,n.map(r=>tR(t,r)))}catch(r){return In(r instanceof Error?r.message:String(r),n[0],n)}}function Gu(e,t,n){let r=xr.now(),i=qu(t,e),o=xr.now()-r,s=xr.now(),a=qu(n,e),c=xr.now()-s,l=[],d=0,p=0,m=0,f=0,g=0;for(let h of e){let y=i.get(h.symbolId)??[],S=a.get(h.symbolId)??[];p+=y.length,m+=S.length;let v=Bu(y),k=Bu(S),R=Vu(y,k),D=Vu(S,v);if(R.length===0&&D.length===0){d+=1;continue}f+=R.length,g+=D.length,l.push({symbol:h.symbol,missing:R,extra:D})}return{slot:"semantic-references",definitions:e.length,matches:d,mismatchCount:l.length,missingReferenceCount:f,extraReferenceCount:g,baselineReferenceCount:p,candidateReferenceCount:m,baselineMs:Number(o.toFixed(3)),candidateMs:Number(c.toFixed(3)),mismatches:l}}var oo=class{constructor(t,n,r){this.projectRoot=t;this.ts=n;this.bundles=r}projectRoot;ts;bundles;language="typescript";referencesCache=new Map;availability(){return{available:!0,tsconfigPath:this.bundles[0]?.tsconfigPath,tsconfigPaths:this.bundles.map(t=>t.tsconfigPath)}}importUsage(t){return[]}referencesFor(t){let n=this.referencesCache.get(t.symbolId);if(n)return n;let r=this.computeReferences(t);return this.referencesCache.set(t.symbolId,r),r}referencesForDefinitions(t){let n=new Map;for(let r of t)n.set(r.symbolId,this.referencesFor(r));return n}calleesFor(t){return[]}signatureFor(t){return null}computeReferences(t){let n=Rr.join(this.projectRoot,t.relativePath),r=this.bundleForFile(n);if(!r)return[];let i=r.service.getProgram()?.getSourceFile(n);if(!i)return[];let o=rR(this.ts,i,t);if(o===null)return[];let s=r.service.findReferences(n,o)??[],a=[];for(let c of s)for(let l of c.references){let d=iR(this.ts,r.service,this.projectRoot,l);d&&(d.file===t.relativePath&&d.line>=t.startLine&&d.line<=t.endLine||a.push(d))}return ss(a)}bundleForFile(t){let n=Ju(t);return this.bundles.find(r=>r.files.has(n))??null}};function eR(){if(an!==void 0)return an;try{an=Zx("typescript")}catch{an=null}return an}function tR(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(Hu(e,n.error));let r=e.parseJsonConfigFileContent(n.config,e.sys,Rr.dirname(t));if(r.errors.length>0)throw new Error(r.errors.map(s=>Hu(e,s)).join(`
376
+ `}import{existsSync as Jx}from"fs";import{join as vr}from"path";function _u(e){let t=e.global===!0,n=e.project===!0,r=!t&&!n,i=t||r,o=n||r,s={dryRun:e.dryRun===!0};return i&&(s.global=$l({dryRun:e.dryRun,homeDir:e.homeDir})),o&&(s.project=zx(e.projectRoot,{dryRun:e.dryRun})),s}function zx(e,t={}){return{hooks:Et(e,{remove:!0,dryRun:t.dryRun}),agentSetup:Kc(e,{dryRun:t.dryRun}),left:Kx(e)}}function Kx(e){return[[".scipquery.json",vr(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",vr(e,".scipquery","suppressions")],[".scipquery/ledger/ (repository records)",vr(e,".scipquery","ledger")],["docs/scip-query/",vr(e,"docs","scip-query")]].filter(([,t])=>Jx(t)).map(([t])=>t)}import{existsSync as Qx,readFileSync as Yx}from"fs";import{createRequire as Xx}from"module";import Rr from"path";import{performance as xr}from"perf_hooks";var Zx=Xx(import.meta.url),an;function Wu(e){let t=eR();if(!t)return In("typescript is not installed");let n=cs(e);if(n.length===0)return In("no tsconfig found");try{return new oo(e.config.projectRoot,t,n.map(r=>tR(t,r)))}catch(r){return In(r instanceof Error?r.message:String(r),n[0],n)}}function Gu(e,t,n){let r=xr.now(),i=Bu(t,e),o=xr.now()-r,s=xr.now(),a=Bu(n,e),c=xr.now()-s,l=[],d=0,p=0,m=0,f=0,g=0;for(let h of e){let y=i.get(h.symbolId)??[],S=a.get(h.symbolId)??[];p+=y.length,m+=S.length;let v=qu(y),k=qu(S),R=Vu(y,k),D=Vu(S,v);if(R.length===0&&D.length===0){d+=1;continue}f+=R.length,g+=D.length,l.push({symbol:h.symbol,missing:R,extra:D})}return{slot:"semantic-references",definitions:e.length,matches:d,mismatchCount:l.length,missingReferenceCount:f,extraReferenceCount:g,baselineReferenceCount:p,candidateReferenceCount:m,baselineMs:Number(o.toFixed(3)),candidateMs:Number(c.toFixed(3)),mismatches:l}}var oo=class{constructor(t,n,r){this.projectRoot=t;this.ts=n;this.bundles=r}projectRoot;ts;bundles;language="typescript";referencesCache=new Map;availability(){return{available:!0,tsconfigPath:this.bundles[0]?.tsconfigPath,tsconfigPaths:this.bundles.map(t=>t.tsconfigPath)}}importUsage(t){return[]}referencesFor(t){let n=this.referencesCache.get(t.symbolId);if(n)return n;let r=this.computeReferences(t);return this.referencesCache.set(t.symbolId,r),r}referencesForDefinitions(t){let n=new Map;for(let r of t)n.set(r.symbolId,this.referencesFor(r));return n}calleesFor(t){return[]}signatureFor(t){return null}computeReferences(t){let n=Rr.join(this.projectRoot,t.relativePath),r=this.bundleForFile(n);if(!r)return[];let i=r.service.getProgram()?.getSourceFile(n);if(!i)return[];let o=rR(this.ts,i,t);if(o===null)return[];let s=r.service.findReferences(n,o)??[],a=[];for(let c of s)for(let l of c.references){let d=iR(this.ts,r.service,this.projectRoot,l);d&&(d.file===t.relativePath&&d.line>=t.startLine&&d.line<=t.endLine||a.push(d))}return ss(a)}bundleForFile(t){let n=Ju(t);return this.bundles.find(r=>r.files.has(n))??null}};function eR(){if(an!==void 0)return an;try{an=Zx("typescript")}catch{an=null}return an}function tR(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(Hu(e,n.error));let r=e.parseJsonConfigFileContent(n.config,e.sys,Rr.dirname(t));if(r.errors.length>0)throw new Error(r.errors.map(s=>Hu(e,s)).join(`
377
377
  `));let i=new Set(r.fileNames.map(Ju)),o=e.createLanguageService(nR(e,r),e.createDocumentRegistry());return{tsconfigPath:t,service:o,files:i}}function nR(e,t){return{getCompilationSettings:()=>t.options,getCurrentDirectory:()=>t.options.configFilePath?Rr.dirname(String(t.options.configFilePath)):process.cwd(),getDefaultLibFileName:n=>e.getDefaultLibFilePath(n),getDirectories:e.sys.getDirectories,getScriptFileNames:()=>t.fileNames,getScriptSnapshot:n=>{if(Qx(n))return e.ScriptSnapshot.fromString(Yx(n,"utf8"))},getScriptVersion:()=>"0",readDirectory:e.sys.readDirectory,readFile:e.sys.readFile,fileExists:e.sys.fileExists,directoryExists:e.sys.directoryExists,realpath:e.sys.realpath,useCaseSensitiveFileNames:()=>e.sys.useCaseSensitiveFileNames}}function rR(e,t,n){let r=t.text.split(`
378
- `),i=Math.max(0,n.startLine),o=Math.min(r.length-1,Math.max(n.endLine,n.startLine));for(let s=i;s<=o;s+=1){let a=r[s]?.indexOf(n.leaf)??-1;if(a>=0)return e.getPositionOfLineAndCharacter(t,s,a)}return null}function iR(e,t,n,r){let i=as(n,r.fileName);if(!i)return null;let o=t.getProgram()?.getSourceFile(r.fileName);if(!o)return null;let s=e.getLineAndCharacterOfPosition(o,r.textSpan.start);return{file:i,line:s.line,column:s.character}}function qu(e,t){return e.referencesForDefinitions?e.referencesForDefinitions(t):new Map(t.map(n=>[n.symbolId,e.referencesFor(n)]))}function Bu(e){return new Set(e.map(Uu))}function Vu(e,t){return e.filter(n=>!t.has(Uu(n)))}function Uu(e){return`${e.file}:${e.line}:${e.column}`}function Ju(e){return Rr.resolve(e).replace(/\\/g,"/")}function Hu(e,t){return e.flattenDiagnosticMessageText(t.messageText,`
378
+ `),i=Math.max(0,n.startLine),o=Math.min(r.length-1,Math.max(n.endLine,n.startLine));for(let s=i;s<=o;s+=1){let a=r[s]?.indexOf(n.leaf)??-1;if(a>=0)return e.getPositionOfLineAndCharacter(t,s,a)}return null}function iR(e,t,n,r){let i=as(n,r.fileName);if(!i)return null;let o=t.getProgram()?.getSourceFile(r.fileName);if(!o)return null;let s=e.getLineAndCharacterOfPosition(o,r.textSpan.start);return{file:i,line:s.line,column:s.character}}function Bu(e,t){return e.referencesForDefinitions?e.referencesForDefinitions(t):new Map(t.map(n=>[n.symbolId,e.referencesFor(n)]))}function qu(e){return new Set(e.map(Uu))}function Vu(e,t){return e.filter(n=>!t.has(Uu(n)))}function Uu(e){return`${e.file}:${e.line}:${e.column}`}function Ju(e){return Rr.resolve(e).replace(/\\/g,"/")}function Hu(e,t){return e.flattenDiagnosticMessageText(t.messageText,`
379
379
  `)}import{readFileSync as oR}from"fs";function zu(e){let t=[];for(let[n,r]of oR(e,"utf8").split(`
380
- `).entries()){let i=r.trim();if(!i)continue;let o;try{o=JSON.parse(i)}catch(s){throw new Error(`${e}:${n+1}: invalid profile JSON: ${s instanceof Error?s.message:String(s)}`,{cause:s})}if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`${e}:${n+1}: profile event must be a JSON object`);t.push(o)}return t}function Ku(e,t={}){let n=new Map,r=new Map,i=new Map,o=new Set,s=new Set,a=new Set,c=new Set,l=0,d=0,p=0;for(let[y,S]of e.entries()){let v=he(S.name)??he(S.phase),k=pR(S.durationMs),R=he(S.runId);v&&k!==null&&(l+=1,s.add(v),R&&o.add(R),sR(i,S,v,k),aR(r,S,v,k,R),he(S.subsystemWorkIdentity)&&c.add(v));let D=he(S.workIdentity);if(!D)continue;d+=1,v&&a.add(v);let q=uR(S.workOutcome);if(!v||k===null||!q){p+=1;continue}let z=R??`unknown-run-${y}`,T=JSON.stringify([v,D]),F=n.get(T)??{spanName:v,workIdentity:D,observations:[]};F.observations.push({runId:z,command:he(S.command)??"unknown",durationMs:k,outcome:q}),n.set(T,F)}let m=[...n.values()].map(dR).filter(y=>y!==null).sort((y,S)=>S.estimatedAvoidableMs-y.estimatedAvoidableMs||S.repeatComputations-y.repeatComputations||y.spanName.localeCompare(S.spanName)||y.workIdentity.localeCompare(S.workIdentity)),f=[...r.values()].map(cR).filter(y=>y!==null).sort((y,S)=>S.laterRunMs-y.laterRunMs||S.laterRunEvents-y.laterRunEvents||y.spanName.localeCompare(S.spanName)),g=[...i.values()].map(lR).sort((y,S)=>S.totalDurationMs-y.totalDurationMs||y.subsystem.localeCompare(S.subsystem)),h=t.top??20;return{profileEvents:e.length,spanEvents:l,distinctSpanNames:s.size,instrumentedEvents:d,unclassifiedInstrumentedEvents:p,exactIdentifiedSpanNames:a.size,workloadIdentifiedEvents:g.reduce((y,S)=>y+S.workloadIdentifiedEvents,0),workloadIdentifiedSpanNames:c.size,runCount:o.size,repeatedGroups:m.length,largestOpportunityMs:m[0]?.estimatedAvoidableMs??0,rows:m.slice(0,h),repeatedWorkloads:f.length,largestRepeatedWorkloadMs:f[0]?.laterRunMs??0,workloadRows:f.slice(0,h),subsystemCoverage:g}}function Qu(e,t){let n=["scip-query work-audit",`Profile: ${t}`,`Profile events: ${e.profileEvents}; spans: ${e.spanEvents}; distinct span names: ${e.distinctSpanNames}; runs: ${e.runCount}`,`Subsystem identity coverage: ${e.workloadIdentifiedSpanNames}/${e.distinctSpanNames} span names, ${e.workloadIdentifiedEvents}/${e.spanEvents} events`,`Exact identity coverage: ${e.exactIdentifiedSpanNames}/${e.distinctSpanNames} span names, ${e.instrumentedEvents}/${e.spanEvents} events`,`Repeated work groups: ${e.repeatedGroups}; largest measured opportunity: ${e.largestOpportunityMs}ms`,""];if(e.rows.length===0)n.push("No exact repeated computations were found in work-identified profile events."),e.instrumentedEvents===0&&n.push("This profile predates exact work identities or its spans have not been instrumented yet.");else{n.push("Exact repeated computations:"),n.push("avoidableMs withinRunMs crossRunMs repeats runs span workIdentity commands");for(let r of e.rows)n.push([r.estimatedAvoidableMs,r.withinRunAvoidableMs,r.crossRunRecomputeMs,r.repeatComputations,r.runCount,r.spanName,r.workIdentity,r.commands.join(", ")].join(" "))}if(n.push("",`Repeated subsystem workloads: ${e.repeatedWorkloads}`),e.workloadRows.length===0)n.push("No named subsystem workload was observed in more than one run.");else{n.push("laterRunMs firstRunMs laterEvents runs subsystem span subsystemWorkIdentity commands");for(let r of e.workloadRows)n.push([r.laterRunMs,r.firstRunMs,r.laterRunEvents,r.runCount,r.subsystem,r.spanName,r.subsystemWorkIdentity,r.commands.join(", ")].join(" "))}return n.push("","Rows are independent measurements; nested spans can overlap and must not be summed."),n.push("Within-run time is direct duplication. Cross-run time is a durable-cache opportunity that still needs safe invalidation."),n.push("Subsystem workload time is an aggregate observation against the same command/project inputs, not proven avoidable time."),`${n.join(`
380
+ `).entries()){let i=r.trim();if(!i)continue;let o;try{o=JSON.parse(i)}catch(s){throw new Error(`${e}:${n+1}: invalid profile JSON: ${s instanceof Error?s.message:String(s)}`,{cause:s})}if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`${e}:${n+1}: profile event must be a JSON object`);t.push(o)}return t}function Ku(e,t={}){let n=new Map,r=new Map,i=new Map,o=new Set,s=new Set,a=new Set,c=new Set,l=0,d=0,p=0;for(let[y,S]of e.entries()){let v=he(S.name)??he(S.phase),k=pR(S.durationMs),R=he(S.runId);v&&k!==null&&(l+=1,s.add(v),R&&o.add(R),sR(i,S,v,k),aR(r,S,v,k,R),he(S.subsystemWorkIdentity)&&c.add(v));let D=he(S.workIdentity);if(!D)continue;d+=1,v&&a.add(v);let B=uR(S.workOutcome);if(!v||k===null||!B){p+=1;continue}let z=R??`unknown-run-${y}`,T=JSON.stringify([v,D]),F=n.get(T)??{spanName:v,workIdentity:D,observations:[]};F.observations.push({runId:z,command:he(S.command)??"unknown",durationMs:k,outcome:B}),n.set(T,F)}let m=[...n.values()].map(dR).filter(y=>y!==null).sort((y,S)=>S.estimatedAvoidableMs-y.estimatedAvoidableMs||S.repeatComputations-y.repeatComputations||y.spanName.localeCompare(S.spanName)||y.workIdentity.localeCompare(S.workIdentity)),f=[...r.values()].map(cR).filter(y=>y!==null).sort((y,S)=>S.laterRunMs-y.laterRunMs||S.laterRunEvents-y.laterRunEvents||y.spanName.localeCompare(S.spanName)),g=[...i.values()].map(lR).sort((y,S)=>S.totalDurationMs-y.totalDurationMs||y.subsystem.localeCompare(S.subsystem)),h=t.top??20;return{profileEvents:e.length,spanEvents:l,distinctSpanNames:s.size,instrumentedEvents:d,unclassifiedInstrumentedEvents:p,exactIdentifiedSpanNames:a.size,workloadIdentifiedEvents:g.reduce((y,S)=>y+S.workloadIdentifiedEvents,0),workloadIdentifiedSpanNames:c.size,runCount:o.size,repeatedGroups:m.length,largestOpportunityMs:m[0]?.estimatedAvoidableMs??0,rows:m.slice(0,h),repeatedWorkloads:f.length,largestRepeatedWorkloadMs:f[0]?.laterRunMs??0,workloadRows:f.slice(0,h),subsystemCoverage:g}}function Qu(e,t){let n=["scip-query work-audit",`Profile: ${t}`,`Profile events: ${e.profileEvents}; spans: ${e.spanEvents}; distinct span names: ${e.distinctSpanNames}; runs: ${e.runCount}`,`Subsystem identity coverage: ${e.workloadIdentifiedSpanNames}/${e.distinctSpanNames} span names, ${e.workloadIdentifiedEvents}/${e.spanEvents} events`,`Exact identity coverage: ${e.exactIdentifiedSpanNames}/${e.distinctSpanNames} span names, ${e.instrumentedEvents}/${e.spanEvents} events`,`Repeated work groups: ${e.repeatedGroups}; largest measured opportunity: ${e.largestOpportunityMs}ms`,""];if(e.rows.length===0)n.push("No exact repeated computations were found in work-identified profile events."),e.instrumentedEvents===0&&n.push("This profile predates exact work identities or its spans have not been instrumented yet.");else{n.push("Exact repeated computations:"),n.push("avoidableMs withinRunMs crossRunMs repeats runs span workIdentity commands");for(let r of e.rows)n.push([r.estimatedAvoidableMs,r.withinRunAvoidableMs,r.crossRunRecomputeMs,r.repeatComputations,r.runCount,r.spanName,r.workIdentity,r.commands.join(", ")].join(" "))}if(n.push("",`Repeated subsystem workloads: ${e.repeatedWorkloads}`),e.workloadRows.length===0)n.push("No named subsystem workload was observed in more than one run.");else{n.push("laterRunMs firstRunMs laterEvents runs subsystem span subsystemWorkIdentity commands");for(let r of e.workloadRows)n.push([r.laterRunMs,r.firstRunMs,r.laterRunEvents,r.runCount,r.subsystem,r.spanName,r.subsystemWorkIdentity,r.commands.join(", ")].join(" "))}return n.push("","Rows are independent measurements; nested spans can overlap and must not be summed."),n.push("Within-run time is direct duplication. Cross-run time is a durable-cache opportunity that still needs safe invalidation."),n.push("Subsystem workload time is an aggregate observation against the same command/project inputs, not proven avoidable time."),`${n.join(`
381
381
  `)}
382
- `}function sR(e,t,n,r){let i=he(t.subsystem)??n.split(/[.:]/,1)[0]??n,o=e.get(i)??{subsystem:i,events:0,totalDurationMs:0,spanNames:new Set,workloadIdentifiedEvents:0,workloadIdentifiedSpanNames:new Set,exactIdentifiedEvents:0,exactIdentifiedSpanNames:new Set};o.events+=1,o.totalDurationMs+=r,o.spanNames.add(n),he(t.subsystemWorkIdentity)&&(o.workloadIdentifiedEvents+=1,o.workloadIdentifiedSpanNames.add(n)),he(t.workIdentity)&&(o.exactIdentifiedEvents+=1,o.exactIdentifiedSpanNames.add(n)),e.set(i,o)}function aR(e,t,n,r,i){let o=he(t.subsystemWorkIdentity);if(!o||!i||t.workloadIdentityKind!=="published-project")return;let s=he(t.subsystem)??n.split(/[.:]/,1)[0]??n,a=JSON.stringify([n,o]),c=e.get(a)??{subsystem:s,spanName:n,subsystemWorkIdentity:o,observations:[]};c.observations.push({runId:i,command:he(t.command)??"unknown",durationMs:r}),e.set(a,c)}function cR(e){let t=new Map;for(let o of e.observations){let s=t.get(o.runId)??[];s.push(o),t.set(o.runId,s)}let n=[...t.values()];if(n.length<2)return null;let r=n[0],i=n.slice(1).flat();return{subsystem:e.subsystem,spanName:e.spanName,subsystemWorkIdentity:e.subsystemWorkIdentity,commands:[...new Set(e.observations.map(o=>o.command))].sort(),runCount:n.length,totalEvents:e.observations.length,firstRunEvents:r.length,laterRunEvents:i.length,totalDurationMs:Dt(e.observations.map(o=>o.durationMs)),firstRunMs:Dt(r.map(o=>o.durationMs)),laterRunMs:Dt(i.map(o=>o.durationMs))}}function lR(e){return{subsystem:e.subsystem,events:e.events,totalDurationMs:e.totalDurationMs,spanNames:[...e.spanNames].sort(),workloadIdentifiedEvents:e.workloadIdentifiedEvents,workloadIdentifiedSpanNames:e.workloadIdentifiedSpanNames.size,exactIdentifiedEvents:e.exactIdentifiedEvents,exactIdentifiedSpanNames:e.exactIdentifiedSpanNames.size}}function dR(e){let t=e.observations.filter(a=>a.outcome==="computed");if(t.length<2)return null;let n=new Map;for(let a of t){let c=n.get(a.runId)??[];c.push(a),n.set(a.runId,c)}let r=[...n.values()],i=Dt(r.flatMap(a=>a.slice(1).map(c=>c.durationMs))),o=Dt(r.slice(1).map(a=>a[0]?.durationMs??0)),s=[...new Set(e.observations.map(a=>a.command))].sort();return{spanName:e.spanName,workIdentity:e.workIdentity,commands:s,computations:t.length,runCount:r.length,repeatComputations:t.length-1,withinRunRepeats:t.length-r.length,crossRunRecomputes:Math.max(0,r.length-1),totalComputeMs:Dt(t.map(a=>a.durationMs)),firstComputeMs:t[0]?.durationMs??0,withinRunAvoidableMs:i,crossRunRecomputeMs:o,estimatedAvoidableMs:i+o,cacheHits:kr(e.observations,"cache-hit"),cacheMisses:kr(e.observations,"cache-miss"),reused:kr(e.observations,"reused"),skipped:kr(e.observations,"skipped")}}function uR(e){switch(e){case"computed":case"cache-hit":case"cache-miss":case"reused":case"skipped":return e;default:return null}}function kr(e,t){return e.filter(n=>n.outcome===t).length}function pR(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function he(e){return typeof e=="string"&&e.length>0?e:null}function Dt(e){return e.reduce((t,n)=>t+n,0)}var Yu={status:"experimental-composite",comparableAcrossLanguages:!1,scope:"completed-analyses-only",note:"The score summarizes analyses that completed under the attached capability matrix. It is not normalized across languages or frameworks and is not suitable for a public leaderboard."};function Xu(e,t){let n=mR(t);return{...e,warnings:[...e.warnings??[],Yu.note,...n],capabilities:t,scoreInterpretation:Yu}}function mR(e){return e.matrix.flatMap(t=>{let n=[t.indexing,t.sourceFacts,t.semantic,t.cleanupVerification].map(r=>/syntax only/i.test(r.reason)?`${r.label}=partial (syntax only)`:r.status==="available"?null:`${r.label}=${r.status}`).filter(r=>r!==null);return n.length===0?[]:[`${t.language} capability limits: ${n.join(", ")}. Unsupported analyses are not clean zeros.`]})}var xR=new Set(_a),RR=18e4,np=100*1024*1024,kR=new Set(Oo),wR=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],$R=[["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 CR(e){return e.filter(t=>xR.has(t))}async function rp(e){let t=G(e),n=Y(),r=me(n),i=Fe(n,r),o=b(t,"json");try{let s=CR(Ct(t,"language")),a=await At({projectRoot:n,languages:s.length>0?s:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:b(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,clojureConfigPath:r.indexer?.clojure?.configPath,skipIfUnchanged:!b(t,"force"),allowPartial:b(t,"allowPartial"),skipAutoInstall:process.env.SCIP_QUERY_SKIP_AUTO_INSTALL==="1",indexerConcurrency:U(t,"indexerConcurrency")??r.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"},...o?{onStatus:()=>{}}:{}});if(o){I("reindex",[],t,a);return}console.log(`${a.reused?"Reused":"Indexed"} ${a.languages.join(", ")} in ${(a.durationMs/1e3).toFixed(1)}s`)}catch(s){console.error(`error: ${s instanceof Error?s.message:s}`),process.exit(1)}}function ip(){let e=Y(),t=wt(e);try{let n=tr({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 op(e){let t=G(e),n=Y(),r=wt(n);try{let i=Ui({projectRoot:n,dbPath:r,tsconfig:w(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}; not-inserted identifier tokens: ${i.skippedReferences}; synthetic symbols: ${i.syntheticSymbols}.`),console.log(`Not inserted by reason: no definition ${i.skippedReferenceReasons["no-definition"]}; same-file definition ${i.skippedReferenceReasons["same-file-definition"]}; unindexed definition ${i.skippedReferenceReasons["unindexed-definition"]}; missing source ${i.skippedReferenceReasons["missing-source-file"]}; missing service script ${i.skippedReferenceReasons["missing-service-script"]}. Samples: ${i.skippedReferenceSamples.length} omitted, ${i.resolvedReferenceSamples.length} resolved.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}}function sp(e){let t=G(e);ce(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=na(n,{base:w(t,"base")}),o=ra(n,r,i.changedFiles,i.changedRanges);console.log(JSON.stringify(o))})}async function ap(e){let t=G(e);try{let n=await uc({base:w(t,"base")});if(b(t,"json")){I("diff-impact",[],t,n);return}pc(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function cp(e,t){let n=G(t),r=String(e).split(",").filter(i=>i.length>0);ce(i=>{let o=[];for(let c of r)Aa.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:w(n,"scope"),full:b(n,"full")},a=o.length===1?La(i,o[0],s):Da(i,o,s);console.log(JSON.stringify(a))})}async function lp(e){let t=G(e);if(b(t,"writeBaseline")||b(t,"baseline")){qR(t);return}try{let n=await Fn({scope:w(t,"scope"),full:b(t,"full"),json:b(t,"json")}),{projectRoot:r,config:i,dbPath:o}=Me(),s=Qe(ge(r,i),{hasIndexedGraph:ke(o)}),a=Xu(n,s);if(b(t,"json")){I("health",[],t,a);return}dc(a,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function dp(e){let t=G(e),n=Y(),r=U(t,"timeoutMs")??RR,i=b(t,"progress"),o=b(t,"profile"),s=w(t,"profileOut"),a={projectRoot:n,...OR(n),index:so(ke(wt(n))),commands:[]};b(t,"coldIndex")&&(Ft(i,"cold index started"),a.coldIndex=await PR(n),Ft(i,`cold index finished ${a.coldIndex.durationMs}ms`),qt({type:"bench-index",phase:"cold-index",projectRoot:n,durationMs:a.coldIndex.durationMs,result:a.coldIndex.result,files:a.coldIndex.files,symbols:a.coldIndex.symbols},s),Ft(i,"warm index started"),a.warmIndex=await jR(n),Ft(i,`warm index finished ${a.warmIndex.durationMs}ms`),qt({type:"bench-index",phase:"warm-index",projectRoot:n,durationMs:a.warmIndex.durationMs,result:a.warmIndex.result,files:a.warmIndex.files,symbols:a.warmIndex.symbols},s),a.index=so(ke(wt(n))));for(let c of AR(t))a.commands.push(DR(n,c,r,{progress:i,profile:o,profileOut:s}));if(b(t,"json")){I("bench",[],t,a);return}NR(a)}function up(e,t){let n=G(t),r=vR(String(e)),i=Ku(zu(r),{top:U(n,"top")??20});if(b(n,"json")){I("work-audit",[r],n,{profilePath:r,...i});return}process.stdout.write(Qu(i,r))}function pp(e){let t=G(e);ce(n=>{let r=n.config.projectRoot,i=w(t,"scope")??null,o=b(t,"full"),s=U(t,"limit")??200,a=Math.max(0,U(t,"maxMismatches")??10),c=Bo(n).filter(k=>Ht(k.relativePath)).filter(k=>!n.isIgnored(k.relativePath)).sort(_R),l=i?c.filter(k=>k.relativePath.includes(i)):c,d=o?l:l.slice(0,s),p=et.now(),m=ds(n),f=Number((et.now()-p).toFixed(3)),g=et.now(),h=Wu(n),y=Number((et.now()-g).toFixed(3)),S=Gu(d,m,h),v={projectRoot:r,selection:{scope:i,full:o,limit:o?null:s,maxMismatchDetails:a,totalTypeScriptDefinitions:c.length,scopedDefinitions:l.length,comparedDefinitions:d.length},baseline:{provider:"ts-morph",createMs:f,availability:m.availability()},candidate:{provider:"tsserver",createMs:y,availability:h.availability()},comparison:{...S,mismatches:S.mismatches.slice(0,a)}};if(b(t,"json")){I("typescript-semantic-compare",[],t,v);return}MR(v)})}async function PR(e){let t=me(e),n=Fe(e,t),r=wr(n.dbPath),i=`${r}.bench-backup-${Date.now()}`;TR(r);let o=IR(r,i);try{let s=await mp(()=>At({projectRoot:e,languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench --cold-index"},onStatus:()=>{}}));return Zu(r,i,o,"discard-backup"),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...fp(e)}}catch(s){throw Zu(r,i,o,"restore-backup"),s}}var ao={existsSync:ke,readFileSync:fR,writeFileSync:bR,renameSync:gR,rmSync:hR,unlinkSync:yR};function co(e){return mt(wr(e),"bench-restore.json")}function TR(e,t=ao){let n=co(e);if(!t.existsSync(n))return!1;let r=ER(t.readFileSync(n,"utf8"));return r&&!t.existsSync(r.originalPath)&&t.existsSync(r.backupPath)&&t.renameSync(r.backupPath,r.originalPath),t.unlinkSync(n),!0}function IR(e,t,n=ao){return n.existsSync(e)?(n.writeFileSync(co(e),JSON.stringify({originalPath:e,backupPath:t})),n.renameSync(e,t),!0):!1}function Zu(e,t,n,r,i=ao){n&&r==="restore-backup"&&!i.existsSync(e)&&i.existsSync(t)?i.renameSync(t,e):n&&r==="discard-backup"&&i.rmSync(t,{recursive:!0,force:!0});let o=co(e);i.existsSync(o)&&i.unlinkSync(o)}function ER(e){try{let t=JSON.parse(e);return typeof t.originalPath=="string"&&typeof t.backupPath=="string"?{originalPath:t.originalPath,backupPath:t.backupPath}:null}catch{return null}}async function jR(e){let t=me(e),n=Fe(e,t),r=await mp(()=>At({projectRoot:e,languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench warm index"},onStatus:()=>{}}));return{durationMs:r.durationMs,result:r.value.reused?"reused":"rebuilt",languages:r.value.languages,...fp(e)}}async function mp(e){let t=et.now(),n=await e();return{durationMs:Math.round(et.now()-t),value:n}}function fp(e){return ke(wt(e))?ce(t=>{let n=vt(t);return{files:n.documents,symbols:n.symbols}}):{}}function AR(e){let t=Ct(e,"command");return t.length>0?t.map(LR).filter(n=>n.length>0):[...wR.map(n=>[...n]),...b(e,"includeHeavy")?$R.map(n=>[...n]):[]]}function LR(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function DR(e,t,n,r={}){let i=`scip-query ${t.join(" ")}`;Ft(r.progress,`${i} started`),qt({type:"bench-command-start",command:i,projectRoot:e},r.profileOut);let o=et.now(),s={...r.profile?FR(i,r.profileOut):process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"},a=tp(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:np,timeout:n}),c=Math.round(et.now()-o),l={command:i,durationMs:c,exitCode:a.status,signal:a.signal,timedOut:a.error?.code==="ETIMEDOUT"||a.error?.name==="ETIMEDOUT",stdoutBytes:a.stdout?.length??0,stderrBytes:a.stderr?.length??0,...r.profileOut?{profilePath:r.profileOut}:{}};return Ft(r.progress,`${i} finished ${c}ms exit=${l.exitCode??l.signal??"unknown"}${l.timedOut?" timed-out":""}`),qt({type:"bench-command-finish",command:i,projectRoot:e,durationMs:c,exitCode:l.exitCode,signal:l.signal,timedOut:l.timedOut,stdoutBytes:l.stdoutBytes,stderrBytes:l.stderrBytes},r.profileOut),l}function Ft(e,t){e&&process.stderr.write(`[bench] ${t}
382
+ `}function sR(e,t,n,r){let i=he(t.subsystem)??n.split(/[.:]/,1)[0]??n,o=e.get(i)??{subsystem:i,events:0,totalDurationMs:0,spanNames:new Set,workloadIdentifiedEvents:0,workloadIdentifiedSpanNames:new Set,exactIdentifiedEvents:0,exactIdentifiedSpanNames:new Set};o.events+=1,o.totalDurationMs+=r,o.spanNames.add(n),he(t.subsystemWorkIdentity)&&(o.workloadIdentifiedEvents+=1,o.workloadIdentifiedSpanNames.add(n)),he(t.workIdentity)&&(o.exactIdentifiedEvents+=1,o.exactIdentifiedSpanNames.add(n)),e.set(i,o)}function aR(e,t,n,r,i){let o=he(t.subsystemWorkIdentity);if(!o||!i||t.workloadIdentityKind!=="published-project")return;let s=he(t.subsystem)??n.split(/[.:]/,1)[0]??n,a=JSON.stringify([n,o]),c=e.get(a)??{subsystem:s,spanName:n,subsystemWorkIdentity:o,observations:[]};c.observations.push({runId:i,command:he(t.command)??"unknown",durationMs:r}),e.set(a,c)}function cR(e){let t=new Map;for(let o of e.observations){let s=t.get(o.runId)??[];s.push(o),t.set(o.runId,s)}let n=[...t.values()];if(n.length<2)return null;let r=n[0],i=n.slice(1).flat();return{subsystem:e.subsystem,spanName:e.spanName,subsystemWorkIdentity:e.subsystemWorkIdentity,commands:[...new Set(e.observations.map(o=>o.command))].sort(),runCount:n.length,totalEvents:e.observations.length,firstRunEvents:r.length,laterRunEvents:i.length,totalDurationMs:Dt(e.observations.map(o=>o.durationMs)),firstRunMs:Dt(r.map(o=>o.durationMs)),laterRunMs:Dt(i.map(o=>o.durationMs))}}function lR(e){return{subsystem:e.subsystem,events:e.events,totalDurationMs:e.totalDurationMs,spanNames:[...e.spanNames].sort(),workloadIdentifiedEvents:e.workloadIdentifiedEvents,workloadIdentifiedSpanNames:e.workloadIdentifiedSpanNames.size,exactIdentifiedEvents:e.exactIdentifiedEvents,exactIdentifiedSpanNames:e.exactIdentifiedSpanNames.size}}function dR(e){let t=e.observations.filter(a=>a.outcome==="computed");if(t.length<2)return null;let n=new Map;for(let a of t){let c=n.get(a.runId)??[];c.push(a),n.set(a.runId,c)}let r=[...n.values()],i=Dt(r.flatMap(a=>a.slice(1).map(c=>c.durationMs))),o=Dt(r.slice(1).map(a=>a[0]?.durationMs??0)),s=[...new Set(e.observations.map(a=>a.command))].sort();return{spanName:e.spanName,workIdentity:e.workIdentity,commands:s,computations:t.length,runCount:r.length,repeatComputations:t.length-1,withinRunRepeats:t.length-r.length,crossRunRecomputes:Math.max(0,r.length-1),totalComputeMs:Dt(t.map(a=>a.durationMs)),firstComputeMs:t[0]?.durationMs??0,withinRunAvoidableMs:i,crossRunRecomputeMs:o,estimatedAvoidableMs:i+o,cacheHits:kr(e.observations,"cache-hit"),cacheMisses:kr(e.observations,"cache-miss"),reused:kr(e.observations,"reused"),skipped:kr(e.observations,"skipped")}}function uR(e){switch(e){case"computed":case"cache-hit":case"cache-miss":case"reused":case"skipped":return e;default:return null}}function kr(e,t){return e.filter(n=>n.outcome===t).length}function pR(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function he(e){return typeof e=="string"&&e.length>0?e:null}function Dt(e){return e.reduce((t,n)=>t+n,0)}var Yu={status:"experimental-composite",comparableAcrossLanguages:!1,scope:"completed-analyses-only",note:"The score summarizes analyses that completed under the attached capability matrix. It is not normalized across languages or frameworks and is not suitable for a public leaderboard."};function Xu(e,t){let n=mR(t);return{...e,warnings:[...e.warnings??[],Yu.note,...n],capabilities:t,scoreInterpretation:Yu}}function mR(e){return e.matrix.flatMap(t=>{let n=[t.indexing,t.sourceFacts,t.semantic,t.cleanupVerification].map(r=>/syntax only/i.test(r.reason)?`${r.label}=partial (syntax only)`:r.status==="available"?null:`${r.label}=${r.status}`).filter(r=>r!==null);return n.length===0?[]:[`${t.language} capability limits: ${n.join(", ")}. Unsupported analyses are not clean zeros.`]})}var xR=new Set(_a),RR=18e4,np=100*1024*1024,kR=new Set(Oo),wR=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],$R=[["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 CR(e){return e.filter(t=>xR.has(t))}async function rp(e){let t=G(e),n=Y(),r=me(n),i=Fe(n,r),o=b(t,"json");try{let s=CR(Ct(t,"language")),a=await At({projectRoot:n,languages:s.length>0?s:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:b(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,clojureConfigPath:r.indexer?.clojure?.configPath,skipIfUnchanged:!b(t,"force"),allowPartial:b(t,"allowPartial"),skipAutoInstall:process.env.SCIP_QUERY_SKIP_AUTO_INSTALL==="1",indexerConcurrency:U(t,"indexerConcurrency")??r.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"},...o?{onStatus:()=>{}}:{}});if(o){I("reindex",[],t,a);return}console.log(`${a.reused?"Reused":"Indexed"} ${a.languages.join(", ")} in ${(a.durationMs/1e3).toFixed(1)}s`)}catch(s){console.error(`error: ${s instanceof Error?s.message:s}`),process.exit(1)}}function ip(){let e=Y(),t=wt(e);try{let n=tr({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 op(e){let t=G(e),n=Y(),r=wt(n);try{let i=Ui({projectRoot:n,dbPath:r,tsconfig:w(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}; not-inserted identifier tokens: ${i.skippedReferences}; synthetic symbols: ${i.syntheticSymbols}.`),console.log(`Not inserted by reason: no definition ${i.skippedReferenceReasons["no-definition"]}; same-file definition ${i.skippedReferenceReasons["same-file-definition"]}; unindexed definition ${i.skippedReferenceReasons["unindexed-definition"]}; missing source ${i.skippedReferenceReasons["missing-source-file"]}; missing service script ${i.skippedReferenceReasons["missing-service-script"]}. Samples: ${i.skippedReferenceSamples.length} omitted, ${i.resolvedReferenceSamples.length} resolved.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}}function sp(e){let t=G(e);ce(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=na(n,{base:w(t,"base")}),o=ra(n,r,i.changedFiles,i.changedRanges);console.log(JSON.stringify(o))})}async function ap(e){let t=G(e);try{let n=await uc({base:w(t,"base")});if(b(t,"json")){I("diff-impact",[],t,n);return}pc(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function cp(e,t){let n=G(t),r=String(e).split(",").filter(i=>i.length>0);ce(i=>{let o=[];for(let c of r)Aa.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:w(n,"scope"),full:b(n,"full")},a=o.length===1?La(i,o[0],s):Da(i,o,s);console.log(JSON.stringify(a))})}async function lp(e){let t=G(e);if(b(t,"writeBaseline")||b(t,"baseline")){BR(t);return}try{let n=await Fn({scope:w(t,"scope"),full:b(t,"full"),json:b(t,"json")}),{projectRoot:r,config:i,dbPath:o}=Me(),s=Qe(ge(r,i),{hasIndexedGraph:ke(o)}),a=Xu(n,s);if(b(t,"json")){I("health",[],t,a);return}dc(a,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function dp(e){let t=G(e),n=Y(),r=U(t,"timeoutMs")??RR,i=b(t,"progress"),o=b(t,"profile"),s=w(t,"profileOut"),a={projectRoot:n,...OR(n),index:so(ke(wt(n))),commands:[]};b(t,"coldIndex")&&(Ft(i,"cold index started"),a.coldIndex=await PR(n),Ft(i,`cold index finished ${a.coldIndex.durationMs}ms`),Bt({type:"bench-index",phase:"cold-index",projectRoot:n,durationMs:a.coldIndex.durationMs,result:a.coldIndex.result,files:a.coldIndex.files,symbols:a.coldIndex.symbols},s),Ft(i,"warm index started"),a.warmIndex=await jR(n),Ft(i,`warm index finished ${a.warmIndex.durationMs}ms`),Bt({type:"bench-index",phase:"warm-index",projectRoot:n,durationMs:a.warmIndex.durationMs,result:a.warmIndex.result,files:a.warmIndex.files,symbols:a.warmIndex.symbols},s),a.index=so(ke(wt(n))));for(let c of AR(t))a.commands.push(DR(n,c,r,{progress:i,profile:o,profileOut:s}));if(b(t,"json")){I("bench",[],t,a);return}NR(a)}function up(e,t){let n=G(t),r=vR(String(e)),i=Ku(zu(r),{top:U(n,"top")??20});if(b(n,"json")){I("work-audit",[r],n,{profilePath:r,...i});return}process.stdout.write(Qu(i,r))}function pp(e){let t=G(e);ce(n=>{let r=n.config.projectRoot,i=w(t,"scope")??null,o=b(t,"full"),s=U(t,"limit")??200,a=Math.max(0,U(t,"maxMismatches")??10),c=qo(n).filter(k=>Ht(k.relativePath)).filter(k=>!n.isIgnored(k.relativePath)).sort(_R),l=i?c.filter(k=>k.relativePath.includes(i)):c,d=o?l:l.slice(0,s),p=et.now(),m=ds(n),f=Number((et.now()-p).toFixed(3)),g=et.now(),h=Wu(n),y=Number((et.now()-g).toFixed(3)),S=Gu(d,m,h),v={projectRoot:r,selection:{scope:i,full:o,limit:o?null:s,maxMismatchDetails:a,totalTypeScriptDefinitions:c.length,scopedDefinitions:l.length,comparedDefinitions:d.length},baseline:{provider:"ts-morph",createMs:f,availability:m.availability()},candidate:{provider:"tsserver",createMs:y,availability:h.availability()},comparison:{...S,mismatches:S.mismatches.slice(0,a)}};if(b(t,"json")){I("typescript-semantic-compare",[],t,v);return}MR(v)})}async function PR(e){let t=me(e),n=Fe(e,t),r=wr(n.dbPath),i=`${r}.bench-backup-${Date.now()}`;TR(r);let o=IR(r,i);try{let s=await mp(()=>At({projectRoot:e,languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench --cold-index"},onStatus:()=>{}}));return Zu(r,i,o,"discard-backup"),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...fp(e)}}catch(s){throw Zu(r,i,o,"restore-backup"),s}}var ao={existsSync:ke,readFileSync:fR,writeFileSync:bR,renameSync:gR,rmSync:hR,unlinkSync:yR};function co(e){return mt(wr(e),"bench-restore.json")}function TR(e,t=ao){let n=co(e);if(!t.existsSync(n))return!1;let r=ER(t.readFileSync(n,"utf8"));return r&&!t.existsSync(r.originalPath)&&t.existsSync(r.backupPath)&&t.renameSync(r.backupPath,r.originalPath),t.unlinkSync(n),!0}function IR(e,t,n=ao){return n.existsSync(e)?(n.writeFileSync(co(e),JSON.stringify({originalPath:e,backupPath:t})),n.renameSync(e,t),!0):!1}function Zu(e,t,n,r,i=ao){n&&r==="restore-backup"&&!i.existsSync(e)&&i.existsSync(t)?i.renameSync(t,e):n&&r==="discard-backup"&&i.rmSync(t,{recursive:!0,force:!0});let o=co(e);i.existsSync(o)&&i.unlinkSync(o)}function ER(e){try{let t=JSON.parse(e);return typeof t.originalPath=="string"&&typeof t.backupPath=="string"?{originalPath:t.originalPath,backupPath:t.backupPath}:null}catch{return null}}async function jR(e){let t=me(e),n=Fe(e,t),r=await mp(()=>At({projectRoot:e,languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench warm index"},onStatus:()=>{}}));return{durationMs:r.durationMs,result:r.value.reused?"reused":"rebuilt",languages:r.value.languages,...fp(e)}}async function mp(e){let t=et.now(),n=await e();return{durationMs:Math.round(et.now()-t),value:n}}function fp(e){return ke(wt(e))?ce(t=>{let n=vt(t);return{files:n.documents,symbols:n.symbols}}):{}}function AR(e){let t=Ct(e,"command");return t.length>0?t.map(LR).filter(n=>n.length>0):[...wR.map(n=>[...n]),...b(e,"includeHeavy")?$R.map(n=>[...n]):[]]}function LR(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function DR(e,t,n,r={}){let i=`scip-query ${t.join(" ")}`;Ft(r.progress,`${i} started`),Bt({type:"bench-command-start",command:i,projectRoot:e},r.profileOut);let o=et.now(),s={...r.profile?FR(i,r.profileOut):process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"},a=tp(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:np,timeout:n}),c=Math.round(et.now()-o),l={command:i,durationMs:c,exitCode:a.status,signal:a.signal,timedOut:a.error?.code==="ETIMEDOUT"||a.error?.name==="ETIMEDOUT",stdoutBytes:a.stdout?.length??0,stderrBytes:a.stderr?.length??0,...r.profileOut?{profilePath:r.profileOut}:{}};return Ft(r.progress,`${i} finished ${c}ms exit=${l.exitCode??l.signal??"unknown"}${l.timedOut?" timed-out":""}`),Bt({type:"bench-command-finish",command:i,projectRoot:e,durationMs:c,exitCode:l.exitCode,signal:l.signal,timedOut:l.timedOut,stdoutBytes:l.stdoutBytes,stderrBytes:l.stderrBytes},r.profileOut),l}function Ft(e,t){e&&process.stderr.write(`[bench] ${t}
383
383
  `)}function FR(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function OR(e){let t=tp("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:np});if(t.status!==0)return{repoFiles:null,sourceFiles:null};let n=t.stdout.split(`
384
384
  `).filter(Boolean);return{repoFiles:n.length,sourceFiles:n.filter(r=>kR.has(SR(r).toLowerCase())).length}}function NR(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, ${_e(e.index.indexSizeBytes)}`),e.coldIndex&&ep("Cold index",e.coldIndex),e.warmIndex&&ep("Warm index",e.warmIndex),console.log(`
385
385
  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 ep(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function MR(e){if(console.log("TypeScript semantic provider comparison"),console.log(`Project: ${e.projectRoot}`),console.log(`Definitions: ${e.selection.comparedDefinitions}/${e.selection.scopedDefinitions} compared`+(e.selection.scope?`, scope ${e.selection.scope}`:"")),console.log(`ts-morph: create ${e.baseline.createMs}ms, refs ${e.comparison.baselineMs}ms, refs ${e.comparison.baselineReferenceCount}`),console.log(`tsserver: create ${e.candidate.createMs}ms, refs ${e.comparison.candidateMs}ms, refs ${e.comparison.candidateReferenceCount}`),console.log(`Matches: ${e.comparison.matches}; mismatches: ${e.comparison.mismatchCount}; missing refs: ${e.comparison.missingReferenceCount}; extra refs: ${e.comparison.extraReferenceCount}`),e.comparison.mismatches.length!==0){console.log(`
386
- Mismatch samples:`);for(let t of e.comparison.mismatches)console.log(` ${t.symbol}`),console.log(` missing=${t.missing.length} extra=${t.extra.length}`)}}function _R(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||(e.startChar??0)-(t.startChar??0)||e.symbolId-t.symbolId}function qR(e){let t=w(e,"scope");ce(n=>{if(b(e,"writeBaseline")){let i=ua(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=pa(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 gp(){let e=Zn(),t=e.installed.length+e.alreadyLinked.length;console.log(`
386
+ Mismatch samples:`);for(let t of e.comparison.mismatches)console.log(` ${t.symbol}`),console.log(` missing=${t.missing.length} extra=${t.extra.length}`)}}function _R(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||(e.startChar??0)-(t.startChar??0)||e.symbolId-t.symbolId}function BR(e){let t=w(e,"scope");ce(n=>{if(b(e,"writeBaseline")){let i=ua(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=pa(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 gp(){let e=Zn(),t=e.installed.length+e.alreadyLinked.length;console.log(`
387
387
  ${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.pruned.length} pruned, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function hp(e){let t=G(e),n=Y(),r=Et(n,{shared:b(t,"shared"),remove:b(t,"remove"),force:b(t,"force")});if(b(t,"json")){I("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: ${o}`);for(let o of r.gitExcluded)console.log(` local: ${o} (excluded through .git/info/exclude)`);for(let o of r.warnings)console.log(` warning: ${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(`
388
388
  Checkout-local scip-query hooks are configured for this clone and must not be committed.`),console.log("Review new or changed hooks in Codex/Claude Code with /hooks before they run.")):console.log(`
389
389
  No project-local hook config was written.`)}function yp(){let e=!1;Xt()?console.log("scip CLI: installed"):(gi(),e=!0);let t=Y(),n=me(t),r=ge(t,n);if(r.languages.length===0){console.log(`
390
390
  No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
391
391
  Detected languages: ${r.languages.join(", ")}`),console.log(`
392
392
  Indexer readiness:`);for(let o of r.indexers){let s=o.runnable?" OK":o.installed?" WARN":" MISSING",a=o.resolvedBinary?` (${o.resolvedBinary})`:"";console.log(`${s} ${o.language}: ${o.binaryLabel}${a}`),o.note&&console.log(` ${o.note}`),!o.installed&&o.installUrl&&console.log(` install: ${o.installUrl}`),o.runnable||(e=!0)}let i=Fp(r);i.length>0&&console.log(`
393
- Semantic provider readiness:`);for(let o of i){let s=o.available?" OK":o.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${o.language}: ${QR(o)}${Op(o)}`),o.reason&&console.log(` ${o.reason}`)}process.exitCode=e?1:0}function bp(e){vp(e,"capabilities")}function Sp(e){b(G(e),"json")||console.error('note: capability-matrix is deprecated; use "scip-query capabilities --matrix".'),vp(e,"capability-matrix")}function vp(e,t){let n=G(e),{projectRoot:r,config:i,paths:o,dbPath:s}=Me(),a=ge(r,i),c=Pe(r,i,o),l=Qe(a,{hasIndexedGraph:ke(s)&&c.state!=="missing"});if(b(n,"json")){I(t,[],n,l);return}lo(l)}function xp(){let e=Y(),t=rt(e),n=qa(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Rp(e){let t=G(e),n=Y(),r=me(n),i=kt(r,{projectRoot:n});if(b(t,"json"))I("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 kp(e,t){let n=G(t),r=w(n,"reason");if(!r||r.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let i=ga(Y(),{id:String(e),check:w(n,"check"),file:w(n,"file"),reason:r,expiresAt:w(n,"expiresAt")});if(b(n,"json")){I("suppress",[String(e)],n,i);return}console.log(`Suppression written to ${i.path}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exitCode=1}}function wp(e){let t=G(e),n=Date.now(),r=w(t,"since"),i;if(r){let y=bu(r,n);if(y===null){console.error(`error: could not parse --since "${r}" (use 30d, 12w, or an ISO date).`),process.exitCode=1;return}i=y}let o=Y(),s=Gn(o),a=yu(s,{sinceMs:i,check:w(t,"check")});if(b(t,"json")){I("effectiveness",[],t,a);return}if(a.checks.length===0){console.log(s.length===0?`No outcome events recorded yet (${mt(Wn,"*.json")} is missing or empty). Events accrue as diff-gate runs; commit the event files so history is shared.`:"No findings match the requested window/check.");return}let c=["check","caught","fixed","suppressed","open","moved","unverified","precision","median-days-to-fix"],l=a.checks.map(y=>[y.check,String(y.caught),String(y.fixed),String(y.suppressed),String(y.open),String(y.moved),String(y.unverified),y.precision===null?"-":`${Math.round(y.precision*100)}%`,y.medianDaysToFix===null?"-":y.medianDaysToFix.toFixed(1)]),d=c.map((y,S)=>Math.max(y.length,...l.map(v=>v[S].length))),p=y=>y.map((S,v)=>S.padEnd(d[v])).join(" ");console.log(p(c));for(let y of l)console.log(p(y));let m=a.checks.reduce((y,S)=>y+S.fixed,0),f=a.checks.reduce((y,S)=>y+S.suppressed,0),g=a.checks.reduce((y,S)=>y+S.unverified,0),h=m+f;h>0?console.log(`
393
+ Semantic provider readiness:`);for(let o of i){let s=o.available?" OK":o.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${o.language}: ${QR(o)}${Op(o)}`),o.reason&&console.log(` ${o.reason}`)}process.exitCode=e?1:0}function bp(e){vp(e,"capabilities")}function Sp(e){b(G(e),"json")||console.error('note: capability-matrix is deprecated; use "scip-query capabilities --matrix".'),vp(e,"capability-matrix")}function vp(e,t){let n=G(e),{projectRoot:r,config:i,paths:o,dbPath:s}=Me(),a=ge(r,i),c=Pe(r,i,o),l=Qe(a,{hasIndexedGraph:ke(s)&&c.state!=="missing"});if(b(n,"json")){I(t,[],n,l);return}lo(l)}function xp(){let e=Y(),t=rt(e),n=Ba(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Rp(e){let t=G(e),n=Y(),r=me(n),i=kt(r,{projectRoot:n});if(b(t,"json"))I("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 kp(e,t){let n=G(t),r=w(n,"reason");if(!r||r.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let i=ga(Y(),{id:String(e),check:w(n,"check"),file:w(n,"file"),reason:r,expiresAt:w(n,"expiresAt")});if(b(n,"json")){I("suppress",[String(e)],n,i);return}console.log(`Suppression written to ${i.path}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exitCode=1}}function wp(e){let t=G(e),n=Date.now(),r=w(t,"since"),i;if(r){let y=bu(r,n);if(y===null){console.error(`error: could not parse --since "${r}" (use 30d, 12w, or an ISO date).`),process.exitCode=1;return}i=y}let o=Y(),s=Gn(o),a=yu(s,{sinceMs:i,check:w(t,"check")});if(b(t,"json")){I("effectiveness",[],t,a);return}if(a.checks.length===0){console.log(s.length===0?`No outcome events recorded yet (${mt(Wn,"*.json")} is missing or empty). Events accrue as diff-gate runs; commit the event files so history is shared.`:"No findings match the requested window/check.");return}let c=["check","caught","fixed","suppressed","open","moved","unverified","precision","median-days-to-fix"],l=a.checks.map(y=>[y.check,String(y.caught),String(y.fixed),String(y.suppressed),String(y.open),String(y.moved),String(y.unverified),y.precision===null?"-":`${Math.round(y.precision*100)}%`,y.medianDaysToFix===null?"-":y.medianDaysToFix.toFixed(1)]),d=c.map((y,S)=>Math.max(y.length,...l.map(v=>v[S].length))),p=y=>y.map((S,v)=>S.padEnd(d[v])).join(" ");console.log(p(c));for(let y of l)console.log(p(y));let m=a.checks.reduce((y,S)=>y+S.fixed,0),f=a.checks.reduce((y,S)=>y+S.suppressed,0),g=a.checks.reduce((y,S)=>y+S.unverified,0),h=m+f;h>0?console.log(`
394
394
  ${m} finding(s) verified fixed against a stable comparison base, ${f} suppressed, ${g} disappeared without comparable evidence \u2014 overall precision ${Math.round(m/h*100)}%.`):g>0&&console.log(`
395
- ${g} finding(s) disappeared without comparable comparison-base evidence; precision is not available.`)}function $p(e){let t=G(e),{report:n,hasIndexerProblems:r,hasErrors:i}=Cp("doctor");b(t,"json")?I("doctor",[],t,n):UR(n,r),process.exitCode=i?1:0}function Cp(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=Me(),o=kt(n,{projectRoot:t}),s=ge(t,n),a=Pe(t,n,r),c=ke(i),l=Qe(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=Pc(t,n,r),p=s.indexers.some(g=>!g.runnable),m=o.some(g=>g.level==="error")||p||a.state==="missing"||a.state==="stale",f=o.some(g=>g.level==="error")||p||a.state==="missing";return{report:{command:e,projectRoot:t,dbPath:i,configuredDbPath:r.dbPath,exists:c,configDiagnostics:o,readiness:s,freshness:a,capabilities:l,sharedCache:d,ok:!m},hasIndexerProblems:p,hasErrors:f}}function Pp(e){let t=G(e),n=Y(),r=qn(n,{gitHook:b(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(`
396
- 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 Tp(e){let t=G(e);try{let n={gitHook:b(t,"gitHook"),noHooks:b(t,"noHooks")||t.hooks===!1,dossierDir:w(t,"dossierDir"),runHealth:b(t,"yes")?!1:t.health!==!1,installSkills:t.skills!==!1,installAstParsers:t.parsers!==!1,...b(t,"yes")?{automaticRefresh:!0}:{}},r=b(t,"json"),i=!r&&!b(t,"yes")&&process.stdin.isTTY&&process.stdout.isTTY;(b(t,"guided")||i)&&(n=await BR(n,{json:b(t,"json")})),r||(n.onStatus=s=>console.log(` ${s}`));let o=await Lu(n);b(t,"json")?I("setup",[],t,o):Du(o),process.exitCode=o.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function BR(e,t){let{projectRoot:n,config:r}=Me(),i=ge(n,r),o=Au({files:VR(n),watchEnabled:Ce(r).enabled,readiness:i}),s=i.languages.map(g=>({id:`language:${g}`,scope:"project",label:`Index ${g}`,reason:"Detected in this project.",selected:!0})),a=o.actions.map(g=>({id:g.id,scope:g.scope==="repository"?"project":g.scope,label:g.label,reason:g.reason,selected:g.recommended})),c=to(i.languages);a.push({id:"install-agent-skills",scope:"user",label:"Install agent skills",reason:"Makes scip-query workflows available to local agents.",selected:!0},...c.length>0?[{id:"install-ast-parsers",scope:"user",label:`Install or repair AST parsers (${c.join(", ")})`,reason:"Installs the Tree-sitter runtime and grammars used for source-level analysis.",selected:!0}]:[],{id:"run-health-analysis",scope:"analysis",label:"Run full health analysis and write dossier",reason:"Optional and can take much longer than indexing.",selected:!1});let l=!t.json&&process.stdin.isTTY&&process.stdout.isTTY,d=l?await Fu([...s,...a]):new Set([...HR(o.actions),...s.map(g=>g.id)]);l&&WR(o.actions,d);let p=d.has("create-agent-guidance")||d.has("update-agent-guidance"),m=o.actions.some(g=>g.id==="enable-automatic-refresh"),f=o.actions.some(g=>g.id==="install-indexers");return{...e,...m?{automaticRefresh:d.has("enable-automatic-refresh")}:{},noHooks:e.noHooks||o.actions.some(g=>g.id==="install-project-hooks")&&!d.has("install-project-hooks"),noAgentGuidance:!p,...f?{installIndexers:d.has("install-indexers")}:{},languages:i.languages.filter(g=>d.has(`language:${g}`)),installSkills:d.has("install-agent-skills"),installAstParsers:d.has("install-ast-parsers"),runHealth:d.has("run-health-analysis")}}function VR(e){return{agentsMd:ke(mt(e,"AGENTS.md")),claudeMd:ke(mt(e,"CLAUDE.md")),codexHooks:ke(mt(e,".codex","hooks.json")),claudeSettings:ke(mt(e,".claude","settings.local.json"))}}function HR(e){return new Set([...e.filter(t=>t.recommended).map(t=>t.id),"install-agent-skills","install-ast-parsers"])}function WR(e,t){console.log(""),console.log("Selected setup changes:");for(let n of["repository","checkout","user"]){let r=e.filter(o=>o.scope===n&&t.has(o.id)).map(o=>o.label);console.log(` ${n} (${n==="repository"?"commit these shared project changes":n==="checkout"?"keep these local to this checkout":"changes this machine or user environment"}): ${r.length>0?r.join(", "):"none"}`)}}function Ip(e){let t=G(e),n=Y(),r=Mu(n,{force:b(t,"force"),dryRun:b(t,"dryRun")});if(b(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 Ep(e){let t=G(e);if(b(t,"global")&&b(t,"project")){console.error("error: choose either --global or --project, not both."),process.exitCode=1;return}let n=_u({projectRoot:Y(),global:b(t,"global"),project:b(t,"project"),dryRun:b(t,"dryRun")});if(b(t,"json")){I("uninstall",[],t,n);return}let r=n.dryRun?"would ":"";if(n.global){for(let o of n.global.removed)console.log(` ${r}remove: ${o}`);for(let o of n.global.left)console.log(` left: ${o}`);for(let o of n.global.skipped)console.log(` skip: ${o}`)}if(n.project){for(let o of n.project.hooks.removed)console.log(` ${r}remove: ${o}`);for(let o of n.project.agentSetup.removed)console.log(` ${r}remove: ${o}`);for(let o of n.project.agentSetup.unchanged)console.log(` ok: ${o} (no managed block)`);for(let o of n.project.hooks.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);for(let o of n.project.agentSetup.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);for(let o of n.project.left)console.log(` left: ${o}`)}(n.global?.removed.length??0)+(n.project?.hooks.removed.length??0)+(n.project?.agentSetup.removed.length??0)===0&&console.log(n.dryRun?"No scip-query-owned files would be removed.":"No scip-query-owned files removed.")}function jp(e){let t=G(e),n=Y(),r=me(n),i=U(t,"debounce"),o=U(t,"cooldown"),s=U(t,"gitPoll"),a=U(t,"idleTimeout"),c=b(t,"daemon"),l=b(t,"status"),d=b(t,"stop"),p=b(t,"json"),m=[c,l,d].filter(Boolean).length;if(m>1){console.error("error: choose only one of --daemon, --status, or --stop."),process.exitCode=1;return}if(p&&m===0){console.error("error: --json requires --daemon, --status, or --stop."),process.exitCode=1;return}let f=[["--debounce",i,!1],["--cooldown",o,!0],["--git-poll",s,!1],["--idle-timeout",a,!0]].find(([,R,D])=>R!==void 0&&(!Number.isInteger(R)||(D?Number(R)<0:Number(R)<=0)));if(f){console.error(`error: ${f[0]} requires ${f[2]?"a non-negative":"a positive"} integer.`),process.exitCode=1;return}let g={...i===void 0?{}:{debounceMs:i},...o===void 0?{}:{cooldownMs:o},...s===void 0?{}:{gitPollMs:s},...a===void 0?{}:{idleTimeoutMs:a}};i&&((r.watch??={}).debounceMs=i),o!==void 0&&((r.watch??={}).cooldownMs=o),s&&((r.watch??={}).gitPollMs=s),a!==void 0&&((r.watch??={}).idleTimeoutMs=a);let h=Ce(r);r.watch=h;let y=Fe(n,r),S={projectRoot:n,cacheDir:y.cacheDir,cliVersion:Ne,watchOverrides:g};if(l){let R=Ap(Qr(S),h.enabled);p?I("watch",[],t,R):Lp(R);return}if(d){try{let R=wc(S);p?I("watch",[],t,R):console.log(R.disposition==="stopped"?`Stopped watch service${R.pid?` (pid ${R.pid})`:""}.`:"Watch service is already stopped.")}catch(R){console.error(`error: ${R instanceof Error?R.message:String(R)}`),process.exitCode=1}return}if(!h.enabled){console.error('error: watch mode is disabled. Set "watch.enabled": true in .scipquery.json to start it.'),process.exitCode=1;return}if(c){try{let R=Nn(S);p?I("watch",[],t,R):console.log(`${R.disposition==="started"?"Started":"Reused"} watch service for ${n} (pid ${R.state.pid}).`)}catch(R){console.error(`error: ${R instanceof Error?R.message:String(R)}`),process.exitCode=1}return}let v=Cc(mt(wr(y.dbPath),ns),n);if(!v.acquired){console.error(v.message),process.exitCode=1;return}let k=new br({projectRoot:n,config:r,languages:r.languages,onStatus:R=>{process.stdout.write(`\r\x1B[K${Jr(R)}`)},onReindexComplete:R=>(console.log(`
395
+ ${g} finding(s) disappeared without comparable comparison-base evidence; precision is not available.`)}function $p(e){let t=G(e),{report:n,hasIndexerProblems:r,hasErrors:i}=Cp("doctor");b(t,"json")?I("doctor",[],t,n):UR(n,r),process.exitCode=i?1:0}function Cp(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=Me(),o=kt(n,{projectRoot:t}),s=ge(t,n),a=Pe(t,n,r),c=ke(i),l=Qe(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=Pc(t,n,r),p=s.indexers.some(g=>!g.runnable),m=o.some(g=>g.level==="error")||p||a.state==="missing"||a.state==="stale",f=o.some(g=>g.level==="error")||p||a.state==="missing";return{report:{command:e,projectRoot:t,dbPath:i,configuredDbPath:r.dbPath,exists:c,configDiagnostics:o,readiness:s,freshness:a,capabilities:l,sharedCache:d,ok:!m},hasIndexerProblems:p,hasErrors:f}}function Pp(e){let t=G(e),n=Y(),r=Bn(n,{gitHook:b(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(`
396
+ 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 Tp(e){let t=G(e);try{let n={gitHook:b(t,"gitHook"),noHooks:b(t,"noHooks")||t.hooks===!1,dossierDir:w(t,"dossierDir"),runHealth:b(t,"yes")?!1:t.health!==!1,installSkills:t.skills!==!1,installAstParsers:t.parsers!==!1,...b(t,"yes")?{automaticRefresh:!0}:{}},r=b(t,"json"),i=!r&&!b(t,"yes")&&process.stdin.isTTY&&process.stdout.isTTY;(b(t,"guided")||i)&&(n=await qR(n,{json:b(t,"json")})),r||(n.onStatus=s=>console.log(` ${s}`));let o=await Lu(n);b(t,"json")?I("setup",[],t,o):Du(o),process.exitCode=o.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function qR(e,t){let{projectRoot:n,config:r}=Me(),i=ge(n,r),o=Au({files:VR(n),watchEnabled:Ce(r).enabled,readiness:i}),s=i.languages.map(g=>({id:`language:${g}`,scope:"project",label:`Index ${g}`,reason:"Detected in this project.",selected:!0})),a=o.actions.map(g=>({id:g.id,scope:g.scope==="repository"?"project":g.scope,label:g.label,reason:g.reason,selected:g.recommended})),c=to(i.languages);a.push({id:"install-agent-skills",scope:"user",label:"Install agent skills",reason:"Makes scip-query workflows available to local agents.",selected:!0},...c.length>0?[{id:"install-ast-parsers",scope:"user",label:`Install or repair AST parsers (${c.join(", ")})`,reason:"Installs the Tree-sitter runtime and grammars used for source-level analysis.",selected:!0}]:[],{id:"run-health-analysis",scope:"analysis",label:"Run full health analysis and write dossier",reason:"Optional and can take much longer than indexing.",selected:!1});let l=!t.json&&process.stdin.isTTY&&process.stdout.isTTY,d=l?await Fu([...s,...a]):new Set([...HR(o.actions),...s.map(g=>g.id)]);l&&WR(o.actions,d);let p=d.has("create-agent-guidance")||d.has("update-agent-guidance"),m=o.actions.some(g=>g.id==="enable-automatic-refresh"),f=o.actions.some(g=>g.id==="install-indexers");return{...e,...m?{automaticRefresh:d.has("enable-automatic-refresh")}:{},noHooks:e.noHooks||o.actions.some(g=>g.id==="install-project-hooks")&&!d.has("install-project-hooks"),noAgentGuidance:!p,...f?{installIndexers:d.has("install-indexers")}:{},languages:i.languages.filter(g=>d.has(`language:${g}`)),installSkills:d.has("install-agent-skills"),installAstParsers:d.has("install-ast-parsers"),runHealth:d.has("run-health-analysis")}}function VR(e){return{agentsMd:ke(mt(e,"AGENTS.md")),claudeMd:ke(mt(e,"CLAUDE.md")),codexHooks:ke(mt(e,".codex","hooks.json")),claudeSettings:ke(mt(e,".claude","settings.local.json"))}}function HR(e){return new Set([...e.filter(t=>t.recommended).map(t=>t.id),"install-agent-skills","install-ast-parsers"])}function WR(e,t){console.log(""),console.log("Selected setup changes:");for(let n of["repository","checkout","user"]){let r=e.filter(o=>o.scope===n&&t.has(o.id)).map(o=>o.label);console.log(` ${n} (${n==="repository"?"commit these shared project changes":n==="checkout"?"keep these local to this checkout":"changes this machine or user environment"}): ${r.length>0?r.join(", "):"none"}`)}}function Ip(e){let t=G(e),n=Y(),r=Mu(n,{force:b(t,"force"),dryRun:b(t,"dryRun")});if(b(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 Ep(e){let t=G(e);if(b(t,"global")&&b(t,"project")){console.error("error: choose either --global or --project, not both."),process.exitCode=1;return}let n=_u({projectRoot:Y(),global:b(t,"global"),project:b(t,"project"),dryRun:b(t,"dryRun")});if(b(t,"json")){I("uninstall",[],t,n);return}let r=n.dryRun?"would ":"";if(n.global){for(let o of n.global.removed)console.log(` ${r}remove: ${o}`);for(let o of n.global.left)console.log(` left: ${o}`);for(let o of n.global.skipped)console.log(` skip: ${o}`)}if(n.project){for(let o of n.project.hooks.removed)console.log(` ${r}remove: ${o}`);for(let o of n.project.agentSetup.removed)console.log(` ${r}remove: ${o}`);for(let o of n.project.agentSetup.unchanged)console.log(` ok: ${o} (no managed block)`);for(let o of n.project.hooks.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);for(let o of n.project.agentSetup.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);for(let o of n.project.left)console.log(` left: ${o}`)}(n.global?.removed.length??0)+(n.project?.hooks.removed.length??0)+(n.project?.agentSetup.removed.length??0)===0&&console.log(n.dryRun?"No scip-query-owned files would be removed.":"No scip-query-owned files removed.")}function jp(e){let t=G(e),n=Y(),r=me(n),i=U(t,"debounce"),o=U(t,"cooldown"),s=U(t,"gitPoll"),a=U(t,"idleTimeout"),c=b(t,"daemon"),l=b(t,"status"),d=b(t,"stop"),p=b(t,"json"),m=[c,l,d].filter(Boolean).length;if(m>1){console.error("error: choose only one of --daemon, --status, or --stop."),process.exitCode=1;return}if(p&&m===0){console.error("error: --json requires --daemon, --status, or --stop."),process.exitCode=1;return}let f=[["--debounce",i,!1],["--cooldown",o,!0],["--git-poll",s,!1],["--idle-timeout",a,!0]].find(([,R,D])=>R!==void 0&&(!Number.isInteger(R)||(D?Number(R)<0:Number(R)<=0)));if(f){console.error(`error: ${f[0]} requires ${f[2]?"a non-negative":"a positive"} integer.`),process.exitCode=1;return}let g={...i===void 0?{}:{debounceMs:i},...o===void 0?{}:{cooldownMs:o},...s===void 0?{}:{gitPollMs:s},...a===void 0?{}:{idleTimeoutMs:a}};i&&((r.watch??={}).debounceMs=i),o!==void 0&&((r.watch??={}).cooldownMs=o),s&&((r.watch??={}).gitPollMs=s),a!==void 0&&((r.watch??={}).idleTimeoutMs=a);let h=Ce(r);r.watch=h;let y=Fe(n,r),S={projectRoot:n,cacheDir:y.cacheDir,cliVersion:Ne,watchOverrides:g};if(l){let R=Ap(Qr(S),h.enabled);p?I("watch",[],t,R):Lp(R);return}if(d){try{let R=wc(S);p?I("watch",[],t,R):console.log(R.disposition==="stopped"?`Stopped watch service${R.pid?` (pid ${R.pid})`:""}.`:"Watch service is already stopped.")}catch(R){console.error(`error: ${R instanceof Error?R.message:String(R)}`),process.exitCode=1}return}if(!h.enabled){console.error('error: watch mode is disabled. Set "watch.enabled": true in .scipquery.json to start it.'),process.exitCode=1;return}if(c){try{let R=Nn(S);p?I("watch",[],t,R):console.log(`${R.disposition==="started"?"Started":"Reused"} watch service for ${n} (pid ${R.state.pid}).`)}catch(R){console.error(`error: ${R instanceof Error?R.message:String(R)}`),process.exitCode=1}return}let v=Cc(mt(wr(y.dbPath),ns),n);if(!v.acquired){console.error(v.message),process.exitCode=1;return}let k=new br({projectRoot:n,config:r,languages:r.languages,onStatus:R=>{process.stdout.write(`\r\x1B[K${Jr(R)}`)},onReindexComplete:R=>(console.log(`
397
397
  Reindex complete in ${(R/1e3).toFixed(1)}s`),Pe(n,r,y).state==="fresh"),onRefreshSuppressed:R=>{ed(y.dbPath,R),console.log(`
398
398
  Skipped redundant refresh; the completed index already includes the queued changes.`)},onError:R=>{console.error(`
399
399
  Watch error: ${R.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${h.debounceMs}ms | Cooldown: ${h.cooldownMs}ms | Git poll: ${h.gitPollMs}ms`),console.log(`Press Ctrl+C to stop.
400
400
  `),k.start(),process.on("SIGINT",()=>{k.stop(),v.release(),console.log(`
401
401
  Stopped.`),process.exit(0)}),process.once("exit",v.release)}function Ap(e,t=!0){let{classification:n}=e;switch(n.kind){case"stopped":return e.lockIsLive&&e.lock?{enabled:t,state:"running",mode:"foreground-or-starting",pid:e.lock.pid,projectRoot:e.identity.projectRoot,worktreeId:e.identity.worktreeId,startedAt:e.lock.startedAt}:{enabled:t,state:"stopped",mode:"none"};case"live":return{enabled:t,state:"running",mode:"daemon",pid:n.state.pid,projectRoot:n.state.projectRoot,worktreeId:n.state.worktreeId,startedAt:n.state.startedAt,heartbeatAt:n.state.heartbeatAt,lastActivityAt:n.state.lastActivityAt,idleDeadlineAt:n.state.idleDeadlineAt,watcher:n.state.watcher,indexGeneration:n.state.indexGeneration,lastRefresh:n.state.lastRefresh,lastError:n.state.lastError,reindexActivity:n.state.reindexActivity,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};case"stale":case"incompatible":return{enabled:t,state:n.kind,mode:"daemon",reason:n.reason,pid:n.state.pid,projectRoot:n.state.projectRoot,worktreeId:n.state.worktreeId,heartbeatAt:n.state.heartbeatAt,watcher:n.state.watcher,indexGeneration:n.state.indexGeneration,lastRefresh:n.state.lastRefresh,lastError:n.state.lastError,reindexActivity:n.state.reindexActivity,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};default:return GR(n)}}function Lp(e){if(e.state==="stopped"){console.log(`Watch service: stopped${e.enabled?"":" (disabled)"}`);return}let t="pid"in e?` (pid ${e.pid})`:"";if(console.log(`Watch service: ${e.state} [${e.mode}]${t}`),"projectRoot"in e&&e.projectRoot){let n="worktreeId"in e&&e.worktreeId?` [${e.worktreeId.slice(0,12)}]`:"";console.log(`Worktree: ${e.projectRoot}${n}`)}if("watcher"in e&&e.watcher&&console.log(`Watcher: ${Jr(e.watcher)}`),"indexGeneration"in e&&e.indexGeneration&&console.log(`Index generation: ${e.indexGeneration.slice(0,12)}`),"idleDeadlineAt"in e&&e.idleDeadlineAt&&console.log(`Idle exit: ${e.idleDeadlineAt}`),"reason"in e&&console.log(`Reason: ${e.reason}`),"lastError"in e&&e.lastError&&console.log(`Last error: ${e.lastError.message}`),"reindexActivity"in e&&e.reindexActivity){let n=e.reindexActivity;console.log(`Reindex activity (24h): ${n.runs} run(s) (${n.rebuilt} rebuilt, ${n.reused} reused, ${n.failed} failed), ${n.suppressed} redundant refresh(es) suppressed, ${_e(n.estimatedLogicalOutputBytes)} estimated logical output`)}if("typescriptSemantic"in e&&e.typescriptSemantic){let n=e.typescriptSemantic;console.log(`TypeScript semantics: ${n.state} (${n.projectsCreated} Projects, ${n.requests} requests)`)}if("typescriptIndex"in e&&e.typescriptIndex){let n=e.typescriptIndex;console.log(`TypeScript index: ${n.state} (${n.initializations} warmups, ${n.programUpdates} updates, ${n.requests} requests)`)}}function GR(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function Dp(e){let t=G(e),{report:n}=Cp("status"),r=Ce(me(n.projectRoot)).enabled,i=Ap(Qr({projectRoot:n.projectRoot,cacheDir:wr(n.configuredDbPath),cliVersion:Ne}),r),o=Ml(n.dbPath),s=it(n.dbPath,n.freshness.metaPath),a=Pn(n.projectRoot,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION);if(b(t,"json")){I("status",[],t,{...n,affectedSetShadow:o,sqliteGeneration:s,rustSemanticSession:a,watchService:i,stats:so(n.exists)});return}JR(n,{affectedSetShadow:o,capabilities:b(t,"capabilities"),sqliteGeneration:s,rustSemanticSession:a,watchService:i})}function UR(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})`:""}`),lo(e.capabilities)}function JR(e,t){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)`);for(let n of Fp(e.readiness)){let r=n.available?"available":n.dependencyAvailable?"fallback":"unavailable",i=n.language==="typescript"?"TS sem:":`${n.language} sem:`;console.log(`${i.padEnd(9)}${r}${Op(n)}`),n.reason&&console.log(`${n.language} note: ${n.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: ${YR(e.freshness.lastRefresh)}`),Lp(t.watchService),zR(e.sharedCache),console.log(`Rust sess: ${t.rustSemanticSession.transport}/${t.rustSemanticSession.state} (${t.rustSemanticSession.source}; worker fallback; opt out with ${t.rustSemanticSession.optOut})`),t.rustSemanticSession.valid||console.log("Rust note: invalid durable-session value; using worker fallback"),KR(t.sqliteGeneration),console.log(`Shadow: ${_l(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),XR(e.exists),t.capabilities&&(console.log(""),lo(e.capabilities))}function zR(e){if(e.state!=="managed"){console.log(`Shared: ${e.state}${e.reason?` (${e.reason})`:""}`);return}let t=e.activeGenerationId?.slice(0,12)??"none",n=e.lastAction??"none";console.log(`Shared: ${n}, active ${t}, ${e.generations} generation(s), ${_e(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${_e(e.unreferencedBytes)}), ${e.temporaryGenerations} temporary`),e.cleanup?.kind==="swept"&&console.log(`Cache GC: ${e.cleanup.deletedWorktrees??0} worktree(s), ${e.cleanup.deletedGenerations??0} generation(s), ${_e(e.cleanup.deletedBytes??0)} removed`)}function KR(e){if(e.state==="legacy"){console.log("DB gen: legacy (no generation record)");return}if(e.state==="invalid"){console.log(`DB gen: invalid (${e.reason})`);return}let t=e.generation.publication,n=t?.mode??"unknown",r=t?[t.affectedDocumentCount===void 0?null:`${t.affectedDocumentCount} affected`,t.changedDocumentCount===void 0?null:`${t.changedDocumentCount} changed`,t.producerDurationMs===void 0?null:`${t.producerDurationMs.toFixed(0)}ms producer`,`${t.converterDurationMs.toFixed(0)}ms convert`,t.patchDurationMs===void 0?null:`${t.patchDurationMs.toFixed(0)}ms patch`,`${t.scipCompanion??"current"} SCIP companion`].filter(i=>i!==null).join(", "):"no publication metrics";console.log(`DB gen: ${e.state} ${e.generation.currentGeneration.slice(0,12)} (${n}; ${r})`),e.generation.previousGeneration&&console.log(`Recovery: ${e.generation.previousGeneration.generationIdentity.slice(0,12)} at ${e.generation.previousGeneration.databasePath}`),t?.fallbackReason&&console.log(`DB fallback: ${t.fallbackReason}`),e.reason&&console.log(`DB note: ${e.reason}`)}function Fp(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function QR(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function Op(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function YR(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 so(e){if(e)return ce(t=>{let n=vt(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function XR(e){e&&ce(t=>{let n=vt(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${_e(n.indexSizeBytes)}`),n.lastBuilt){let r=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${r}s ago`)}})}function lo(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(`
402
- 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 cn(e){return{...e,options:P(e.options)}}function Ee({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,...a}){let c=cn(a);return{...c,renderShape:"list",handler:fc({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s})}}function $r({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c,...l}){let d=cn(l);return{...d,renderShape:"table",handler:gc({commandName:d.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c})}}function Np({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a,...c}){let l=cn(c);return{...l,renderShape:"grouped-by-file",handler:hc({commandName:l.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a})}}function Mp({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=cn(a);return{...c,renderShape:"sectioned-report",handler:yc({commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}function Cr({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=cn(a);return{...c,budget:c.budget??"semantic",renderShape:"sectioned-report",handler:bc(c.id,{commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}import{existsSync as Ek,mkdirSync as jk,writeFileSync as Ak}from"fs";import{dirname as Lk,relative as Dk}from"path";import{existsSync as Je,readdirSync as ik,readFileSync as ft}from"fs";import{basename as ok,dirname as Gp,isAbsolute as Up,join as sk,relative as ak,resolve as ln,sep as ck}from"path";import{spawnSync as ek}from"child_process";import{dirname as tk}from"path";function qp(e){let n=(e.spawnSync??ek)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:tk(e.specPath),maxBuffer:1024*1024*32});if(n.status!==0)return null;let r=n.stdout??"";return r.includes("<?xml")?r:null}function Bp(e){let t=rk(e),n=new Map,r=new Map,i=[],o=new Map;for(let a of t)a.type==="OpDeclNode"&&a.kind===3&&a.uniquename?n.set(a.uid,a.uniquename):a.type==="BuiltInKind"&&a.uniquename?r.set(a.uid,a.uniquename):a.type==="UserDefinedOpKind"&&a.uniquename&&(i.push(a),o.set(a.uid,a));let s=[];for(let a of i){let c=Vp(a.block,n,r,o,a.filename,new Set([a.uid]),0);s.push({name:a.uniquename,reads:c.reads,writes:c.writes})}return{modelParse:"sany",variables:[...n.values()].sort(),operators:i.map(a=>a.uniquename).sort(),actions:s}}var nk=8;function rk(e){let t=[],n=/<entry>\s*<UID>(\d+)<\/UID>\s*<(\w+)>/g;for(let r of e.matchAll(n)){let i=r.index,o=e.indexOf("</entry>",i),s=e.slice(i,o<0?e.length:o),a=uo(s,"uniquename"),c=uo(s,"kind"),l=uo(s,"filename");t.push({uid:r[1],type:r[2],uniquename:a===null?null:_p(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:_p(l),block:s})}return t}function Vp(e,t,n,r,i,o,s){let a=new Set,c=new Set,l=[...e.matchAll(/<(\w+Ref)>\s*<UID>(\d+)<\/UID>/g)],d="read";for(let[,p,m]of l){if(p==="BuiltInKindRef"){let f=n.get(m)??"";f==="'"?d="write-next":f==="UNCHANGED"?d="unchanged-run":d==="unchanged-run"&&f==="$Tuple"||d!=="write-next"&&(d="read");continue}if(p==="OpDeclNodeRef"){let f=t.get(m);if(!f)continue;d==="write-next"?(c.add(f),d="read"):d==="unchanged-run"||a.add(f);continue}if(p==="UserDefinedOpKindRef"){d==="unchanged-run"&&(d="read");let f=r.get(m);if(f&&s<nk&&!o.has(f.uid)&&f.filename===i){let g=Vp(f.block,t,n,r,i,new Set([...o,f.uid]),s+1);for(let h of g.reads)a.add(h);for(let h of g.writes)c.add(h)}continue}d==="unchanged-run"&&(d="read")}return{reads:[...a].sort(),writes:[...c].sort()}}function uo(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function _p(e){return e.replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}var Jp=["update","insert","delete"],zp=["select","query","findFirst","findMany"],po=new Set([...Jp,...zp]);function mo(e){let t=e.methods&&e.methods.length>0?e.methods:[...po],n=new Set(Jp),r=new Set(zp);return{write:t.filter(i=>n.has(i)),read:t.filter(i=>r.has(i))}}var lk=/^(.*)@L(\d+)-L(\d+)$/;function fo(e){let t=e.match(lk);if(!t)return{ref:e};let n=t[1],r=Number.parseInt(t[2],10),i=Number.parseInt(t[3],10);return n?r<1?{error:`codeRef "${e}" line window must start at line 1 or later`}:i<r?{error:`codeRef "${e}" line window end (L${i}) is before its start (L${r})`}:{ref:n,window:{startLine:r,endLine:i}}:{error:`codeRef "${e}" has a line window but no referent before @L${t[2]}-L${t[3]}`}}var dk=new Set(["auto","sany","tlc","apalache","none"]),Tr=/^[A-Za-z_][A-Za-z0-9_]*$/;function Kp(e){return dk.has(e)}function Ir(e,t){let n=[],r=ue(e,t);if(!r)return{errors:[`map path escapes project root: ${t}`]};if(!Je(r))return{errors:[`map file not found: ${t}`]};let i;try{i=JSON.parse(ft(r,"utf8"))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let o=uk(i,n);return o?{loaded:{contract:o,mapPath:r,mapDir:Gp(r)},errors:n}:{errors:n}}function ue(e,t){if(!t)return null;let n=Up(t)?ln(t):ln(e,t);return pe(e,n)?n:null}function Qp(e,t,n){if(!n)return null;if(Up(n)){let s=ln(n);return pe(e,s)?s:null}let r=ln(e,n);if(pe(e,r)&&Je(r))return r;let i=ln(t,n);if(pe(e,i)&&Je(i))return i;let o=pe(e,r)?r:i;return pe(e,o)?o:null}function Yp(e,t){let n=ue(e,t);if(!n||!Je(n))return null;let r=ft(n,"utf8");return{path:n,modelParse:"regex-fallback",text:r,variables:$k(r),operators:Ck(r),actions:[]}}function Xp(e,t,n){let r=ue(e,t);if(!r||!Je(r))return null;let i=ft(r,"utf8"),o=Bp(n);return{path:r,modelParse:"sany",text:i,variables:o.variables,operators:o.operators,actions:o.actions}}function go(e,t){let n=ue(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!Je(n))return{steps:[],errors:[`trace file not found: ${t}`]};try{let r=JSON.parse(ft(n,"utf8")),i=Array.isArray(r)?r:B(r)&&Array.isArray(r.steps)?r.steps:null;if(!i)return{steps:[],errors:["trace file must be an array or an object with a steps array"]};let o=[],s=[];for(let[a,c]of i.entries()){if(!B(c)||typeof c.action!="string"){s.push(`trace step ${a} must include an action string`);continue}o.push({action:c.action,before:B(c.before)?c.before:void 0,after:B(c.after)?c.after:void 0,code:typeof c.code=="string"?c.code:void 0})}return{steps:o,errors:s}}catch(r){let i=r instanceof Error?r.message:String(r);return{steps:[],errors:[`trace file is not valid JSON: ${i}`]}}}function ho(e,t){let n=new Set,r=[];for(let i of t){let o=ue(e,i)??i;n.has(o)||(n.add(o),r.push(i))}return r}function uk(e,t){if(!B(e))return t.push("map file must contain a JSON object"),null;let n=yk(e.variables,t);hk(n,t);let r=kk(e.actions,n,t),i=pk(e.init,t);fk(i,r,t);let o={module:Wp(e.module,"module",t),config:Wp(e.config,"config",t),scope:J(e.scope)??[],variables:n,actions:r,...i?{init:i}:{},invariants:J(e.invariants)??[],traces:J(e.traces)??[],unmappedWriteScope:gk(e.unmappedWriteScope,t)};return Tk(e.scope,t),t.length===0?o:null}function pk(e,t){if(e===void 0)return;if(!B(e)){t.push("init must be an object when present");return}let n=J(e.codeRefs);if(!n||n.length===0){t.push("init.codeRefs must name at least one TypeScript referent");return}let r=mk(e.waive,t);return{codeRefs:n,...r?{waive:r}:{}}}function mk(e,t){if(e===void 0)return;if(!B(e)){t.push("init.waive must be an object when present");return}let n=typeof e.reason=="string"?e.reason.trim():"";if(!n){t.push("init.waive.reason must be a non-empty string");return}return{reason:n}}function fk(e,t,n){if(!e)return;let r=new Set(e.codeRefs),i=new Set;for(let o of Object.values(t))for(let s of o.code)r.has(s)&&i.add(s);i.size>0&&n.push(`init.codeRefs overlaps action code referents: ${[...i].sort().join(", ")} \u2014 a referent cannot be both Init and an action`)}function gk(e,t){return e===void 0?"scope-files":e==="actions"||e==="scope-files"?e:(t.push('unmappedWriteScope must be "actions" or "scope-files" when present'),"scope-files")}function hk(e,t){Pr(e,t,"alias",n=>n.aliases),Pr(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),Pr(e,t,"statement pattern",n=>n.statements?n.statements.map(r=>r.pattern):[]),Pr(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(r=>{let{write:i,read:o}=mo(r);return[...i,...o].map(s=>`${r.table}:${s}`)}))}function Pr(e,t,n,r){let i=new Map;for(let[o,s]of Object.entries(e))for(let a of r(s)){let c=i.get(a);c?c.push(o):i.set(a,[o])}for(let[o,s]of i)s.length<2||t.push(`variables ${[...new Set(s)].sort().join(", ")} share ${n} "${o}" \u2014 conformance scanning cannot attribute a matching write/read to one variable unambiguously`)}function yk(e,t){if(!B(e))return t.push("variables must be an object keyed by TLA+ variable name"),{};let n={};for(let[r,i]of Object.entries(e)){if(!Tr.test(r)){t.push(`invalid TLA+ variable name: ${r}`);continue}if(!B(i)){t.push(`variables.${r} must be an object`);continue}let o=em(i.code);if(!o||o.length===0){t.push(`variables.${r}.code must name at least one TypeScript referent`);continue}let s=J(i.aliases)??[],a=Sk(i.resource,r,t),c=vk(i.statements,r,t),l=xk(i.ormCalls,r,t),d=Rk(i.waive,r,t),p=bk(i.selfAlias,r,t),m=p?[...new Set([r,...s])]:[...new Set(s)];p===!1&&m.length===0&&!a&&!c&&!l&&!d&&t.push(`variables.${r}.selfAlias is false but no aliases, resource, statements, ormCalls, or waive are set \u2014 ${r} would be unattributable; add an explicit alias, bind resource/statements/ormCalls, or add variables.${r}.waive with a reason`),n[r]={code:o,aliases:m,projection:typeof i.projection=="string"?i.projection:void 0,...a?{resource:a}:{},...c?{statements:c}:{},...l?{ormCalls:l}:{},...d?{waive:d}:{},...p===!1?{selfAlias:!1}:{}}}return n}function bk(e,t,n){return e===void 0?!0:typeof e=="boolean"?e:(n.push(`variables.${t}.selfAlias must be a boolean when present`),!0)}function Sk(e,t,n){if(e===void 0)return;if(!B(e)){n.push(`variables.${t}.resource must be an object when present`);return}let r=typeof e.path=="string"?e.path.trim():"";if(!r){n.push(`variables.${t}.resource.path must be a non-empty string`);return}return{path:r}}function vk(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push(`variables.${t}.statements must be an array when present`);return}let r=[];return e.forEach((i,o)=>{if(!B(i)){n.push(`variables.${t}.statements[${o}] must be an object`);return}let s=typeof i.pattern=="string"?i.pattern.trim():"";if(!s){n.push(`variables.${t}.statements[${o}].pattern must be a non-empty string`);return}try{new RegExp(s)}catch(a){let c=a instanceof Error?a.message:String(a);n.push(`variables.${t}.statements[${o}].pattern is not a valid regular expression: ${c}`);return}r.push({pattern:s})}),r.length>0?r:void 0}function xk(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push(`variables.${t}.ormCalls must be an array when present`);return}let r=[];return e.forEach((i,o)=>{if(!B(i)){n.push(`variables.${t}.ormCalls[${o}] must be an object`);return}let s=typeof i.table=="string"?i.table.trim():"";if(!s){n.push(`variables.${t}.ormCalls[${o}].table must be a non-empty string`);return}if(i.methods===void 0){r.push({table:s});return}let a=J(i.methods);if(!a){n.push(`variables.${t}.ormCalls[${o}].methods must be an array of strings when present`);return}let c=a.filter(l=>!po.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${o}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...po].join(", ")}`);return}r.push(a.length>0?{table:s,methods:a}:{table:s})}),r.length>0?r:void 0}function Rk(e,t,n){if(e===void 0)return;if(!B(e)){n.push(`variables.${t}.waive must be an object when present`);return}let r=typeof e.reason=="string"?e.reason.trim():"";if(!r){n.push(`variables.${t}.waive.reason must be a non-empty string`);return}return{reason:r}}function kk(e,t,n){if(!B(e))return n.push("actions must be an object keyed by TLA+ action name"),{};let r=new Set(Object.keys(t)),i={};for(let[o,s]of Object.entries(e)){if(!Tr.test(o)){n.push(`invalid TLA+ action name: ${o}`);continue}if(!B(s)){n.push(`actions.${o} must be an object`);continue}let a=em(s.code);if(!a||a.length===0){n.push(`actions.${o}.code must name at least one TypeScript referent`);continue}for(let m of a){let f=fo(m);"error"in f&&n.push(`actions.${o}.code: ${f.error}`)}let c=J(s.reads)??[],l=J(s.writes)??[],d=J(s.calls)??[];for(let m of[...c,...l])r.has(m)||n.push(`actions.${o} references unknown variable: ${m}`);let p=wk(s.waive,s.allowUnknown===!0,c,l,r,o,n);i[o]={code:a,reads:c,writes:l,calls:d,...p?{waive:p}:{}}}return i}function wk(e,t,n,r,i,o,s){if(B(e)){let a=typeof e.reason=="string"?e.reason.trim():"";a||s.push(`actions.${o}.waive.reason must be a non-empty string`);let c=J(e.reads)??[],l=J(e.writes)??[];return c.length===0&&l.length===0&&s.push(`actions.${o}.waive must list reads or writes`),Hp(o,"reads",c,i,s),Hp(o,"writes",l,i,s),{reads:[...new Set(c)],writes:[...new Set(l)],reason:a}}if(e!==void 0&&s.push(`actions.${o}.waive must be an object when present`),t)return{reads:[...new Set(n)],writes:[...new Set(r)],reason:"legacy allowUnknown",legacy:!0}}function Hp(e,t,n,r,i){for(let o of n)r.has(o)||i.push(`actions.${e}.waive.${t} references unknown variable: ${o}`)}function $k(e){let t=new Set;for(let n of e.matchAll(/^\s*VARIABLES?\s+([^\n]+)/gm)){let r=n[1]??"";for(let i of r.split(",")){let o=i.trim();Tr.test(o)&&t.add(o)}}return[...t].sort()}function Ck(e){let t=new Set;for(let n of e.matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*(?:\([^)]*\))?\s*==/gm))t.add(n[1]);return[...t].sort()}var Pk=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function Zp(e){if(!e||!Je(e))return[];let t=ft(e,"utf8").replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,r=!1;for(let i of t.split(/[\s,]+/))if(i){if(Pk.has(i)){r=i==="INVARIANT"||i==="INVARIANTS";continue}r&&Tr.test(i)&&n.add(i)}return[...n].sort()}function Wp(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function em(e){return typeof e=="string"?[e]:J(e)}function Tk(e,t){e!==void 0&&(J(e)||t.push("scope must be an array of strings when present"))}function Er(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var Ik=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function tm(e,t){if(!Je(t))return{status:"none"};let r=ft(t,"utf8").match(Ik)?.[1],i=ak(e,t).split(ck).join("/"),o=ok(t),s=new Set([r,i,o,o.replace(/\.tla$/i,"")].filter(d=>!!d)),a=Gp(t);if(!Je(a))return{status:"none"};let c=[];for(let d of ik(a)){if(!d.endsWith(".scip-tla.json"))continue;let p=sk(a,d),m;try{m=JSON.parse(ft(p,"utf8"))}catch{continue}B(m)&&typeof m.module=="string"&&s.has(m.module)&&c.push(p)}c.sort();let l=r??i;return c.length===0?{status:"none"}:c.length>1?{status:"ambiguous",candidates:c,moduleName:l}:{status:"found",mapPath:c[0],moduleName:l}}function jr(e,t,n,r,i={count:e.length,loc:r}){let o=i.count===e.length&&i.loc===r?`${e.length}, ${r} LOC`:`${e.length} of ${i.count}, ${r} of ${i.loc} LOC`;console.log(`\u2550\u2550\u2550 ${t} (${o}) \u2550\u2550\u2550`),console.log(n),console.log("");let s=new Map;for(let l of e){let d=s.get(l.relativePath)??[];d.push(l),s.set(l.relativePath,d)}let a=[...s.entries()].map(([l,d])=>({file:l,bucket:d,totalLoc:d.reduce((p,m)=>p+m.loc,0)})).sort((l,d)=>d.totalLoc-l.totalLoc||l.file.localeCompare(d.file)),c=!0;for(let{file:l,bucket:d}of a){c||console.log(""),c=!1,console.log(` ${l}`),d.sort((p,m)=>p.startLine-m.startLine);for(let p of d){let m=p.implicitUsageReason?` [implicit usage: ${p.implicitUsageReason}]`:"";console.log(` ${ie(p.startLine,p.endLine)} (${p.loc} LOC) ${p.shortName}${m}`)}}}var yo=20,nm=K("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:V(t,0)||void 0,minLoc:C(n,"minLoc",1),includeTests:b(n,"includeTests"),skipBarrels:b(n,"skipBarrels"),includeMembers:b(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=vs(e,i),s=o.symbols.filter(O=>O.kind==="dead-code"),a=o.symbols.filter(O=>O.kind==="file-internal"),c=o.symbols.filter(O=>O.kind==="implicit-usage"),l=!b(n,"onlyInternal"),d=!b(n,"onlyDead"),p=!b(n,"onlyDead")&&!b(n,"onlyInternal"),m=l?s:[],f=d?a:[],g=p?c:[],h=m.reduce((O,H)=>O+H.loc,0),y=f.reduce((O,H)=>O+H.loc,0),S=g.reduce((O,H)=>O+H.loc,0),v=b(n,"full"),k=v?m:m.slice(0,yo),R=v?f:f.slice(0,yo),D=v?g:g.slice(0,yo),q=k.reduce((O,H)=>O+H.loc,0),z=R.reduce((O,H)=>O+H.loc,0),T=D.reduce((O,H)=>O+H.loc,0),F={total:m.length+f.length+g.length,deadCode:m.length,fileInternal:f.length,implicitUsage:g.length,loc:h+y+S};if(b(n,"json")){I("dead",t,n,{...o,shown:{deadCode:m,fileInternal:f,implicitUsage:g},shownCounts:F,totals:{total:o.counts.total,deadCode:o.counts.deadCode,fileInternal:o.counts.fileInternal,implicitUsage:o.counts.implicitUsage,loc:o.counts.loc}},{analysisBudget:r.analysisBudget});return}if(m.length===0&&f.length===0&&g.length===0){E.empty("No matching dead-code symbols found.");return}m.length>0&&(jr(k,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
403
- Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,q,{count:m.length,loc:h}),!v&&m.length>k.length&&console.log(`
402
+ 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 cn(e){return{...e,options:P(e.options)}}function Ee({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,...a}){let c=cn(a);return{...c,renderShape:"list",handler:fc({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s})}}function $r({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c,...l}){let d=cn(l);return{...d,renderShape:"table",handler:gc({commandName:d.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c})}}function Np({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a,...c}){let l=cn(c);return{...l,renderShape:"grouped-by-file",handler:hc({commandName:l.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a})}}function Mp({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=cn(a);return{...c,renderShape:"sectioned-report",handler:yc({commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}function Cr({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=cn(a);return{...c,budget:c.budget??"semantic",renderShape:"sectioned-report",handler:bc(c.id,{commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}import{existsSync as Ek,mkdirSync as jk,writeFileSync as Ak}from"fs";import{dirname as Lk,relative as Dk}from"path";import{existsSync as Je,readdirSync as ik,readFileSync as ft}from"fs";import{basename as ok,dirname as Gp,isAbsolute as Up,join as sk,relative as ak,resolve as ln,sep as ck}from"path";import{spawnSync as ek}from"child_process";import{dirname as tk}from"path";function Bp(e){let n=(e.spawnSync??ek)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:tk(e.specPath),maxBuffer:1024*1024*32});if(n.status!==0)return null;let r=n.stdout??"";return r.includes("<?xml")?r:null}function qp(e){let t=rk(e),n=new Map,r=new Map,i=[],o=new Map;for(let a of t)a.type==="OpDeclNode"&&a.kind===3&&a.uniquename?n.set(a.uid,a.uniquename):a.type==="BuiltInKind"&&a.uniquename?r.set(a.uid,a.uniquename):a.type==="UserDefinedOpKind"&&a.uniquename&&(i.push(a),o.set(a.uid,a));let s=[];for(let a of i){let c=Vp(a.block,n,r,o,a.filename,new Set([a.uid]),0);s.push({name:a.uniquename,reads:c.reads,writes:c.writes})}return{modelParse:"sany",variables:[...n.values()].sort(),operators:i.map(a=>a.uniquename).sort(),actions:s}}var nk=8;function rk(e){let t=[],n=/<entry>\s*<UID>(\d+)<\/UID>\s*<(\w+)>/g;for(let r of e.matchAll(n)){let i=r.index,o=e.indexOf("</entry>",i),s=e.slice(i,o<0?e.length:o),a=uo(s,"uniquename"),c=uo(s,"kind"),l=uo(s,"filename");t.push({uid:r[1],type:r[2],uniquename:a===null?null:_p(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:_p(l),block:s})}return t}function Vp(e,t,n,r,i,o,s){let a=new Set,c=new Set,l=[...e.matchAll(/<(\w+Ref)>\s*<UID>(\d+)<\/UID>/g)],d="read";for(let[,p,m]of l){if(p==="BuiltInKindRef"){let f=n.get(m)??"";f==="'"?d="write-next":f==="UNCHANGED"?d="unchanged-run":d==="unchanged-run"&&f==="$Tuple"||d!=="write-next"&&(d="read");continue}if(p==="OpDeclNodeRef"){let f=t.get(m);if(!f)continue;d==="write-next"?(c.add(f),d="read"):d==="unchanged-run"||a.add(f);continue}if(p==="UserDefinedOpKindRef"){d==="unchanged-run"&&(d="read");let f=r.get(m);if(f&&s<nk&&!o.has(f.uid)&&f.filename===i){let g=Vp(f.block,t,n,r,i,new Set([...o,f.uid]),s+1);for(let h of g.reads)a.add(h);for(let h of g.writes)c.add(h)}continue}d==="unchanged-run"&&(d="read")}return{reads:[...a].sort(),writes:[...c].sort()}}function uo(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function _p(e){return e.replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}var Jp=["update","insert","delete"],zp=["select","query","findFirst","findMany"],po=new Set([...Jp,...zp]);function mo(e){let t=e.methods&&e.methods.length>0?e.methods:[...po],n=new Set(Jp),r=new Set(zp);return{write:t.filter(i=>n.has(i)),read:t.filter(i=>r.has(i))}}var lk=/^(.*)@L(\d+)-L(\d+)$/;function fo(e){let t=e.match(lk);if(!t)return{ref:e};let n=t[1],r=Number.parseInt(t[2],10),i=Number.parseInt(t[3],10);return n?r<1?{error:`codeRef "${e}" line window must start at line 1 or later`}:i<r?{error:`codeRef "${e}" line window end (L${i}) is before its start (L${r})`}:{ref:n,window:{startLine:r,endLine:i}}:{error:`codeRef "${e}" has a line window but no referent before @L${t[2]}-L${t[3]}`}}var dk=new Set(["auto","sany","tlc","apalache","none"]),Tr=/^[A-Za-z_][A-Za-z0-9_]*$/;function Kp(e){return dk.has(e)}function Ir(e,t){let n=[],r=ue(e,t);if(!r)return{errors:[`map path escapes project root: ${t}`]};if(!Je(r))return{errors:[`map file not found: ${t}`]};let i;try{i=JSON.parse(ft(r,"utf8"))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let o=uk(i,n);return o?{loaded:{contract:o,mapPath:r,mapDir:Gp(r)},errors:n}:{errors:n}}function ue(e,t){if(!t)return null;let n=Up(t)?ln(t):ln(e,t);return pe(e,n)?n:null}function Qp(e,t,n){if(!n)return null;if(Up(n)){let s=ln(n);return pe(e,s)?s:null}let r=ln(e,n);if(pe(e,r)&&Je(r))return r;let i=ln(t,n);if(pe(e,i)&&Je(i))return i;let o=pe(e,r)?r:i;return pe(e,o)?o:null}function Yp(e,t){let n=ue(e,t);if(!n||!Je(n))return null;let r=ft(n,"utf8");return{path:n,modelParse:"regex-fallback",text:r,variables:$k(r),operators:Ck(r),actions:[]}}function Xp(e,t,n){let r=ue(e,t);if(!r||!Je(r))return null;let i=ft(r,"utf8"),o=qp(n);return{path:r,modelParse:"sany",text:i,variables:o.variables,operators:o.operators,actions:o.actions}}function go(e,t){let n=ue(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!Je(n))return{steps:[],errors:[`trace file not found: ${t}`]};try{let r=JSON.parse(ft(n,"utf8")),i=Array.isArray(r)?r:q(r)&&Array.isArray(r.steps)?r.steps:null;if(!i)return{steps:[],errors:["trace file must be an array or an object with a steps array"]};let o=[],s=[];for(let[a,c]of i.entries()){if(!q(c)||typeof c.action!="string"){s.push(`trace step ${a} must include an action string`);continue}o.push({action:c.action,before:q(c.before)?c.before:void 0,after:q(c.after)?c.after:void 0,code:typeof c.code=="string"?c.code:void 0})}return{steps:o,errors:s}}catch(r){let i=r instanceof Error?r.message:String(r);return{steps:[],errors:[`trace file is not valid JSON: ${i}`]}}}function ho(e,t){let n=new Set,r=[];for(let i of t){let o=ue(e,i)??i;n.has(o)||(n.add(o),r.push(i))}return r}function uk(e,t){if(!q(e))return t.push("map file must contain a JSON object"),null;let n=yk(e.variables,t);hk(n,t);let r=kk(e.actions,n,t),i=pk(e.init,t);fk(i,r,t);let o={module:Wp(e.module,"module",t),config:Wp(e.config,"config",t),scope:J(e.scope)??[],variables:n,actions:r,...i?{init:i}:{},invariants:J(e.invariants)??[],traces:J(e.traces)??[],unmappedWriteScope:gk(e.unmappedWriteScope,t)};return Tk(e.scope,t),t.length===0?o:null}function pk(e,t){if(e===void 0)return;if(!q(e)){t.push("init must be an object when present");return}let n=J(e.codeRefs);if(!n||n.length===0){t.push("init.codeRefs must name at least one TypeScript referent");return}let r=mk(e.waive,t);return{codeRefs:n,...r?{waive:r}:{}}}function mk(e,t){if(e===void 0)return;if(!q(e)){t.push("init.waive must be an object when present");return}let n=typeof e.reason=="string"?e.reason.trim():"";if(!n){t.push("init.waive.reason must be a non-empty string");return}return{reason:n}}function fk(e,t,n){if(!e)return;let r=new Set(e.codeRefs),i=new Set;for(let o of Object.values(t))for(let s of o.code)r.has(s)&&i.add(s);i.size>0&&n.push(`init.codeRefs overlaps action code referents: ${[...i].sort().join(", ")} \u2014 a referent cannot be both Init and an action`)}function gk(e,t){return e===void 0?"scope-files":e==="actions"||e==="scope-files"?e:(t.push('unmappedWriteScope must be "actions" or "scope-files" when present'),"scope-files")}function hk(e,t){Pr(e,t,"alias",n=>n.aliases),Pr(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),Pr(e,t,"statement pattern",n=>n.statements?n.statements.map(r=>r.pattern):[]),Pr(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(r=>{let{write:i,read:o}=mo(r);return[...i,...o].map(s=>`${r.table}:${s}`)}))}function Pr(e,t,n,r){let i=new Map;for(let[o,s]of Object.entries(e))for(let a of r(s)){let c=i.get(a);c?c.push(o):i.set(a,[o])}for(let[o,s]of i)s.length<2||t.push(`variables ${[...new Set(s)].sort().join(", ")} share ${n} "${o}" \u2014 conformance scanning cannot attribute a matching write/read to one variable unambiguously`)}function yk(e,t){if(!q(e))return t.push("variables must be an object keyed by TLA+ variable name"),{};let n={};for(let[r,i]of Object.entries(e)){if(!Tr.test(r)){t.push(`invalid TLA+ variable name: ${r}`);continue}if(!q(i)){t.push(`variables.${r} must be an object`);continue}let o=em(i.code);if(!o||o.length===0){t.push(`variables.${r}.code must name at least one TypeScript referent`);continue}let s=J(i.aliases)??[],a=Sk(i.resource,r,t),c=vk(i.statements,r,t),l=xk(i.ormCalls,r,t),d=Rk(i.waive,r,t),p=bk(i.selfAlias,r,t),m=p?[...new Set([r,...s])]:[...new Set(s)];p===!1&&m.length===0&&!a&&!c&&!l&&!d&&t.push(`variables.${r}.selfAlias is false but no aliases, resource, statements, ormCalls, or waive are set \u2014 ${r} would be unattributable; add an explicit alias, bind resource/statements/ormCalls, or add variables.${r}.waive with a reason`),n[r]={code:o,aliases:m,projection:typeof i.projection=="string"?i.projection:void 0,...a?{resource:a}:{},...c?{statements:c}:{},...l?{ormCalls:l}:{},...d?{waive:d}:{},...p===!1?{selfAlias:!1}:{}}}return n}function bk(e,t,n){return e===void 0?!0:typeof e=="boolean"?e:(n.push(`variables.${t}.selfAlias must be a boolean when present`),!0)}function Sk(e,t,n){if(e===void 0)return;if(!q(e)){n.push(`variables.${t}.resource must be an object when present`);return}let r=typeof e.path=="string"?e.path.trim():"";if(!r){n.push(`variables.${t}.resource.path must be a non-empty string`);return}return{path:r}}function vk(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push(`variables.${t}.statements must be an array when present`);return}let r=[];return e.forEach((i,o)=>{if(!q(i)){n.push(`variables.${t}.statements[${o}] must be an object`);return}let s=typeof i.pattern=="string"?i.pattern.trim():"";if(!s){n.push(`variables.${t}.statements[${o}].pattern must be a non-empty string`);return}try{new RegExp(s)}catch(a){let c=a instanceof Error?a.message:String(a);n.push(`variables.${t}.statements[${o}].pattern is not a valid regular expression: ${c}`);return}r.push({pattern:s})}),r.length>0?r:void 0}function xk(e,t,n){if(e===void 0)return;if(!Array.isArray(e)){n.push(`variables.${t}.ormCalls must be an array when present`);return}let r=[];return e.forEach((i,o)=>{if(!q(i)){n.push(`variables.${t}.ormCalls[${o}] must be an object`);return}let s=typeof i.table=="string"?i.table.trim():"";if(!s){n.push(`variables.${t}.ormCalls[${o}].table must be a non-empty string`);return}if(i.methods===void 0){r.push({table:s});return}let a=J(i.methods);if(!a){n.push(`variables.${t}.ormCalls[${o}].methods must be an array of strings when present`);return}let c=a.filter(l=>!po.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${o}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...po].join(", ")}`);return}r.push(a.length>0?{table:s,methods:a}:{table:s})}),r.length>0?r:void 0}function Rk(e,t,n){if(e===void 0)return;if(!q(e)){n.push(`variables.${t}.waive must be an object when present`);return}let r=typeof e.reason=="string"?e.reason.trim():"";if(!r){n.push(`variables.${t}.waive.reason must be a non-empty string`);return}return{reason:r}}function kk(e,t,n){if(!q(e))return n.push("actions must be an object keyed by TLA+ action name"),{};let r=new Set(Object.keys(t)),i={};for(let[o,s]of Object.entries(e)){if(!Tr.test(o)){n.push(`invalid TLA+ action name: ${o}`);continue}if(!q(s)){n.push(`actions.${o} must be an object`);continue}let a=em(s.code);if(!a||a.length===0){n.push(`actions.${o}.code must name at least one TypeScript referent`);continue}for(let m of a){let f=fo(m);"error"in f&&n.push(`actions.${o}.code: ${f.error}`)}let c=J(s.reads)??[],l=J(s.writes)??[],d=J(s.calls)??[];for(let m of[...c,...l])r.has(m)||n.push(`actions.${o} references unknown variable: ${m}`);let p=wk(s.waive,s.allowUnknown===!0,c,l,r,o,n);i[o]={code:a,reads:c,writes:l,calls:d,...p?{waive:p}:{}}}return i}function wk(e,t,n,r,i,o,s){if(q(e)){let a=typeof e.reason=="string"?e.reason.trim():"";a||s.push(`actions.${o}.waive.reason must be a non-empty string`);let c=J(e.reads)??[],l=J(e.writes)??[];return c.length===0&&l.length===0&&s.push(`actions.${o}.waive must list reads or writes`),Hp(o,"reads",c,i,s),Hp(o,"writes",l,i,s),{reads:[...new Set(c)],writes:[...new Set(l)],reason:a}}if(e!==void 0&&s.push(`actions.${o}.waive must be an object when present`),t)return{reads:[...new Set(n)],writes:[...new Set(r)],reason:"legacy allowUnknown",legacy:!0}}function Hp(e,t,n,r,i){for(let o of n)r.has(o)||i.push(`actions.${e}.waive.${t} references unknown variable: ${o}`)}function $k(e){let t=new Set;for(let n of e.matchAll(/^\s*VARIABLES?\s+([^\n]+)/gm)){let r=n[1]??"";for(let i of r.split(",")){let o=i.trim();Tr.test(o)&&t.add(o)}}return[...t].sort()}function Ck(e){let t=new Set;for(let n of e.matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*(?:\([^)]*\))?\s*==/gm))t.add(n[1]);return[...t].sort()}var Pk=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function Zp(e){if(!e||!Je(e))return[];let t=ft(e,"utf8").replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,r=!1;for(let i of t.split(/[\s,]+/))if(i){if(Pk.has(i)){r=i==="INVARIANT"||i==="INVARIANTS";continue}r&&Tr.test(i)&&n.add(i)}return[...n].sort()}function Wp(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function em(e){return typeof e=="string"?[e]:J(e)}function Tk(e,t){e!==void 0&&(J(e)||t.push("scope must be an array of strings when present"))}function Er(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var Ik=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function tm(e,t){if(!Je(t))return{status:"none"};let r=ft(t,"utf8").match(Ik)?.[1],i=ak(e,t).split(ck).join("/"),o=ok(t),s=new Set([r,i,o,o.replace(/\.tla$/i,"")].filter(d=>!!d)),a=Gp(t);if(!Je(a))return{status:"none"};let c=[];for(let d of ik(a)){if(!d.endsWith(".scip-tla.json"))continue;let p=sk(a,d),m;try{m=JSON.parse(ft(p,"utf8"))}catch{continue}q(m)&&typeof m.module=="string"&&s.has(m.module)&&c.push(p)}c.sort();let l=r??i;return c.length===0?{status:"none"}:c.length>1?{status:"ambiguous",candidates:c,moduleName:l}:{status:"found",mapPath:c[0],moduleName:l}}function jr(e,t,n,r,i={count:e.length,loc:r}){let o=i.count===e.length&&i.loc===r?`${e.length}, ${r} LOC`:`${e.length} of ${i.count}, ${r} of ${i.loc} LOC`;console.log(`\u2550\u2550\u2550 ${t} (${o}) \u2550\u2550\u2550`),console.log(n),console.log("");let s=new Map;for(let l of e){let d=s.get(l.relativePath)??[];d.push(l),s.set(l.relativePath,d)}let a=[...s.entries()].map(([l,d])=>({file:l,bucket:d,totalLoc:d.reduce((p,m)=>p+m.loc,0)})).sort((l,d)=>d.totalLoc-l.totalLoc||l.file.localeCompare(d.file)),c=!0;for(let{file:l,bucket:d}of a){c||console.log(""),c=!1,console.log(` ${l}`),d.sort((p,m)=>p.startLine-m.startLine);for(let p of d){let m=p.implicitUsageReason?` [implicit usage: ${p.implicitUsageReason}]`:"";console.log(` ${ie(p.startLine,p.endLine)} (${p.loc} LOC) ${p.shortName}${m}`)}}}var yo=20,nm=K("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:V(t,0)||void 0,minLoc:C(n,"minLoc",1),includeTests:b(n,"includeTests"),skipBarrels:b(n,"skipBarrels"),includeMembers:b(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=vs(e,i),s=o.symbols.filter(O=>O.kind==="dead-code"),a=o.symbols.filter(O=>O.kind==="file-internal"),c=o.symbols.filter(O=>O.kind==="implicit-usage"),l=!b(n,"onlyInternal"),d=!b(n,"onlyDead"),p=!b(n,"onlyDead")&&!b(n,"onlyInternal"),m=l?s:[],f=d?a:[],g=p?c:[],h=m.reduce((O,H)=>O+H.loc,0),y=f.reduce((O,H)=>O+H.loc,0),S=g.reduce((O,H)=>O+H.loc,0),v=b(n,"full"),k=v?m:m.slice(0,yo),R=v?f:f.slice(0,yo),D=v?g:g.slice(0,yo),B=k.reduce((O,H)=>O+H.loc,0),z=R.reduce((O,H)=>O+H.loc,0),T=D.reduce((O,H)=>O+H.loc,0),F={total:m.length+f.length+g.length,deadCode:m.length,fileInternal:f.length,implicitUsage:g.length,loc:h+y+S};if(b(n,"json")){I("dead",t,n,{...o,shown:{deadCode:m,fileInternal:f,implicitUsage:g},shownCounts:F,totals:{total:o.counts.total,deadCode:o.counts.deadCode,fileInternal:o.counts.fileInternal,implicitUsage:o.counts.implicitUsage,loc:o.counts.loc}},{analysisBudget:r.analysisBudget});return}if(m.length===0&&f.length===0&&g.length===0){E.empty("No matching dead-code symbols found.");return}m.length>0&&(jr(k,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
403
+ Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,B,{count:m.length,loc:h}),!v&&m.length>k.length&&console.log(`
404
404
  Showing top ${k.length} by LOC. Re-run with --full for the remaining ${m.length-k.length}.`)),f.length>0&&(m.length>0&&console.log(""),jr(R,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
405
405
  single-use helper, an abstraction-in-progress, or a callback registered
406
406
  through a framework path that static analysis cannot trace (signal
@@ -428,7 +428,7 @@ ${e.length} passthrough candidate(s).`)}),lm=de("stale-abstractions",{query:({db
428
428
  ${e.reason}
429
429
  Kind: ${e.stalenessKind}; tier: ${e.actionTier}
430
430
  Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
431
- ${e.length} stale abstraction(s).`)}),dm=On("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>Ca(e,{scope:w(t,"scope"),minLoc:C(t,"minLoc",10),limit:L(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]}),um=Se("similar",{query:({db:e,args:t,opts:n,budget:r})=>{if(b(n,"plan")){let o=V(t,0),s=V(t,1);if(!o||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:Bs(e,o,s,{scanLimit:r.scanLimit,semantic:r.semantic})}}let i=V(t,0);return i?{mode:"target",rows:qs(e,i,{minSimilarity:C(n,"minSimilarity",.4),limit:L(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:Vs(e,{minSimilarity:C(n,"minSimilarity",.4),limit:L(n,"limit",20),scope:w(n,"scope"),minCallees:C(n,"minCallees",4),crossFileOnly:b(n,"crossFileOnly"),scanLimit:r.scanLimit,semantic:r.semantic})}},emptyMessage:e=>{if(e.mode==="plan")return e.result?void 0:"No similarity evidence found for that pair.";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==="plan"){let t=e.result;if(!t)return;let n=t.similarityBasis==="source-tokens"?"source-token overlap":"weighted callee overlap";console.log(`
431
+ ${e.length} stale abstraction(s).`)}),dm=On("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>Ca(e,{scope:w(t,"scope"),minLoc:C(t,"minLoc",10),limit:L(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]}),um=Se("similar",{query:({db:e,args:t,opts:n,budget:r})=>{if(b(n,"plan")){let o=V(t,0),s=V(t,1);if(!o||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:qs(e,o,s,{scanLimit:r.scanLimit,semantic:r.semantic})}}let i=V(t,0);return i?{mode:"target",rows:Bs(e,i,{minSimilarity:C(n,"minSimilarity",.4),limit:L(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:Vs(e,{minSimilarity:C(n,"minSimilarity",.4),limit:L(n,"limit",20),scope:w(n,"scope"),minCallees:C(n,"minCallees",4),crossFileOnly:b(n,"crossFileOnly"),scanLimit:r.scanLimit,semantic:r.semantic})}},emptyMessage:e=>{if(e.mode==="plan")return e.result?void 0:"No similarity evidence found for that pair.";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==="plan"){let t=e.result;if(!t)return;let n=t.similarityBasis==="source-tokens"?"source-token overlap":"weighted callee overlap";console.log(`
432
432
  ${Math.round(t.similarity*100)}% ${n}
433
433
  `),console.log(` A: ${t.symbolA.shortName} (${t.symbolA.file}, ${t.symbolA.loc} LOC)`),console.log(` B: ${t.symbolB.shortName} (${t.symbolB.file}, ${t.symbolB.loc} LOC)`),console.log(` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`),console.log(` Recommendation: ${t.recommendation}
434
434
  `),console.log(` Shared evidence (${t.sharedEvidence.length}):`);for(let r of t.sharedEvidence)console.log(` ${r}`);if(t.uniqueToA.length>0){console.log(`
@@ -506,19 +506,24 @@ ${Math.round(t.similarity*100)}% similar Vue behavior:`,` ${t.fileA}`,` ${t.fi
506
506
  ${e.length} Vue composable candidate pair(s) found.`)}}),Lm=Se("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Ks(e,{minTotalLines:b(n,"reviewThresholds")&&vc(n,"minTotalLines")==="default"?300:C(n,"minTotalLines",800),minTemplateLines:C(n,"minTemplateLines",300),minScriptLines:C(n,"minScriptLines",300),minStyleLines:C(n,"minStyleLines",500),limit:L(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:V(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{E.list(e,t=>{let n=[`
507
507
  ${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(`
508
508
  `)}),console.log(`
509
- ${e.length} large Vue view pressure file(s) found.`)}});function re(e){return{docs:$("Cleanup"),...e}}function X({heuristicLabel:e,...t}){return re({...t,heuristic:{label:e}})}var Ar=[re({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:P([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Maximum findings",x,30),u("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:$("Cleanup",["scip-query unused-params -s src/services"]),handler:Pm}),re({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Only include symbols >= N lines",x,1),u("--max-depth <n>","Maximum cascade depth",x,5),u("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),u("--patch","With --verify, print the compiler-verified deletion patch to stdout"),u("--json","Output as JSON for programmatic consumption"),u("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:km}),re({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Only include symbols >= N lines",x,1),u("--max-depth <n>","Maximum cascade depth",x,5),u("--verified","Required: verify the selected cleanup batch before applying it"),u("--batch <n>","Apply one batch depth",x),u("--all","Apply every compiler-verified batch in the plan"),u("--force-dirty","Allow applying when plan files already have working-tree edits"),u("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:wm}),re({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:P([u("--window <n>",'How many commits back counts as "recent"',x,100),u("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",fe),u("-n, --limit <n>","Maximum findings",x,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded semantic and git-history analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:$("Cleanup",["scip-query recent-duplicates --window 50"]),handler:$m}),re({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([u("-n, --limit <n>","Maximum docs to report",x,20),u("--min-coupling <n>","Minimum historical co-changes to track a subject",x,3),u("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:$("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:Cm}),re({id:"dead",command:"dead [scope]",description:"Find repository-dead code, file-internal symbols, and implicit-usage signals",options:P([u("--min-loc <n>","Only show symbols >= N lines",x,1),u("--include-tests","Include definitions from test files (test references always count)"),u("--skip-barrels","Ignore refs from barrel re-export files"),u("--include-members","Include class members"),u("--only-dead","Show only [dead code] symbols (skip file-internal and implicit-usage signals)"),u("--only-internal","Show only [file-internal only] symbols (skip dead-code and implicit-usage signals)"),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query dead --min-loc 10"]),handler:nm}),re({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:P([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:rm}),re({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum lines of code",x,3),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:im}),X({id:"similar",command:"similar [symbol] [other]",description:"Find heuristic function similarity candidates from callee fingerprints",options:P([u("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",fe,.4),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-callees <n>","Minimum callees to consider",x,4),u("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),u("--plan","Render a consolidation preview for two symbols"),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:um}),X({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:P([u("--min-similarity <n>","Minimum Jaccard similarity (0-1)",fe,.5),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-deps <n>","Minimum dependencies to consider",x),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:pm}),X({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([u("--min-similarity <n>","Minimum JSX structure similarity (0-1)",fe,.62),u("--min-tokens <n>","Minimum structural tokens to consider",x,8),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Tm}),X({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([u("--min-similarity <n>","Minimum behavior similarity (0-1)",fe,.45),u("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Im}),X({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([u("--min-component-lines <n>","Minimum component lines",x,300),u("--min-file-lines <n>","Minimum file lines",x,800),u("--min-jsx-tokens <n>","Minimum JSX structure tokens",x,80),u("--min-behavior-tokens <n>","Minimum behavior tokens",x,40),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Em}),X({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([u("--min-similarity <n>","Minimum template similarity (0-1)",fe,.62),u("--min-tokens <n>","Minimum structural tokens to consider",x,8),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:jm}),X({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([u("--min-similarity <n>","Minimum behavior similarity (0-1)",fe,.45),u("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Am}),X({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([u("--min-total-lines <n>","Minimum total component lines",x,800),u("--min-template-lines <n>","Minimum template lines",x,300),u("--min-script-lines <n>","Minimum script lines",x,300),u("--min-style-lines <n>","Minimum style lines",x,500),u("--review-thresholds","Use lower review thresholds without changing health scoring"),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Lm}),X({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:P([u("--min-similarity <n>","Minimum chain similarity (0-1)",fe,.5),u("-n, --limit <n>","Number of results",x,15),u("-s, --scope <path>","Limit to files matching path"),u("--min-length <n>","Minimum chain length",x,3),u("--max-length <n>","Maximum chain length",x,8),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:mm}),X({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum function LOC",x,10),u("--min-callees <n>","Minimum callees to analyze",x,6),u("-n, --limit <n>","Number of results",x,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:om}),X({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:P([u("-s, --scope <path>","Limit scan mode to files matching path"),u("--min-consumers <n>","Minimum consumers in scan mode",x,1),u("-n, --limit <n>","Number of results",x,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:sm}),X({id:"drift",command:"drift [module]",description:"Detect drift candidates: unused imports and declared architecture violations; pass --architecture for boundary context",options:P([u("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",Be,5),u("--patterns",'Also include pattern-deviation findings ("only sibling importing X") \u2014 off by default: low precision at scale (21.2 calibration)',void 0,!1),u("--architecture","Include boundary coverage, undeclared edges, reciprocal pairs, and connected groups",void 0,!1),u("-n, --limit <n>","Number of results",x,50),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:fm}),X({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC for candidates",x,15),u("-n, --limit <n>","Number of results",x,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:am}),X({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC for candidates",x,15),u("-n, --limit <n>","Number of results",x,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:cm}),X({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC",x,3),u("-n, --limit <n>","Number of results",x,30),u("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:lm}),X({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC",x,10),u("-n, --limit <n>","Number of results",x,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:dm}),re({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Deprecated alias for similar <symbol1> <symbol2> --plan",options:P([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:gm}),Np({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",x,30),u("--full","Run unbounded analysis on large indexes")],docs:$("Cleanup"),query:({db:e,opts:t})=>Oa(e,{scope:w(t,"scope"),limit:L(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
509
+ ${e.length} large Vue view pressure file(s) found.`)}});function re(e){return{docs:$("Cleanup"),...e}}function X({heuristicLabel:e,...t}){return re({...t,heuristic:{label:e}})}var Ar=[re({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:P([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Maximum findings",x,30),u("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:$("Cleanup",["scip-query unused-params -s src/services"]),handler:Pm}),re({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Only include symbols >= N lines",x,1),u("--max-depth <n>","Maximum cascade depth",x,5),u("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),u("--patch","With --verify, print the compiler-verified deletion patch to stdout"),u("--json","Output as JSON for programmatic consumption"),u("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:km}),re({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Only include symbols >= N lines",x,1),u("--max-depth <n>","Maximum cascade depth",x,5),u("--verified","Required: verify the selected cleanup batch before applying it"),u("--batch <n>","Apply one batch depth",x),u("--all","Apply every compiler-verified batch in the plan"),u("--force-dirty","Allow applying when plan files already have working-tree edits"),u("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:wm}),re({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:P([u("--window <n>",'How many commits back counts as "recent"',x,100),u("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",fe),u("-n, --limit <n>","Maximum findings",x,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded semantic and git-history analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:$("Cleanup",["scip-query recent-duplicates --window 50"]),handler:$m}),re({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([u("-n, --limit <n>","Maximum docs to report",x,20),u("--min-coupling <n>","Minimum historical co-changes to track a subject",x,3),u("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:$("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:Cm}),re({id:"dead",command:"dead [scope]",description:"Find repository-dead code, file-internal symbols, and implicit-usage signals",options:P([u("--min-loc <n>","Only show symbols >= N lines",x,1),u("--include-tests","Include definitions from test files (test references always count)"),u("--skip-barrels","Ignore refs from barrel re-export files"),u("--include-members","Include class members"),u("--only-dead","Show only [dead code] symbols (skip file-internal and implicit-usage signals)"),u("--only-internal","Show only [file-internal only] symbols (skip dead-code and implicit-usage signals)"),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query dead --min-loc 10"]),handler:nm}),re({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:P([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:rm}),re({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum lines of code",x,3),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:im}),X({id:"similar",command:"similar [symbol] [other]",description:"Find heuristic function similarity candidates from callee fingerprints",options:P([u("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",fe,.4),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-callees <n>","Minimum callees to consider",x,4),u("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),u("--plan","Render a consolidation preview for two symbols"),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:um}),X({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:P([u("--min-similarity <n>","Minimum Jaccard similarity (0-1)",fe,.5),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-deps <n>","Minimum dependencies to consider",x),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:pm}),X({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([u("--min-similarity <n>","Minimum JSX structure similarity (0-1)",fe,.62),u("--min-tokens <n>","Minimum structural tokens to consider",x,8),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Tm}),X({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([u("--min-similarity <n>","Minimum behavior similarity (0-1)",fe,.45),u("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Im}),X({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([u("--min-component-lines <n>","Minimum component lines",x,300),u("--min-file-lines <n>","Minimum file lines",x,800),u("--min-jsx-tokens <n>","Minimum JSX structure tokens",x,80),u("--min-behavior-tokens <n>","Minimum behavior tokens",x,40),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Em}),X({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([u("--min-similarity <n>","Minimum template similarity (0-1)",fe,.62),u("--min-tokens <n>","Minimum structural tokens to consider",x,8),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:jm}),X({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([u("--min-similarity <n>","Minimum behavior similarity (0-1)",fe,.45),u("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Am}),X({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([u("--min-total-lines <n>","Minimum total component lines",x,800),u("--min-template-lines <n>","Minimum template lines",x,300),u("--min-script-lines <n>","Minimum script lines",x,300),u("--min-style-lines <n>","Minimum style lines",x,500),u("--review-thresholds","Use lower review thresholds without changing health scoring"),u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Lm}),X({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:P([u("--min-similarity <n>","Minimum chain similarity (0-1)",fe,.5),u("-n, --limit <n>","Number of results",x,15),u("-s, --scope <path>","Limit to files matching path"),u("--min-length <n>","Minimum chain length",x,3),u("--max-length <n>","Maximum chain length",x,8),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:mm}),X({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum function LOC",x,10),u("--min-callees <n>","Minimum callees to analyze",x,6),u("-n, --limit <n>","Number of results",x,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:om}),X({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:P([u("-s, --scope <path>","Limit scan mode to files matching path"),u("--min-consumers <n>","Minimum consumers in scan mode",x,1),u("-n, --limit <n>","Number of results",x,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:sm}),X({id:"drift",command:"drift [module]",description:"Detect drift candidates: unused imports and declared architecture violations; pass --architecture for boundary context",options:P([u("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",qe,5),u("--patterns",'Also include pattern-deviation findings ("only sibling importing X") \u2014 off by default: low precision at scale (21.2 calibration)',void 0,!1),u("--architecture","Include boundary coverage, undeclared edges, reciprocal pairs, and connected groups",void 0,!1),u("-n, --limit <n>","Number of results",x,50),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:fm}),X({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC for candidates",x,15),u("-n, --limit <n>","Number of results",x,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:am}),X({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC for candidates",x,15),u("-n, --limit <n>","Number of results",x,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:cm}),X({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC",x,3),u("-n, --limit <n>","Number of results",x,30),u("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:lm}),X({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC",x,10),u("-n, --limit <n>","Number of results",x,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:dm}),re({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Deprecated alias for similar <symbol1> <symbol2> --plan",options:P([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:gm}),Np({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",x,30),u("--full","Run unbounded analysis on large indexes")],docs:$("Cleanup"),query:({db:e,opts:t})=>Oa(e,{scope:w(t,"scope"),limit:L(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
510
510
  barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
511
511
  Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
512
512
  Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
513
- ${e.length} redundant re-export(s).`)}),re({id:"duplicate-bodies",command:"duplicate-bodies",description:"Find exact duplicate small-body candidates across files",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC per function body",x,15),u("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",x,3),u("-n, --limit <n>","Number of groups",x,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:ym}),re({id:"twin-drift",command:"twin-drift",description:"Twin drift candidates: same-name (or near-name) functions across files with diverged bodies",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-similarity <n>","Minimum normalized-token Jaccard similarity to report as divergent (0-1)",fe,.3),u("--include-homonyms","Also report same-name pairs below the similarity threshold (likely coincidental)"),u("-n, --limit <n>","Number of groups",x,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:bm}),X({id:"not-implemented",command:"not-implemented",description:"Reachable placeholder stub candidates (throw-stub, TODO+return-default, empty body) \u2014 production callers can actually reach these; an unreachable stub is dead's job, not this one's",options:P([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",x,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"reachable placeholder stubs",budget:"candidate-scan",renderShape:"list",docs:$("Cleanup",["scip-query not-implemented -s src/services"]),handler:Sm}),X({id:"decorative-checkers",command:"decorative-checkers",description:"Decorative checker candidates: validate*/verify*/check*/assert*/is*/has* callables with no reachable failure exit anywhere in their body",options:P([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",x,30),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"decorative checker candidates",budget:"candidate-scan",renderShape:"list",docs:$("Cleanup",["scip-query decorative-checkers -s src/services"]),handler:vm}),re({id:"test-quality",command:"test-quality",description:"Test-quality candidates: assertion-free it/test bodies, a skipped-test ledger with git-blame age, and mock-echo tests that assert the same literal they stubbed into a mock",options:P([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Maximum findings per sub-check",x,30),u("--rot-days <n>","Skips older than this many days are reported as rot",x,60),u("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"test-quality findings"},renderShape:"custom",docs:$("Cleanup",["scip-query test-quality -s tests/queries"]),handler:xm}),re({id:"twin-ab",command:"twin-ab <symbolA> <symbolB>",description:"Generate a behavioral A/B scaffold comparing two same-concept twins (scip-integrity-audit drill 5) \u2014 a ready-to-fill vitest file, not an auto-executor",options:P([u("--out <path>","Output path for the generated vitest file (default: tests/generated/twin-ab/<a>-vs-<b>.test.ts)"),u("--force","Overwrite an existing scaffold file at the output path")]),evidence:"heuristic",renderShape:"custom",docs:$("Cleanup",["scip-query twin-ab src/a.ts/escapeRegex src/b.ts/escapeRegExp"]),handler:Rm}),re({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC per function",x,3),u("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",x,12),u("-n, --limit <n>","Number of groups",x,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:hm})];var Nk=le(({db:e,args:t,opts:n})=>{let r=vt(e);if(b(n,"json")){I("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: ${_e(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Dm=[{id:"stats",command:"stats",description:"Show index statistics",options:[mc()],renderShape:"custom",docs:$("Core"),handler:Nk}];var Mk=On("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Ds(e,{limit:L(t,"limit",20),scope:w(t,"scope"),minFanIn:C(t,"minFanIn",2),minFanOut:C(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."}),_k=le(({db:e,args:t,opts:n})=>{let r=V(t,0),i=L(n,"limit",30);if(r){let c=Cs(e,r);if(b(n,"json")){I("fan-in",t,n,{mode:"symbol",symbol:r,rows:c});return}if(c.length===0)return E.empty(`No fan-in for ${r}.`);E.list(c,l=>` ${String(l.count).padStart(4)} files ${l.name}`);return}let o=Ts(e,{limit:i,scope:w(n,"scope")});if(b(n,"json")){I("fan-in",t,n,{mode:"top",rows:o});return}let s=new Map;for(let c of o)s.set(c.name,(s.get(c.name)??0)+1);let a=new Set([...s].filter(([,c])=>c>1).map(([c])=>c));E.table(["files","symbol"],o.map(c=>` ${String(c.count).padStart(5)} ${c.name}${a.has(c.name)?` [${c.definedIn}]`:""}`))}),qk=le(({db:e,args:t,opts:n})=>{let r=V(t,0),i=L(n,"limit",30);if(r){let s=Ps(e,r);if(b(n,"json")){I("fan-out",t,n,{mode:"file",file:r,rows:s});return}if(s.length===0)return E.empty(`No fan-out for ${r}.`);E.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=Is(e,{limit:i,scope:w(n,"scope")});if(b(n,"json")){I("fan-out",t,n,{mode:"top",rows:o});return}E.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),Bk=le(({db:e,args:t,opts:n})=>{let r=V(t,0),i=V(t,1),o=L(n,"limit",20);if(r&&i){let a=Es(e,r,i);if(b(n,"json")){I("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=js(e,{limit:o,scope:w(n,"scope")});if(b(n,"json")){I("coupling",t,n,{mode:"top",rows:s});return}E.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}`))}),Vk=Ke({commandName:"cycles",query:({db:e,opts:t})=>As(e,{scope:w(t,"scope"),maxDepth:C(t,"maxDepth",10)}),emptyMessage:e=>e.cycles.length===0?e.truncated?`No circular dependencies found. Search truncated at depth ${e.maxDepth}; deeper cycles may exist.`:"No circular dependencies found.":void 0,toJson:e=>e,render:e=>{let t=e.cycles.filter(r=>r.kind==="real"),n=e.cycles.filter(r=>r.kind==="module-hierarchy");for(let r=0;r<t.length;r++){console.log(`
513
+ ${e.length} redundant re-export(s).`)}),re({id:"duplicate-bodies",command:"duplicate-bodies",description:"Find exact duplicate small-body candidates across files",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--max-loc <n>","Maximum LOC per function body",x,15),u("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",x,3),u("-n, --limit <n>","Number of groups",x,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:ym}),re({id:"twin-drift",command:"twin-drift",description:"Twin drift candidates: same-name (or near-name) functions across files with diverged bodies",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-similarity <n>","Minimum normalized-token Jaccard similarity to report as divergent (0-1)",fe,.3),u("--include-homonyms","Also report same-name pairs below the similarity threshold (likely coincidental)"),u("-n, --limit <n>","Number of groups",x,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:bm}),X({id:"not-implemented",command:"not-implemented",description:"Reachable placeholder stub candidates (throw-stub, TODO+return-default, empty body) \u2014 production callers can actually reach these; an unreachable stub is dead's job, not this one's",options:P([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",x,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"reachable placeholder stubs",budget:"candidate-scan",renderShape:"list",docs:$("Cleanup",["scip-query not-implemented -s src/services"]),handler:Sm}),X({id:"decorative-checkers",command:"decorative-checkers",description:"Decorative checker candidates: validate*/verify*/check*/assert*/is*/has* callables with no reachable failure exit anywhere in their body",options:P([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",x,30),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"decorative checker candidates",budget:"candidate-scan",renderShape:"list",docs:$("Cleanup",["scip-query decorative-checkers -s src/services"]),handler:vm}),re({id:"test-quality",command:"test-quality",description:"Test-quality candidates: assertion-free it/test bodies, a skipped-test ledger with git-blame age, and mock-echo tests that assert the same literal they stubbed into a mock",options:P([u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Maximum findings per sub-check",x,30),u("--rot-days <n>","Skips older than this many days are reported as rot",x,60),u("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"test-quality findings"},renderShape:"custom",docs:$("Cleanup",["scip-query test-quality -s tests/queries"]),handler:xm}),re({id:"twin-ab",command:"twin-ab <symbolA> <symbolB>",description:"Generate a behavioral A/B scaffold comparing two same-concept twins (scip-integrity-audit drill 5) \u2014 a ready-to-fill vitest file, not an auto-executor",options:P([u("--out <path>","Output path for the generated vitest file (default: tests/generated/twin-ab/<a>-vs-<b>.test.ts)"),u("--force","Overwrite an existing scaffold file at the output path")]),evidence:"heuristic",renderShape:"custom",docs:$("Cleanup",["scip-query twin-ab src/a.ts/escapeRegex src/b.ts/escapeRegExp"]),handler:Rm}),re({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--min-loc <n>","Minimum LOC per function",x,3),u("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",x,12),u("-n, --limit <n>","Number of groups",x,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:hm})];var Nk=le(({db:e,args:t,opts:n})=>{let r=vt(e);if(b(n,"json")){I("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: ${_e(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Dm=[{id:"stats",command:"stats",description:"Show index statistics",options:[mc()],renderShape:"custom",docs:$("Core"),handler:Nk}];var Mk=On("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Ds(e,{limit:L(t,"limit",20),scope:w(t,"scope"),minFanIn:C(t,"minFanIn",2),minFanOut:C(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."}),_k=le(({db:e,args:t,opts:n})=>{let r=V(t,0),i=L(n,"limit",30);if(r){let c=Cs(e,r);if(b(n,"json")){I("fan-in",t,n,{mode:"symbol",symbol:r,rows:c});return}if(c.length===0)return E.empty(`No fan-in for ${r}.`);E.list(c,l=>` ${String(l.count).padStart(4)} files ${l.name}`);return}let o=Ts(e,{limit:i,scope:w(n,"scope")});if(b(n,"json")){I("fan-in",t,n,{mode:"top",rows:o});return}let s=new Map;for(let c of o)s.set(c.name,(s.get(c.name)??0)+1);let a=new Set([...s].filter(([,c])=>c>1).map(([c])=>c));E.table(["files","symbol"],o.map(c=>` ${String(c.count).padStart(5)} ${c.name}${a.has(c.name)?` [${c.definedIn}]`:""}`))}),Bk=le(({db:e,args:t,opts:n})=>{let r=V(t,0),i=L(n,"limit",30);if(r){let s=Ps(e,r);if(b(n,"json")){I("fan-out",t,n,{mode:"file",file:r,rows:s});return}if(s.length===0)return E.empty(`No fan-out for ${r}.`);E.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=Is(e,{limit:i,scope:w(n,"scope")});if(b(n,"json")){I("fan-out",t,n,{mode:"top",rows:o});return}E.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),qk=le(({db:e,args:t,opts:n})=>{let r=V(t,0),i=V(t,1),o=L(n,"limit",20);if(r&&i){let a=Es(e,r,i);if(b(n,"json")){I("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=js(e,{limit:o,scope:w(n,"scope")});if(b(n,"json")){I("coupling",t,n,{mode:"top",rows:s});return}E.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}`))}),Vk=Ke({commandName:"cycles",query:({db:e,opts:t})=>As(e,{scope:w(t,"scope"),maxDepth:C(t,"maxDepth",10)}),emptyMessage:e=>e.cycles.length===0?e.truncated?`No circular dependencies found. Search truncated at depth ${e.maxDepth}; deeper cycles may exist.`:"No circular dependencies found.":void 0,toJson:e=>e,render:e=>{let t=e.cycles.filter(r=>r.kind==="real"),n=e.cycles.filter(r=>r.kind==="module-hierarchy");for(let r=0;r<t.length;r++){console.log(`
514
514
  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(`
515
515
  ${t.length} real cycle(s) found.`),e.truncated&&console.log(`(search truncated at depth ${e.maxDepth} \u2014 deeper cycles may exist)`),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.)`)}}),Hk=Ke({commandName:"architecture",query:({db:e,opts:t})=>Ls(e,{scope:w(t,"scope")}),emptyMessage:e=>e.configured?void 0:"No architecture boundaries configured. Add architecture.boundaries to .scipquery.json.",render:e=>{if(console.log(`Mapped ${e.coverage.mappedFiles}/${e.coverage.totalFiles} indexed file(s) across ${e.boundaries.length} boundary(ies); ${e.policyCoverage.declaredRows}/${e.policyCoverage.totalBoundaries} dependency row(s) declared.`),e.policyCoverage.missingRows.length>0){let t=e.policyCoverage.requiresCompletePolicy?" [violates requireCompletePolicy]":"";console.log(`Missing dependency rows: ${e.policyCoverage.missingRows.join(", ")}${t}`)}if(e.coverage.unmappedFiles.length>0&&console.log(`Unmapped files: ${e.coverage.unmappedFiles.length}`),e.coverage.ambiguousFiles.length>0){console.log(`Ambiguous files: ${e.coverage.ambiguousFiles.length}`);for(let t of e.coverage.ambiguousFiles.slice(0,5))console.log(` ${t.file} -> ${t.boundaries.join(", ")}`)}if(e.forbiddenEdges.length>0){console.log(`
516
516
  Forbidden boundary edges (${e.forbiddenEdges.length}):`);for(let t of e.forbiddenEdges){console.log(` ${t.from} -> ${t.to}: ${t.fileEdgeCount} file edge(s), ${t.importerCount} importer(s), ${t.importedFileCount} imported file(s)`);for(let n of t.examples)console.log(` ${n.fromFile} -> ${n.toFile}`)}}else console.log(`
517
- No declared boundary violations found.`);if(e.edges.length>0){console.log(`
517
+ No declared boundary violations found.`);if(e.staleAllowances.length>0){console.log(`
518
+ Stale dependency allowances (${e.staleAllowances.length}): declared but unused, so the policy is wider than the code requires.`);for(let t of e.staleAllowances)console.log(` ${t.from} -> ${t.to}`)}if(e.boundaryLimits.length>0){console.log(`
519
+ Boundaries over configured limits (${e.boundaryLimits.length}):`);for(let t of e.boundaryLimits)console.log(` ${t.boundary}: ${t.kind} ${t.observed} exceeds limit ${t.limit}`)}if(e.testBoundaryViolations.length>0){console.log(`
520
+ Test boundary violations (${e.testBoundaryViolations.length}): a test reaches further than the boundary of the code it covers is allowed to reach.`);for(let t of e.testBoundaryViolations.slice(0,20)){let n=t.ownerBoundary??"(no subject found)";console.log(` ${t.testFile} [${n}] -> ${t.importedBoundary} (${t.importedFile})`)}e.testBoundaryViolations.length>20&&console.log(` ... +${e.testBoundaryViolations.length-20} more`)}if(e.fragileEdges.length>0){console.log(`
521
+ Single-import boundary edges (${e.fragileEdges.length} of ${e.edges.length}): the whole boundary dependency is carried by one file-level import. Breadth alone does not establish importance -- inspect before concluding either way.`);for(let t of e.fragileEdges.slice(0,10)){let n=t.examples[0];console.log(` ${t.from} -> ${t.to}${n?` (${n.fromFile} -> ${n.toFile})`:""}`)}e.fragileEdges.length>10&&console.log(` ... +${e.fragileEdges.length-10} more`)}if(e.coarseBoundaries.length>0){console.log(`
522
+ Boundaries too coarse to check (${e.coarseBoundaries.length}): these own an internal dependency cycle that the boundary graph cannot express, so requireAcyclic reports nothing about the code inside them.`);for(let t of e.coarseBoundaries){console.log(` ${t.boundary}: ${t.subUnits.join(" <-> ")}`);for(let n of t.narrowestEdges){console.log(` narrowest: ${n.from} -> ${n.to} (${n.fileEdgeCount} file edge(s))`);for(let r of n.examples.slice(0,3))console.log(` ${r.fromFile} -> ${r.toFile}`)}}}if(e.edges.length>0){console.log(`
518
523
  Boundary graph (${e.edges.length} directed edge(s)):`);for(let t of e.edges)console.log(` ${t.from} -> ${t.to} ${t.policyStatus.padEnd(10)} ${t.fileEdgeCount} file edge(s)`)}if(e.reciprocalPairs.length>0){console.log(`
519
524
  Reciprocal boundary pairs (${e.reciprocalPairs.length}):`);for(let t of e.reciprocalPairs)console.log(` ${t.boundaries[0]} <-> ${t.boundaries[1]} ${t.forward.fileEdgeCount}/${t.reverse.fileEdgeCount} file edge(s)`)}if(e.cycles.length>0){console.log(`
520
525
  Strongly connected boundary groups (${e.cycles.length}):`);for(let t of e.cycles){let n=t.violatesPolicy?" [violates requireAcyclic]":"";console.log(` { ${t.boundaries.join(", ")} }${n}`);for(let r of t.narrowestEdges)console.log(` inspect ${r.from} -> ${r.to}: ${r.fileEdgeCount} file edge(s)`)}}}}),Wk=Ke({commandName:"deep-chains",query:({db:e,opts:t})=>Ms(e,{limit:L(t,"limit",10),scope:w(t,"scope"),minDepth:C(t,"minDepth",3)}),emptyMessage:e=>e.length===0?"No deep chains found.":void 0,render:e=>{for(let t=0;t<e.length;t++){console.log(`
521
- Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].components){let r=n.length===1?n[0]:`{ ${n.join(", ")} } (cycle)`;console.log(` \u2192 ${r}`)}console.log(` Tier: ${e[t].actionTier} Risk: ${e[t].chainKind}`),console.log(` Recommendation: ${e[t].recommendation}`),console.log(` Evidence: ${e[t].evidenceReasons.join("; ")}`)}}}),Fm=[$r({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[u("-n, --limit <n>","Number of results",x,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")],docs:$("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>xs(e,{limit:L(t,"limit",30),scope:w(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"Count files referencing an exact symbol; top JSON rows include exact symbol identity",options:P([u("-n, --limit <n>","Number of results for top mode",x,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:_k},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:P([u("-n, --limit <n>","Number of results for top mode",x,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:qk},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:P([u("-n, --limit <n>","Number of results for top mode",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:Bk},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--max-depth <n>","Bound DFS search depth",x,10)]),renderShape:"custom",docs:$("Graph"),handler:Vk},{id:"architecture",command:"architecture",description:"Evaluate project-owned architectural boundaries and dependency rules",options:P([u("-s, --scope <path>","Limit to files matching path")]),evidence:"mixed",renderShape:"custom",docs:$("Graph",["scip-query architecture --json"]),handler:Hk},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:P([u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-fan-in <n>","Minimum fan-in",x,2),u("--min-fan-out <n>","Minimum fan-out",x,2),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:$("Graph"),handler:Mk},{id:"deep-chains",command:"deep-chains",description:"Find the longest condensed dependency-component chains",options:P([u("-n, --limit <n>","Number of chains to show",x,10),u("-s, --scope <path>","Limit to files matching path"),u("--min-depth <n>","Minimum chain depth",x,3),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:Wk},Cr({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[u("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:$("Graph"),query:({db:e,args:t,budget:n})=>Wt(e,String(t[0]),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e?void 0:se(t,String(n[0]),"Symbol not found."),before:(e,{db:t,args:n})=>{e&&(oe(t,String(n[0])),console.log(`Symbol: ${e.shortName}
526
+ Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].components){let r=n.length===1?n[0]:`{ ${n.join(", ")} } (cycle)`;console.log(` \u2192 ${r}`)}console.log(` Tier: ${e[t].actionTier} Risk: ${e[t].chainKind}`),console.log(` Recommendation: ${e[t].recommendation}`),console.log(` Evidence: ${e[t].evidenceReasons.join("; ")}`)}}}),Fm=[$r({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[u("-n, --limit <n>","Number of results",x,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")],docs:$("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>xs(e,{limit:L(t,"limit",30),scope:w(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"Count files referencing an exact symbol; top JSON rows include exact symbol identity",options:P([u("-n, --limit <n>","Number of results for top mode",x,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:_k},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:P([u("-n, --limit <n>","Number of results for top mode",x,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:Bk},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:P([u("-n, --limit <n>","Number of results for top mode",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:qk},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:P([u("-s, --scope <path>","Limit to files matching path"),u("--max-depth <n>","Bound DFS search depth",x,10)]),renderShape:"custom",docs:$("Graph"),handler:Vk},{id:"architecture",command:"architecture",description:"Evaluate project-owned architectural boundaries and dependency rules",options:P([u("-s, --scope <path>","Limit to files matching path")]),evidence:"mixed",renderShape:"custom",docs:$("Graph",["scip-query architecture --json"]),handler:Hk},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:P([u("-n, --limit <n>","Number of results",x,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-fan-in <n>","Minimum fan-in",x,2),u("--min-fan-out <n>","Minimum fan-out",x,2),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:$("Graph"),handler:Mk},{id:"deep-chains",command:"deep-chains",description:"Find the longest condensed dependency-component chains",options:P([u("-n, --limit <n>","Number of chains to show",x,10),u("-s, --scope <path>","Limit to files matching path"),u("--min-depth <n>","Minimum chain depth",x,3),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:Wk},Cr({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[u("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:$("Graph"),query:({db:e,args:t,budget:n})=>Wt(e,String(t[0]),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e?void 0:se(t,String(n[0]),"Symbol not found."),before:(e,{db:t,args:n})=>{e&&(oe(t,String(n[0])),console.log(`Symbol: ${e.shortName}
522
527
  `))},toJson:(e,{db:t,args:n})=>ve(t,String(n[0]),e,"callGraph"),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 Gk=K("complexity",({db:e,args:t,opts:n,budget:r})=>{let i=A(t,0),o=Ra(e,i,{semantic:r.semantic});if(b(n,"json")){I("complexity",t,n,ve(e,i,o,"complexity"),{analysisBudget:r.analysisBudget});return}if(!o)return E.empty(se(e,i,"Symbol not found."));oe(e,i),console.log(`${M(o.relativePath,o.startLine,o.endLine)} ${o.shortName}
523
528
  `),console.log(` LOC: ${o.loc}`),console.log(` Branches: ${o.branches}`),console.log(` Cyclomatic estimate: ${o.cyclomaticEstimate}`),console.log(` Callees: ${o.calleeCount}`),console.log(` Fan-in: ${o.fanIn}`),console.log(` Fan-out: ${o.fanOut}`)}),Uk=le(({db:e,args:t,opts:n})=>{let r=Na(e,{samples:C(n,"samples",50),scope:w(n,"scope")});if(b(n,"json")){I("self-audit",t,n,r);return}if(!r.available)return E.empty("No semantic or source-backed oracle available to audit against.");let i=r.oracleKind==="source"?"source facts":"compiler semantics";console.log(`Sampled ${r.sampleSize} symbols; ${i} oracle answered ${Math.round(r.oracleCoverage*100)}%.
524
529
  `),console.log(`Agreement with ${i} (file-level):`);for(let o of r.scores){let s=o.precision===null?`unverified ${o.unverified} (oracle partial \u2014 no precision claim)`:`precision ${o.precision}`;console.log(` ${o.question.padEnd(11)} ${s} recall ${o.recall} (${o.comparedSymbols} compared, ${o.skippedOraclePartial} skipped: oracle-partial)`)}if(r.topDisagreements.length>0){console.log(`
@@ -537,20 +542,20 @@ ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or
537
542
  `);for(let f of s.skipped)console.log(` skipped ${f.check}: ${f.reason}`);if(s.findings.length===0){console.log("PASS: this change introduces no gate findings.");return}Te("diff gate candidates");let p=s.rootCauseGroups?.filter(f=>f.count>1)??[];if(p.length>0){console.log(`Root-cause groups (${p.length}):`);for(let f of p){console.log(` [${f.check}] ${f.count} finding(s), ${f.severity}${f.actionTier?`, tier: ${f.actionTier}`:""}`),(f.sourceAnalyzer||f.rootCauseKey)&&console.log(` source: ${f.sourceAnalyzer??f.check}${f.rootCauseKey?` root cause: ${f.rootCauseKey}`:""}`);let g=[...new Set([...f.files,...f.relatedFiles])].slice(0,6);g.length>0&&console.log(` files: ${g.join(", ")}`),console.log(` -> ${f.remediation}`)}console.log("")}for(let f of s.findings){if(console.log(` [${f.check}]${f.advisory?" (advisory)":""} ${f.message}`),f.partnerClass){console.log(` partner class: ${f.partnerClass}`);for(let g of f.partnerClassReasons??[])console.log(` reason: ${g}`)}f.citationKind&&console.log(` citation kind: ${f.citationKind}${f.actionTier?` (tier: ${f.actionTier})`:""}`);for(let g of f.citedClaims?.slice(0,2)??[])console.log(` cited claim: ${Dn(g)}`);f.declaredCouplingSuggestion&&console.log(` declare coupling: ${f.declaredCouplingSuggestion.name} (${f.declaredCouplingSuggestion.reason})`),console.log(` -> ${f.remediation}`)}if(a.length===0){console.log(`
538
543
  PASS (advisory only): ${s.findings.length} advisory finding(s) recorded \u2014 none block this diff.`);return}let m=s.findings.length-a.length;console.log(`
539
544
  FAIL: ${a.length} finding(s)${m>0?` (+${m} advisory)`:""}, ${s.rootCauseGroups?.length??s.findings.length} root-cause group(s). Fix or knowingly accept before merging.`),process.exitCode=1}),Nm=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:P([u("--max-depth <n>","Maximum traversal depth",x,5),u("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:$("Impact"),handler:Jk},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:P([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:$("Impact"),handler:Yk},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: architecture regressions plus echo, migration, coordination, doc-drift, unused-param, and new-dead candidates; exit 1 on blocking findings",options:[u("--base <ref>","Git ref to diff against (default: HEAD)"),u("--min-together <n>","Minimum historical co-changes for the partner check",x,6),u("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",x),u("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",x),u("--baseline","Also run the full health-baseline ratchet"),u("--full","Run unbounded semantic and git-history analysis on large indexes"),u("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, twin-partner, coverage-contract, architecture, doc-reference, unused-params, new-dead, baseline",ot,[]),u("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),u("--json","Output as JSON for programmatic consumption")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:$("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:ew},{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([u("--base <ref>","Git ref to diff against (default: HEAD)"),u("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",fe,.7),u("--max-helpers <n>","Maximum new helpers to score (default: all)",x),u("-n, --limit <n>","Maximum findings to report",x,20),u("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:$("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:Xk},{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([u("--min-together <n>","Minimum commits where both files changed",x,4),u("-n, --limit <n>","Maximum pairs to report",x,30),u("--all","Include pairs that already have a dependency edge"),u("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:$("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:zk}];function tw(e){let t=[];for(let i of e.definitions){let o=i.signature?` \u2014 ${i.signature}`:"";t.push(` ${M(i.relativePath,i.startLine,i.endLine)}${o}`),i.source&&t.push(i.source.split(`
540
- `).map((s,a)=>` ${qe(i.startLine+a)} ${s}`).join(`
541
- `))}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 nw=de("imports",{query:({db:e,args:t,budget:n})=>Rs(e,A(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)."}),rw=K("dataflow",({db:e,args:t,opts:n,budget:r})=>{let i=A(t,0),o=ka(e,i,{semantic:r.semantic});if(b(n,"json")){I("dataflow",t,n,ve(e,i,o,"dataflow"),{analysisBudget:r.analysisBudget});return}if(!o)return E.empty(se(e,i,"No dataflow found."));if(oe(e,i),console.log(`${o.shortName} (${o.relativePath})
542
- `),o.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of o.definitionSites)console.log(` ${s.file}:${qe(s.line)}`)}if(o.usageSites.length>0){console.log(`
543
- \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of o.usageSites)console.log(` ${s.file}:${qe(s.line)} in ${s.enclosingShort}`)}if(o.producers.length>0){console.log(`
545
+ `).map((s,a)=>` ${Be(i.startLine+a)} ${s}`).join(`
546
+ `))}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 ${Be(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var nw=de("imports",{query:({db:e,args:t,budget:n})=>Rs(e,A(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)."}),rw=K("dataflow",({db:e,args:t,opts:n,budget:r})=>{let i=A(t,0),o=ka(e,i,{semantic:r.semantic});if(b(n,"json")){I("dataflow",t,n,ve(e,i,o,"dataflow"),{analysisBudget:r.analysisBudget});return}if(!o)return E.empty(se(e,i,"No dataflow found."));if(oe(e,i),console.log(`${o.shortName} (${o.relativePath})
547
+ `),o.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of o.definitionSites)console.log(` ${s.file}:${Be(s.line)}`)}if(o.usageSites.length>0){console.log(`
548
+ \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of o.usageSites)console.log(` ${s.file}:${Be(s.line)} in ${s.enclosingShort}`)}if(o.producers.length>0){console.log(`
544
549
  \u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let s of o.producers)console.log(` ${s.file} ${s.shortName}`)}if(o.consumers.length>0){console.log(`
545
550
  \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of o.consumers)console.log(` ${s.file} ${s.shortName}`)}}),iw=K("slice",({db:e,args:t,opts:n,budget:r})=>{let i=A(t,0),o=b(n,"forward")?"forward":"backward",s=wa(e,i,{direction:o,maxDepth:C(n,"depth",3),semantic:r.semantic});if(b(n,"json")){I("slice",t,n,ve(e,i,s,"slice"),{analysisBudget:r.analysisBudget});return}if(!s)return E.empty(se(e,i,"No slice found."));if(oe(e,i),console.log(`${s.direction} slice of ${s.shortName}
546
551
  `),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}E.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
547
552
  ${a.relationship}`),console.log(`
548
553
  ${s.connectedSymbols.length} connected symbol(s).`)}),Mm=[...Rc,Ee({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:$("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>ms(e,A(t,0)),format:e=>e.relativePath}),Ee({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:$("Navigation"),query:({db:e,args:t})=>fs(e,A(t,0)),format:e=>` ${ie(e.startLine,e.endLine)} ${e.name}`}),Cr({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[u("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:$("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>gs(e,A(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?se(t,A(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>oe(t,A(n,0)),toJson:(e,{db:t,args:n})=>({...Ut(t,A(n,0)),...e}),sections:tw}),Ee({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:$("Navigation"),query:({db:e,args:t})=>hs(e,A(t,0)),format:e=>e.relativePath}),Ee({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:$("Navigation"),query:({db:e,args:t})=>ys(e,A(t,0)),format:e=>e.relativePath}),Mp({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",docs:$("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>bs(e,A(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${ie(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}`)}]}),Ee({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:$("Navigation"),query:({db:e,args:t})=>Ss(e,A(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[u("--full","Run unbounded semantic analysis on large indexes"),u("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:$("Navigation"),handler:nw},Ee({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:$("Navigation"),query:({db:e,args:t})=>ks(e,A(t,0)),format:e=>` ${e.fromFile}`}),Ee({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:$("Navigation"),query:({db:e,args:t})=>$s(e,A(t,0)),format:e=>` ${ie(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>oe(t,A(n,0)),emptyMessage:({db:e,args:t})=>se(e,A(t,0),"No child symbols found."),toJson:(e,{db:t,args:n})=>ve(t,A(n,0),e,"members")}),Ee({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[u("-s, --scope <path>","Limit to files matching path"),u("-n, --limit <n>","Number of results",x,100),u("--full","Run unbounded analysis on large indexes")],docs:$("Navigation"),query:({db:e,args:t,opts:n})=>Os(e,A(t,0),{scope:w(n,"scope"),limit:L(n,"limit",100)}),format:e=>` ${M(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${A(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
549
554
  ${e.length} symbol(s)`)}),$r({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[u("-s, --scope <path>","Limit to files matching path")],docs:$("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>Ns(e,{scope:w(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),Ee({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:$("Navigation"),query:({db:e,args:t})=>_s(e,A(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>oe(t,A(n,0)),emptyMessage:({db:e,args:t})=>se(e,A(t,0),"Symbol not found."),toJson:(e,{db:t,args:n})=>ve(t,A(n,0),e,"hierarchy")}),{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:P([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Navigation"),handler:rw},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:P([u("--forward","Forward slice (what does this affect). Default is backward."),u("--depth <n>","Max transitive depth for backward slice",x,3),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Navigation"),handler:iw}];var ow=K("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=L(n,"limit",20),o=Me(e.config.projectRoot).gitContext?.headCommit,s=$a(e,A(t,0),{semantic:r.semantic,impactDepth:C(n,"impactDepth",3),sliceDepth:C(n,"sliceDepth",3),scope:w(n,"scope"),...o?{gitHead:o}:{}});if(s.warnings.length===1&&s.warnings[0]==="No symbol, file, or module matched target."){if(b(n,"json")){I("plan-context",t,n,{...Ut(e,A(t,0)),...s},{analysisBudget:r.analysisBudget});return}return E.empty(se(e,A(t,0)))}if(b(n,"json")){I("plan-context",t,n,s.matched.symbol?{...Ut(e,A(t,0)),...s}:s,{analysisBudget:r.analysisBudget});return}s.matched.symbol&&oe(e,A(t,0));let a=[{title:"TARGET",rows:sw(s)},{title:"DEFINITIONS",rows:aw(s,i),skipIfEmpty:!0},{title:"REFERENCES",rows:cw(s,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:lw(s,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:dw(s,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:uw(s,i),skipIfEmpty:!0},{title:"SURFACE",rows:pw(s,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:mw(s,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:fw(s,i),skipIfEmpty:!0},{title:"HISTORY",rows:gw(s),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:hw(s),skipIfEmpty:!0}];E.sectionedReport(a)}),_m=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:P([u("--impact-depth <n>","Maximum affected traversal depth",x,3),u("--slice-depth <n>","Maximum backward slice depth",x,3),u("-s, --scope <path>","Limit downstream impact to files matching path"),u("-n, --limit <n>","Rows per section",x,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Planning",["scip-query plan-context parseSymbol"]),handler:ow}];function sw(e){return[`Target: ${e.target}`,`Matched: symbol=${bo(e.matched.symbol)} file=${bo(e.matched.file)} module=${bo(e.matched.module)}`]}function aw(e,t){let n=[];for(let r of e.trace.definitions){let i=r.signature?` -- ${r.signature}`:"";n.push(` ${M(r.relativePath,r.startLine,r.endLine)}${i}`),r.source&&n.push(...r.source.split(`
550
- `).map((o,s)=>` ${String(qe(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${ie(r.startLine,r.endLine)} ${r.shortName}`)),tt(n,t).rows}function cw(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${qe(r.line)} in ${r.enclosingShort}`);return gt(tt(n,t))}function lw(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 gt(tt([...n,...r],t))}function dw(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 gt(tt([...n,...r,...i],t))}function uw(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 gt(tt(n,t))}function pw(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${ie(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return gt(tt(n,t))}function mw(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 gt(tt(n,t))}function fw(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` ${ie(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${M(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}`)),gt(tt(n,t))}function gw(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 hw(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 tt(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function gt(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function bo(e){return e?"yes":"no"}import{existsSync as mn}from"fs";import{existsSync as $w,mkdtempSync as Cw,rmSync as Pw}from"fs";import{tmpdir as Tw}from"os";import{dirname as vo,join as xo}from"path";import{performance as Hm}from"perf_hooks";import{spawnSync as Iw}from"child_process";import{createHash as yw}from"crypto";import{existsSync as bw,mkdirSync as Sw,readFileSync as vw,renameSync as xw,writeFileSync as Rw}from"fs";import{homedir as kw}from"os";import{dirname as ww,join as So}from"path";function qm(e){return yw("sha256").update(e).digest("hex")}function Bm(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?So(t.XDG_CACHE_HOME,"scip-query"):So(kw(),".cache","scip-query"));return So(n,e)}async function Vm(e){let{cachePath:t,url:n,expectedSha256:r}=e;if(bw(t)){let l=qm(vw(t));if(l===r)return{status:"cached",path:t,sha256:l}}let o=await(e.fetchImpl??fetch)(n);if(!o.ok)throw new Error(`failed to download ${n}: HTTP ${o.status}`);let s=Buffer.from(await o.arrayBuffer()),a=qm(s);if(a!==r)throw new Error(`downloaded ${n} checksum mismatch: expected ${r}, got ${a}`);Sw(ww(t),{recursive:!0});let c=`${t}.tmp-${process.pid}`;return Rw(c,s),xw(c,t),{status:"downloaded",path:t,sha256:a}}var Ew=12e4,Um="v1.8.0",jw=`https://github.com/tlaplus/tlaplus/releases/download/${Um}/tla2tools.jar`,Aw="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function Dr(e){let t=e.spawn??Iw,n=Lw(e,t);if(n.missing)return{checker:n.checker,status:"skipped",command:n.command,durationMs:0,exitCode:null,signal:null,timedOut:!1,diagnostics:[{severity:"warning",message:n.missing}],stdout:"",stderr:""};let r=e.timeoutMs??Ew,i=Hm.now(),o;try{o=t(n.command[0],n.command.slice(1),{cwd:n.cwd,encoding:"utf8",timeout:r,maxBuffer:1024*1024*10})}finally{for(let l of n.cleanupPaths??[])Pw(l,{recursive:!0,force:!0})}let s=Math.round(Hm.now()-i),a=o.error?.name==="ETIMEDOUT"||o.signal==="SIGTERM"&&s>=r,c=a?"timed-out":o.status===0?"passed":"failed";return{checker:n.checker,status:c,command:n.command,durationMs:s,exitCode:o.status,signal:o.signal,timedOut:a,diagnostics:Dw(c,o.stdout??"",o.stderr??""),stdout:o.stdout??"",stderr:o.stderr??""}}function Lw(e,t){let n=e.checker;if(n==="none")return{checker:"none",command:["<none>"],cwd:e.projectRoot,missing:"model checker skipped by --checker none"};if(n==="apalache"||n==="auto"&&De(Wm(e),t)){let o=Wm(e);return De(o,t)?{checker:"apalache",command:[o,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:vo(e.specPath)}:Lr("apalache",`Apalache binary is not available: ${o}`)}let r=Ro(e),i=De("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!r)return Lr(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!i)return Lr(n==="sany"?"sany":"tlc","java is not available on PATH");let o=n==="sany"?"sany":n==="tlc"||e.configPath?"tlc":"sany";if(o==="sany")return{checker:o,command:["java","-cp",r,"tla2sany.SANY",e.specPath],cwd:vo(e.specPath)};let s=e.metaDir??Cw(xo(Tw(),"scip-tla-tlc-"));return{checker:o,command:["java","-cp",r,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:vo(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Lr("none",`unknown checker mode: ${n}`)}function Wm(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function Ro(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,Jm(t),xo(e.projectRoot,"tla2tools.jar"),xo(e.projectRoot,"tools","tla2tools.jar")].filter(r=>typeof r=="string"&&r.length>0).find(r=>$w(r))??null}function Jm(e=process.env){return Bm("tla2tools.jar",e)}async function zm(e={}){let t=e.cachePath??Jm(e.env),n=e.expectedSha256??Aw,r=e.version??Um,i=e.url??jw;return{...await Vm({cachePath:t,url:i,expectedSha256:n,fetchImpl:e.fetchImpl}),version:r,url:i}}function Dw(e,t,n){if(e==="passed")return[{severity:"info",message:"model checker completed successfully"}];if(e==="timed-out")return[{severity:"error",message:"model checker timed out"}];let r=[...Gm(n),...Gm(t)].slice(0,20);return r.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:r.map(i=>({severity:"error",message:i}))}function Gm(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Lr(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as Fw}from"crypto";import{readFileSync as Qm}from"fs";import{join as Ym}from"path";var Xm=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),Zm=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),ef=new Set(["readFileSync","existsSync","statSync"]),Ow=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,Nw=/^\s*SELECT\b/i;function tf(e){return Ow.test(e)?"write":Nw.test(e)?"read":null}var Mw=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function _w(e,t){let n=e.match(Mw);if(!n)return!1;let r=e.slice(n[0].length);return new RegExp(`^${Le(t)}\\b`).test(r)}function nf(e,t,n,r=[],i=[]){let o=[],s=Vw(e,t,o),a=s.aliases,c=Hw(t),l=Ww(t),d=Gw(t),p=zw(e,t,o),m=Qw(e,t,o);n&&Yw(t,n,i,o);let f=new Map((n?.actions??[]).map(v=>[v.name,v])),g=new Set(p.flatMap(v=>v.referents.map(k=>k.match?.symbol).filter(Boolean))),h=new Set((m?.referents??[]).map(v=>v.match?.symbol).filter(Boolean)),y=Xw(e,t,p,a,c,l,d,g,h,o,f),S=t$(e,p,a,c,l,d,o,f);return r$(e,p,o),i$(t,r,o),{modelParse:n?.modelParse??"unavailable",modelVariables:n?.variables??[],modelOperators:n?.operators??[],modelActionFacts:n?.actions??[],mappedVariables:Object.keys(t.variables).length,mappedActions:Object.keys(t.actions).length,resolvedReferents:wo(p.flatMap(v=>v.referents))+wo(s.referents)+wo(m?.referents??[]),staticWrites:y,staticReads:S,waivers:w$(t),checkedInvariants:[...i],traceStepsChecked:r.length,findings:o,findingGroups:qw(o)}}function qw(e){let t=new Map;for(let n of e){let r=`${n.category}:${n.modelElement??"-"}`,i=t.get(r);i||(i={groupKey:r,category:n.category,modelElement:n.modelElement,severity:n.severity,count:0,findingIds:[]},t.set(r,i)),i.count+=1,i.findingIds.push(n.id),i.severity=Bw(i.severity,n.severity)}return[...t.values()].sort((n,r)=>r.count-n.count||Fr(r.severity)-Fr(n.severity)||n.groupKey.localeCompare(r.groupKey))}function Bw(e,t){return Fr(t)>Fr(e)?t:e}function Fr(e){return e==="error"?2:e==="warning"?1:0}function Vw(e,t,n){let r=[],i=[];for(let[o,s]of Object.entries(t.variables)){let a=new Set(s.aliases),c=!!s.waive;for(let l of s.code){let d=Mr(e,l,n,o);i.push(d);let p=d.match;if(!p){c||n.push(W("missing-referent","error","compiler-symbol",{modelElement:o,codeRef:l,message:`TLA+ variable ${o} maps to missing TypeScript referent ${l}.`,why:["The mapping contract must point at live compiler-indexed code before conformance can be checked."],remediation:`Update variables.${o}.code to a live symbol, or remove the variable from the model mapping.`}));continue}b$(e,o,l,p,n,c),s.aliases.length===0&&a.add(qo(p.symbol))}for(let l of a)r.push({variable:o,alias:l})}return{aliases:k$(r),referents:i}}function Hw(e){let t=[];for(let[n,r]of Object.entries(e.variables))r.resource&&t.push({variable:n,path:r.resource.path});return t}function Ww(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.statements??[])t.push({variable:n,pattern:i.pattern,regex:new RegExp(i.pattern)});return t}function Gw(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.ormCalls??[]){let{write:o,read:s}=mo(i);t.push({variable:n,table:i.table,writeMethods:new Set(o),readMethods:new Set(s)})}return t}function Uw(e,t,n,r,i,o){return rf(e,t,(s,a,c)=>ht(e,s,a,c,n,r,i,o))}function Jw(e,t,n,r,i,o){return rf(e,t,(s,a,c)=>Nr(e,s,a,c,n,r,i,o))}function rf(e,t,n){let r=Wt(e,t,{semantic:!1});if(!r)return[];let i=[],o=new Set;for(let s of r.callees){if(o.has(s.symbol))continue;o.add(s.symbol);let a=xn(e,s.symbol).match;if(a)for(let c of n(a.relativePath,a.startLine,a.endLine))i.push({...c,via:s.shortName})}return i}function zw(e,t,n){return Object.entries(t.actions).map(([r,i])=>{let o=i.code.map(s=>{let a=fo(s),c="error"in a?s:a.ref,d=Mr(e,c,n,r).match;return d?(S$(e,r,s,d,n),"error"in a||!a.window?{ref:s,match:d}:Kw(a.window,d)?(n.push(W("invalid-line-window","error","compiler-symbol",{modelElement:r,codeRef:s,file:d.relativePath,startLine:d.startLine,endLine:d.endLine,message:`TLA+ action ${r} codeRef line window L${a.window.startLine}-L${a.window.endLine} falls outside ${Q(d.symbol)}'s actual span L${d.startLine+1}-L${d.endLine+1} in ${d.relativePath}.`,why:[`${s} resolves to ${Q(d.symbol)} at ${d.relativePath}:${d.startLine+1}-${d.endLine+1}.`,"The requested window does not fall entirely inside that span."],remediation:`Update the @L${a.window.startLine}-L${a.window.endLine} window in actions.${r}.code to fall within L${d.startLine+1}-L${d.endLine+1}, or drop the window to cover the whole function.`})),{ref:s,match:null}):{ref:s,match:d,window:{startLine:a.window.startLine-1,endLine:a.window.endLine-1}}):(n.push(W("missing-referent","error","compiler-symbol",{modelElement:r,codeRef:s,message:`TLA+ action ${r} maps to missing TypeScript referent ${s}.`,why:["The action cannot be compared to code because the mapped symbol did not resolve in the SCIP index."],remediation:`Update actions.${r}.code to a live function or method symbol.`})),{ref:s,match:null})});return{name:r,mapping:i,referents:o}})}function Kw(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function Qw(e,t,n){let r=t.init;if(!r)return;let i=!!r.waive,o=r.codeRefs.map(s=>{let a=Mr(e,s,n,"Init"),c=a.match;return c?v$(e,s,c,n,i):i||n.push(W("missing-referent","error","compiler-symbol",{modelElement:"Init",codeRef:s,message:`TLA+ Init maps to missing TypeScript referent ${s}.`,why:["The Init mapping must point at live compiler-indexed code before conformance can be checked."],remediation:"Update init.codeRefs to a live function or method symbol, or remove the stale entry."})),a});return{mapping:r,referents:o}}function Yw(e,t,n,r){let i=new Set(t.variables),o=new Set(t.operators),s=new Set(n);for(let a of Object.keys(e.variables))i.has(a)||r.push(W("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ variable ${a} is not declared in the module.`,why:["The mapping names a model variable, but the TLA+ module text does not declare it with VARIABLE(S)."],remediation:`Declare ${a} in the TLA+ module or remove it from the mapping.`}));for(let a of Object.keys(e.actions))o.has(a)||r.push(W("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ action ${a} is not defined in the module.`,why:["The mapping names a model action, but the TLA+ module text has no matching operator definition."],remediation:`Define ${a} == ... in the TLA+ module or update the mapping action name.`}));for(let a of t.actions){let c=e.actions[a.name];c&&(Km({action:a.name,field:"writes",modelValues:a.writes,mappingValues:c.writes,missingInMappingCategory:"model-mapping-write",missingInModelCategory:"model-mapping-write",findings:r,file:t.path,isWaived:l=>!!c.waive?.writes.includes(l)}),Km({action:a.name,field:"reads",modelValues:a.reads,mappingValues:c.reads,missingInMappingCategory:"model-mapping-read",missingInModelCategory:"model-mapping-read",findings:r,file:t.path}))}for(let a of e.invariants)s.has(a)||r.push(W("missing-invariant","warning","model-text",{modelElement:a,file:t.path,message:`Mapping lists invariant ${a}, but the checker config does not include it.`,why:["The model mapping names an invariant that was not found in INVARIANT lines of the selected config."],remediation:`Add INVARIANT ${a} to the config used for this run, or remove it from the mapping invariants list.`}))}function Km(e){let t=new Set(e.modelValues),n=new Set(e.mappingValues),r=e.isWaived??(()=>!1);for(let i of t)n.has(i)||r(i)||e.findings.push(W(e.missingInMappingCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`TLA+ action ${e.action} ${e.field==="writes"?"writes":"reads"} ${i}, but the mapping does not declare that ${e.field.slice(0,-1)}.`,why:[`SANY-derived model facts list ${i} in ${e.action}.${e.field}, while the mapping omits it.`],remediation:`Add ${i} to actions.${e.action}.${e.field}, or update the TLA+ model if the ${e.field.slice(0,-1)} is unintended.`}));for(let i of n)t.has(i)||r(i)||e.findings.push(W(e.missingInModelCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`Mapping declares ${e.action}.${e.field} includes ${i}, but the SANY model facts do not.`,why:[`The mapping says ${e.action} ${e.field==="writes"?"writes":"reads"} ${i}, but the parsed TLA+ action does not show that model-side fact.`],remediation:`Update the TLA+ action to ${e.field==="writes"?"prime":"reference"} ${i}, remove the mapping declaration, or add a waiver if static evidence cannot represent the model boundary.`}))}function Xw(e,t,n,r,i,o,s,a,c,l,d){let p=[];for(let f of n){let g=[];for(let h of f.referents){if(!h.match)continue;let y=h.window??{startLine:h.match.startLine,endLine:h.match.endLine},S=ht(e,h.match.relativePath,y.startLine,y.endLine,r,i,o,s);g.push(...S),p.push(...S);let v=new Set(f.mapping.writes),k=Uw(e,h.match.symbol,r,i,o,s).filter(R=>v.has(R.variable));g.push(...k),p.push(...k)}e$(f,g,l,d.get(f.name))}let m=t.unmappedWriteScope==="actions"?[]:g$(e,t);for(let f of m)for(let g of ht(e,f,0,Number.POSITIVE_INFINITY,r,i,o,s))p.push(g),Zw(g)&&(g.enclosingSymbol&&(a.has(g.enclosingSymbol)||c.has(g.enclosingSymbol))||l.push(W("unmapped-write","error","static-action",{modelElement:g.variable,codeRef:g.enclosingSymbol??`${g.file}:${g.line+1}`,file:g.file,startLine:g.line,endLine:g.line,message:`Modeled variable ${g.variable} is written outside any mapped TLA+ action.`,why:[`The static source scan found ${g.target} at ${g.file}:${g.line+1}.`,g.enclosingShort?`The write is inside ${g.enclosingShort}, which is not mapped as a model action.`:"The write is outside an indexed callable definition."],remediation:`Map the enclosing code to a TLA+ action, remove the write, or remove ${g.variable} from the modeled slice if it is intentionally out of scope.`})));return Po(p)}function Zw(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function e$(e,t,n,r){let i=new Set(e.mapping.writes),o=new Set(t.map(a=>a.variable)),s=new Set(r?.writes??[]);for(let a of t)r&&!s.has(a.variable)&&!un(e,"write",a.variable)&&n.push(W("model-code-write","error","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`Code for TLA+ action ${e.name} writes ${a.variable}, but the SANY model action does not prime it.`,why:[`The code writes ${a.target} at ${a.file}:${a.line+1}${Or(a.via)}.`,`SANY-derived model facts for ${e.name} list writes: ${r.writes.join(", ")||"none"}.`],remediation:`Prime ${a.variable} in the TLA+ action, remove the code write from this action, or remap the code to the correct action.`})),!i.has(a.variable)&&!un(e,"write",a.variable)&&n.push(W("undeclared-write","error","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`TLA+ action ${e.name} writes modeled variable ${a.variable}, but the mapping does not declare that write.`,why:[`The code writes ${a.target} at ${a.file}:${a.line+1}${Or(a.via)}.`],remediation:`Add ${a.variable} to actions.${e.name}.writes, update the model action, or change the code so it no longer mutates that modeled variable.`}));for(let a of i)!o.has(a)&&!un(e,"write",a)&&n.push(W("missing-write-evidence","warning","unknown",{modelElement:e.name,message:`TLA+ action ${e.name} declares a write to ${a}, but no direct source write was found.`,why:["The write may happen through an alias, callback, dependency, or runtime side effect that static scanning could not prove."],remediation:`Add a more precise variable alias, add the write sink as a mapped action referent, provide a trace, or waive actions.${e.name}.writes.${a} with a specific reason.`}))}function t$(e,t,n,r,i,o,s,a){let c=[];for(let l of t){let d=[];for(let p of l.referents){if(!p.match)continue;let m=p.window??{startLine:p.match.startLine,endLine:p.match.endLine},f=Nr(e,p.match.relativePath,m.startLine,m.endLine,n,r,i,o);d.push(...f),c.push(...f);let g=new Set(l.mapping.reads),h=Jw(e,p.match.symbol,n,r,i,o).filter(y=>g.has(y.variable));d.push(...h),c.push(...h)}n$(l,d,s,a.get(l.name))}return To(c)}function n$(e,t,n,r){let i=new Set(e.mapping.reads),o=new Set(t.map(a=>a.variable)),s=new Set(r?.reads??[]);for(let a of t)r&&!s.has(a.variable)&&n.push(W("model-code-read","warning","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`Code for TLA+ action ${e.name} reads ${a.variable}, but the SANY model action does not reference it.`,why:[`The code reads ${a.target} at ${a.file}:${a.line+1}${Or(a.via)}.`,`SANY-derived model facts for ${e.name} list reads: ${r.reads.join(", ")||"none"}.`],remediation:`Reference ${a.variable} in the TLA+ action, remove the code read from this action, or remap the code to the correct action.`})),!i.has(a.variable)&&!un(e,"read",a.variable)&&n.push(W("undeclared-read","warning","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`TLA+ action ${e.name} reads modeled variable ${a.variable}, but the mapping does not declare that read.`,why:[`The code reads ${a.target} at ${a.file}:${a.line+1}${Or(a.via)}.`],remediation:`Add ${a.variable} to actions.${e.name}.reads, update the model action, or waive the read with a specific reason if it is intentionally outside the model step.`}));for(let a of i)!o.has(a)&&!un(e,"read",a)&&n.push(W("missing-read-evidence","warning","unknown",{modelElement:e.name,message:`TLA+ action ${e.name} declares a read of ${a}, but no direct source read was found.`,why:["The read may happen through an alias, callback, dependency, or runtime side effect that static scanning could not prove."],remediation:`Add a more precise variable alias, add the read source as a mapped action referent, provide a trace, or waive actions.${e.name}.reads.${a} with a specific reason.`}))}function r$(e,t,n){for(let r of t){if(r.mapping.calls.length===0)continue;let i=r.mapping.calls.map(s=>Mr(e,s,n,r.name));for(let s of i)s.match||n.push(W("missing-referent","error","compiler-symbol",{modelElement:r.name,codeRef:s.ref,message:`actions.${r.name}.calls contains missing TypeScript referent ${s.ref}.`,why:["Declared call checks require the expected callee to resolve in the SCIP index."],remediation:`Update actions.${r.name}.calls to a live symbol or remove the stale call expectation.`}));let o=new Set(i.map(s=>s.match?.symbol).filter(Boolean));for(let s of r.referents){if(!s.match)continue;let a=Wt(e,s.match.symbol),c=new Set(a?.callees.map(l=>l.symbol)??[]);for(let l of o)c.has(l)||n.push(W("missing-call","error","compiler-symbol",{modelElement:r.name,codeRef:s.ref,file:s.match.relativePath,startLine:s.match.startLine,endLine:s.match.endLine,message:`TLA+ action ${r.name} no longer calls ${Q(l)} from ${s.ref}.`,why:["The mapping declares a call dependency that is absent from the current compiler-resolved call graph."],remediation:`Update actions.${r.name}.calls, update the TLA+ action, or restore the code path if the call is required.`}))}}}function i$(e,t,n){for(let[r,i]of t.entries()){let o=e.actions[i.action];if(!o){n.push(W("trace","error","trace",{modelElement:i.action,codeRef:i.code,message:`Trace step ${r} uses action ${i.action}, which is not mapped.`,why:["Every observed trace action must map to a TLA+ action before trace conformance can be checked."],remediation:`Add actions.${i.action} to the mapping, or fix the trace action name.`}));continue}let s=R$(i),a=new Set(o.writes);for(let c of s)a.has(c)||n.push(W("trace","error","trace",{modelElement:i.action,codeRef:i.code,message:`Trace step ${r} changed ${c}, but action ${i.action} does not declare that write.`,why:["The runtime trace observed a state change outside the action write set."],remediation:`Update actions.${i.action}.writes, update the TLA+ model, or investigate the code path that changed ${c}.`}))}}function ht(e,t,n,r,i,o=[],s=[],a=[]){let c=o$(e,t,n,r,i,o,s,a);return c||m$(e,t,n,r,i,o,s,a)}function Nr(e,t,n,r,i,o=[],s=[],a=[]){let c=s$(e,t,n,r,i,o,s,a);return c||f$(e,t,n,r,i,o,s,a)}function o$(e,t,n,r,i,o=[],s=[],a=[]){let c=Br(e,t);if(!c)return null;let l=[],d=p=>{if(!(p.startPosition.row>r||p.endPosition.row<n)){a$(e,t,p,i,l),of(e,t,p,o,"write",l),sf(e,t,p,s,"write",l),af(e,t,p,a,"write",l);for(let m of p.children)d(m)}};return d(c.rootNode),Po(l)}function s$(e,t,n,r,i,o=[],s=[],a=[]){let c=Br(e,t);if(!c)return null;let l=[],d=p=>{if(!(p.startPosition.row>r||p.endPosition.row<n)){d$(e,t,p,i,l),of(e,t,p,o,"read",l),sf(e,t,p,s,"read",l),af(e,t,p,a,"read",l);for(let m of p.children)d(m)}};return d(c.rootNode),To(l)}function a$(e,t,n,r,i){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let o=n.childForFieldName("left")??n.namedChild(0);o&&dn(e,t,o,"assignment",r,i);return}if(n.type!=="variable_declarator"){if(n.type==="pair"){let o=n.childForFieldName("key")??n.namedChild(0);o&&dn(e,t,o,"object-field",r,i);return}if(n.type==="update_expression"){let o=n.namedChildren.find(s=>s.type!=="++"&&s.type!=="--")??n.namedChild(0);o&&dn(e,t,o,"update",r,i);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let o=n.namedChild(0);o&&dn(e,t,o,"delete",r,i);return}if(n.type==="call_expression"){let o=n.childForFieldName("function")??n.namedChild(0);if(!o||!lf(o))return;dn(e,t,o,"mutation-call",r,i)}}}function of(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?$o(s):null;if(!a||!(i==="write"?Zm:ef).has(a))return;let d=n.childForFieldName("arguments")?.namedChild(0);if(!d)return;let p=d.text;for(let m of r){if(!p.includes(m.path))continue;let f=je(e,t,n.startPosition.row);o.push({variable:m.variable,alias:m.path,file:t,line:n.startPosition.row,target:`${a}(${p})`,kind:"resource",enclosingSymbol:f?.symbol,enclosingShort:f?Q(f.symbol):void 0})}}function $o(e){if(e.type==="identifier")return e.text;if(e.type==="member_expression"){let t=e.namedChild(e.namedChildCount-1);return t?t.text:null}return null}function sf(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("arguments");if(s)for(let a of s.namedChildren){let c=c$(a);if(c!==null&&tf(c)===i)for(let l of r){if(!l.regex.test(c))continue;let d=je(e,t,n.startPosition.row),p=n.childForFieldName("function")??n.namedChild(0),m=(p&&$o(p))??"call";o.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${m}(${l$(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?Q(d.symbol):void 0})}}}function c$(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function l$(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function af(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?$o(s):null;if(!a)return;let l=n.childForFieldName("arguments")?.namedChild(0);if(!l)return;let d=l.text.trim();for(let p of r){if(!cf(p,a,d,i))continue;let m=je(e,t,n.startPosition.row);o.push({variable:p.variable,alias:p.table,file:t,line:n.startPosition.row,target:`${a}(${d})`,kind:"orm-call",enclosingSymbol:m?.symbol,enclosingShort:m?Q(m.symbol):void 0})}}function cf(e,t,n,r){return n!==e.table?!1:r==="write"?e.writeMethods.has(t):e.readMethods.has(t)||t==="from"&&e.readMethods.has("select")}function d$(e,t,n,r,i){if(!(!u$(n)||p$(n)))for(let o of r){if(n.text!==o.alias)continue;let s=je(e,t,n.startPosition.row);i.push({variable:o.variable,alias:o.alias,file:t,line:n.startPosition.row,target:n.text,kind:"identifier",enclosingSymbol:s?.symbol,enclosingShort:s?Q(s.symbol):void 0})}}function u$(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function p$(e){let t=e.parent;for(;t;){if(t.type==="assignment_expression"||t.type==="augmented_assignment_expression"){let n=t.childForFieldName("left")??t.namedChild(0);return!!(n&&ko(n,e))}if(t.type==="update_expression"||t.type==="unary_expression"&&/^\s*delete\b/.test(t.text))return!0;if(t.type==="pair"){let n=t.childForFieldName("key")??t.namedChild(0);return!!(n&&ko(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&lf(n)&&ko(n,e))return!0}if(t.type.endsWith("statement")||t.type==="function_declaration"||t.type==="method_definition")return!1;t=t.parent}return!1}function ko(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function lf(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&Xm.has(t.text))}function dn(e,t,n,r,i,o){for(let s of i){if(!x$(s.alias,n.text))continue;let a=je(e,t,n.startPosition.row);o.push({variable:s.variable,alias:s.alias,file:t,line:n.startPosition.row,target:n.text,kind:r,enclosingSymbol:a?.symbol,enclosingShort:a?Q(a.symbol):void 0})}}function m$(e,t,n,r,i,o=[],s=[],a=[]){let l=Qm(Ym(e.config.projectRoot,t),"utf8").split(/\r?\n/),d=[],p=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=p;m+=1){let f=l[m]??"";for(let g of i){if(_w(f,g.alias))continue;let h=Le(g.alias);if(!new RegExp(`(?:\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${h}\\b\\s*\\.\\s*(?:${[...Xm].join("|")})\\s*\\(|\\b${h}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(f))continue;let S=je(e,t,m);d.push({variable:g.variable,alias:g.alias,file:t,line:m,target:f.trim(),kind:"source-scan",enclosingSymbol:S?.symbol,enclosingShort:S?Q(S.symbol):void 0})}df(e,t,m,f,o,Zm,d),uf(e,t,m,f,s,"write",d),pf(e,t,m,f,a,"write",d)}return Po(d)}function f$(e,t,n,r,i,o=[],s=[],a=[]){let l=Qm(Ym(e.config.projectRoot,t),"utf8").split(/\r?\n/),d=[],p=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=p;m+=1){let f=l[m]??"";for(let g of i){let h=Le(g.alias);if(!new RegExp(`\\b${h}\\b`).test(f)||new RegExp(`\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=|\\.|\\[)`).test(f))continue;let y=je(e,t,m);d.push({variable:g.variable,alias:g.alias,file:t,line:m,target:f.trim(),kind:"source-scan",enclosingSymbol:y?.symbol,enclosingShort:y?Q(y.symbol):void 0})}df(e,t,m,f,o,ef,d),uf(e,t,m,f,s,"read",d),pf(e,t,m,f,a,"read",d)}return To(d)}function df(e,t,n,r,i,o,s){if(i.length!==0)for(let a of o){let c=r.indexOf(`${a}(`);if(c===-1)continue;let l=r.slice(c+a.length);for(let d of i){if(!l.includes(d.path))continue;let p=je(e,t,n);s.push({variable:d.variable,alias:d.path,file:t,line:n,target:r.trim(),kind:"resource",enclosingSymbol:p?.symbol,enclosingShort:p?Q(p.symbol):void 0})}}}function uf(e,t,n,r,i,o,s){if(i.length!==0&&tf(r)===o)for(let a of i){if(!a.regex.test(r))continue;let c=je(e,t,n);s.push({variable:a.variable,alias:a.pattern,file:t,line:n,target:r.trim(),kind:"statement",enclosingSymbol:c?.symbol,enclosingShort:c?Q(c.symbol):void 0})}}function pf(e,t,n,r,i,o,s){if(i.length!==0)for(let a of r.matchAll(/\.([A-Za-z_$][\w$]*)\s*\(\s*([^,)\s][^,)]*?)\s*\)/g)){let c=a[1],l=a[2].trim();for(let d of i){if(!cf(d,c,l,o))continue;let p=je(e,t,n);s.push({variable:d.variable,alias:d.table,file:t,line:n,target:r.trim(),kind:"orm-call",enclosingSymbol:p?.symbol,enclosingShort:p?Q(p.symbol):void 0})}}}function g$(e,t){let n=t.scope??[];return n.length===0?[]:e.all("SELECT relative_path FROM documents ORDER BY relative_path").map(i=>i.relative_path).filter(i=>n.some(o=>i.includes(o)))}function Mr(e,t,n,r){let i=xn(e,t),o=i.match??(t.includes("#")?xn(e,t.replace("#","/")).match:null);return i.match&&i.total>1&&!h$(t)&&n.push(W("ambiguous-referent","warning","compiler-symbol",{modelElement:r,codeRef:t,file:i.match.relativePath,startLine:i.match.startLine,endLine:i.match.endLine,message:`Mapping referent ${t} resolved ambiguously to ${Q(i.match.symbol)}.`,why:[`${i.total} indexed definitions share this lookup shape.`,y$(i.candidates)].filter(Boolean),remediation:`Qualify ${t} with a path or fuller symbol name so the mapping cannot drift to another definition.`})),{ref:t,match:o}}function h$(e){return/[/#:]/.test(e)}function y$(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function b$(e,t,n,r,i,o=!1){let s=Co(e,r);if(s===null||$$.has(s)||o)return;let a=Io.has(s);i.push(W("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:a?`TLA+ variable ${t} referent is a type; map the runtime state it describes.`:`TLA+ variable ${t} referent is ${Bt(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${Q(r.symbol)} with SCIP kind ${Bt(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function S$(e,t,n,r,i){let o=Co(e,r);o===null||mf.has(o)||Io.has(o)&&i.push(W("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:`TLA+ action ${t} referent is a type; map the runtime transition code it describes.`,why:[`${n} resolves to ${Q(r.symbol)} with SCIP kind ${Bt(o)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function v$(e,t,n,r,i){let o=Co(e,n);o===null||mf.has(o)||i||Io.has(o)&&r.push(W("invalid-referent-kind","error","compiler-symbol",{modelElement:"Init",codeRef:t,file:n.relativePath,startLine:n.startLine,endLine:n.endLine,message:"TLA+ Init referent is a type; map the runtime initialization code it describes.",why:[`${t} resolves to ${Q(n.symbol)} with SCIP kind ${Bt(o)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function Co(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function je(e,t,n){return vn(e,t).filter(i=>i.startLine<=n&&i.endLine>=n).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine))[0]??null}function x$(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${Le(e)}([^A-Za-z0-9_$]|$)`).test(t)}function R$(e){return!e.before||!e.after?[]:[...new Set([...Object.keys(e.before),...Object.keys(e.after)])].filter(n=>JSON.stringify(e.before?.[n])!==JSON.stringify(e.after?.[n]))}function Po(e){let t=new Set,n=[];for(let r of e){let i=`${r.variable}:${r.file}:${r.line}:${r.target}:${r.enclosingSymbol??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function To(e){let t=new Set,n=[];for(let r of e){let i=`${r.variable}:${r.file}:${r.line}:${r.target}:${r.enclosingSymbol??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function k$(e){let t=new Set;return e.filter(n=>{let r=`${n.variable}:${n.alias}`;return t.has(r)?!1:(t.add(r),!0)})}function wo(e){return e.filter(t=>t.match).length}function Or(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function un(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function w$(e){let t=Object.entries(e.actions).flatMap(([o,s])=>{let a=s.waive;return a?[...(a.reads??[]).map(c=>({action:o,kind:"read",variable:c,reason:a.reason,legacy:a.legacy===!0})),...(a.writes??[]).map(c=>({action:o,kind:"write",variable:c,reason:a.reason,legacy:a.legacy===!0}))]:[]}),n=Object.entries(e.variables).flatMap(([o,s])=>{let a=s.waive;return a?[{kind:"referent",variable:o,reason:a.reason,legacy:!1}]:[]}),r=e.init?.waive,i=r?[{kind:"referent",variable:"Init",reason:r.reason,legacy:!1}]:[];return[...t,...n,...i]}var Io=new Set(Wo()),mf=new Set(Ho()),$$=new Set(Go());function W(e,t,n,r){let i=JSON.stringify({category:e,evidence:n,...r});return{id:`TLA${Fw("sha1").update(i).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...r}}import{readFileSync as C$}from"fs";import{basename as P$,join as ff}from"path";var Eo=/^[A-Za-z_][A-Za-z0-9_]*$/;function gf(e,t,n={}){let r=[],i=vn(e,t,{includeClassMemberFallbacks:!0});if(i.length===0)throw new Error(`no indexed definitions found for ${t}; run 'scip-query reindex' or check the path`);let s=C$(ff(e.config.projectRoot,t),"utf8").split(/\r?\n/),a=T=>T.symbol.trimEnd().endsWith("()."),c=i.filter(T=>!a(T)&&!T.isTypeLike&&T.parentTypeName===null&&Eo.test(T.leaf)),l=c.map(T=>({variable:T.leaf,alias:T.leaf})),d=l.length>0?ht(e,t,0,Number.POSITIVE_INFINITY,l):[],p=new Set(d.map(T=>T.variable)),m=c.filter(T=>p.has(T.leaf)?!0:E$(s,T)),f=null,g;if(m.length>0)g=i.filter(T=>a(T)&&T.parentTypeName===null);else{if(f=T$(e,t,i,a),!f){let T=i.some(F=>!a(F)&&!F.isTypeLike&&F.parentTypeName!==null&&Eo.test(F.leaf));throw new Error(`no mutable state discovered in ${t} \u2014 the static write scan found no writes to top-level variables, no top-level let declarations exist, and `+(T?"no class in this file has an instance field the write scan can confirm is mutated by one of its own methods.":"no class instance-field definitions were exposed for this file at all \u2014 the indexer emitted no member rows (neither a primary defn_enclosing_ranges row nor a role=1 mention) for any class in this file, so there is nothing for getDefinitionsForFile to surface even with class-member fallbacks included (docs/plans/2026-07-02-catalog-class-members.md).")+" Pick a file that owns runtime state.")}m=f.fields,g=f.methods,r.push(`state scoped to class ${f.className} (${t}): scaffolded actions are drawn only from its own methods \u2014 other classes or top-level functions in this file are not considered.`)}let h=m.map(T=>j$(T,s,t,r,f?.className)),y=h.map(T=>({variable:T.name,alias:T.leaf})),S=[],v=new Set;for(let T of g){let F=ht(e,t,T.startLine,T.endLine,y);if(F.length===0)continue;let Z=Nr(e,t,T.startLine,T.endLine,y),O=F$(hf(T.leaf),v);S.push({name:O,leaf:T.leaf,codeRef:I$(t,T,f?.className),startLine:T.startLine,writes:[...new Set(F.map(H=>H.variable))].sort(),reads:[...new Set(Z.map(H=>H.variable))].sort()})}S.length===0&&r.push("no top-level callable writes the discovered state; the generated Next relation is empty and the model cannot step. State may be mutated through methods, callbacks, or other files \u2014 narrow or widen the target.");let k=n.moduleName??O$(t),R=n.specDir??ff("specs",k),D=N$(k,h,S,t),q=M$(),z=_$(k,R,t,h,S);return{moduleName:k,file:t,variables:h,actions:S,warnings:r,spec:D,cfg:q,map:z}}function T$(e,t,n,r){let i=new Map;for(let s of n){if(r(s)||s.isTypeLike||s.parentTypeName===null||!Eo.test(s.leaf))continue;let a=i.get(s.parentTypeName);a?a.push(s):i.set(s.parentTypeName,[s])}let o=null;for(let[s,a]of i){let c=n.filter(m=>r(m)&&m.parentTypeName===s),l=a.map(m=>({variable:m.leaf,alias:m.leaf})),d=new Set;for(let m of c)for(let f of ht(e,t,m.startLine,m.endLine,l))d.add(f.variable);let p=a.filter(m=>d.has(m.leaf));p.length!==0&&(!o||p.length>o.fields.length)&&(o={className:s,fields:p,methods:c})}return o}function I$(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function E$(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function j$(e,t,n,r,i){let o=A$(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=L$(e.leaf,o);return a||r.push(`variable ${e.leaf} (${n}:${e.startLine+1}): domain not inferable from the declared type \u2014 fill in the TODO domain before model checking.`),l||r.push(`variable ${e.leaf} (${n}:${e.startLine+1}): initial value not inferable \u2014 fill in the TODO in Init.`),{name:s,leaf:e.leaf,codeRef:i?`${n}/${i}#${e.leaf}`:`${n}/${e.leaf}`,declarationLine:e.startLine,initTla:l,domainTla:a,domainBasis:c}}function A$(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function L$(e,t){let r=t.match(new RegExp(`\\b${q$(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,o=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(r){let l=D$(r);l?(s=`{${l.map(d=>`"${d}"`).join(", ")}}`,a="union-literal"):/^boolean\b/.test(r)?(s="BOOLEAN",a="boolean"):(/\[\]\s*$/.test(r)||/^(Array|ReadonlyArray)</.test(r))&&(a="sequence",s=null)}let c=null;if(o){let l=o.match(/^['"]([^'"]*)['"]/);l?c=`"${l[1]}"`:/^(true|false)\b/.test(o)?c=o.startsWith("true")?"TRUE":"FALSE":/^-?\d+\b/.test(o)?c=o.match(/^-?\d+/)[0]:/^\[\s*\]/.test(o)&&(c="<<>>")}return{domainTla:s,domainBasis:a,initTla:c}}function D$(e){let t=e.split("|").map(r=>r.trim());if(t.length<2)return null;let n=[];for(let r of t){let i=r.match(/^['"]([^'"]*)['"]$/);if(!i)return null;n.push(i[1])}return n}function hf(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function F$(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}${r++}`;return t.add(n),n}function O$(e){let n=P$(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return hf(n||"Model")}function N$(e,t,n,r){let i=t.map(s=>s.name),o=[];o.push(`---- MODULE ${e} ----`),o.push(`\\* Scaffolded by 'scip-query tla scaffold ${r}'.`),o.push("\\* Draft evidence tier: state from the static write scan, domains from"),o.push("\\* declared types, actions from top-level callables that write state."),o.push("\\* Review every TODO before trusting a green model-check run."),o.push("EXTENDS Naturals, Sequences, TLC"),o.push(""),o.push(`VARIABLES ${i.join(", ")}`),o.push(""),o.push(`vars == <<${i.join(", ")}>>`),o.push("");for(let s of t){if(s.domainBasis==="sequence")continue;let a=s.domainTla??'{ "TODO" } \\* TODO: declare the domain';o.push(`${s.name}Domain == ${a}`)}o.push(""),o.push("Init ==");for(let s of t){let a=s.initTla??`${s.name}Domain \\* TODO: replace with the concrete initial value (\\in used)`;o.push(s.initTla!==null?` /\\ ${s.name} = ${s.initTla}`:` /\\ ${s.name} \\in ${a}`)}o.push("");for(let s of n){let a=i.filter(c=>!s.writes.includes(c));o.push(`\\* Derived from ${s.codeRef} (writes: ${s.writes.join(", ")||"none"})`),o.push(`${s.name} ==`),o.push(` /\\ TRUE \\* TODO guard: encode the enabling condition of ${s.leaf}()`);for(let c of s.writes){let d=t.find(p=>p.name===c)?.domainBasis==="sequence"?'Seq({"TODO"})':`${c}Domain`;o.push(` /\\ ${c}' \\in ${d} \\* TODO: tighten to the concrete transition`)}a.length>0&&o.push(` /\\ UNCHANGED <<${a.join(", ")}>>`),o.push("")}if(o.push("Next =="),n.length===0)o.push(" FALSE \\* TODO: no state-writing callables were discovered");else for(let[s,a]of n.entries())o.push(` \\/ ${a.name}`);o.push(""),o.push("Spec == Init /\\ [][Next]_vars"),o.push(""),o.push("TypeOK ==");for(let s of t)s.domainBasis==="sequence"?o.push(` /\\ ${s.name} \\in Seq({"TODO"}) \\* TODO: element domain`):o.push(` /\\ ${s.name} \\in ${s.name}Domain`);return o.push("===="),o.push(""),o.join(`
555
+ `).map((o,s)=>` ${String(Be(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${ie(r.startLine,r.endLine)} ${r.shortName}`)),tt(n,t).rows}function cw(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${Be(r.line)} in ${r.enclosingShort}`);return gt(tt(n,t))}function lw(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 gt(tt([...n,...r],t))}function dw(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}:${Be(o.line)} in ${o.enclosingShort}`);return gt(tt([...n,...r,...i],t))}function uw(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 gt(tt(n,t))}function pw(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${ie(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return gt(tt(n,t))}function mw(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 gt(tt(n,t))}function fw(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` ${ie(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${M(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}`)),gt(tt(n,t))}function gw(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 hw(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 tt(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function gt(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function bo(e){return e?"yes":"no"}import{existsSync as mn}from"fs";import{existsSync as $w,mkdtempSync as Cw,rmSync as Pw}from"fs";import{tmpdir as Tw}from"os";import{dirname as vo,join as xo}from"path";import{performance as Hm}from"perf_hooks";import{spawnSync as Iw}from"child_process";import{createHash as yw}from"crypto";import{existsSync as bw,mkdirSync as Sw,readFileSync as vw,renameSync as xw,writeFileSync as Rw}from"fs";import{homedir as kw}from"os";import{dirname as ww,join as So}from"path";function Bm(e){return yw("sha256").update(e).digest("hex")}function qm(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?So(t.XDG_CACHE_HOME,"scip-query"):So(kw(),".cache","scip-query"));return So(n,e)}async function Vm(e){let{cachePath:t,url:n,expectedSha256:r}=e;if(bw(t)){let l=Bm(vw(t));if(l===r)return{status:"cached",path:t,sha256:l}}let o=await(e.fetchImpl??fetch)(n);if(!o.ok)throw new Error(`failed to download ${n}: HTTP ${o.status}`);let s=Buffer.from(await o.arrayBuffer()),a=Bm(s);if(a!==r)throw new Error(`downloaded ${n} checksum mismatch: expected ${r}, got ${a}`);Sw(ww(t),{recursive:!0});let c=`${t}.tmp-${process.pid}`;return Rw(c,s),xw(c,t),{status:"downloaded",path:t,sha256:a}}var Ew=12e4,Um="v1.8.0",jw=`https://github.com/tlaplus/tlaplus/releases/download/${Um}/tla2tools.jar`,Aw="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function Dr(e){let t=e.spawn??Iw,n=Lw(e,t);if(n.missing)return{checker:n.checker,status:"skipped",command:n.command,durationMs:0,exitCode:null,signal:null,timedOut:!1,diagnostics:[{severity:"warning",message:n.missing}],stdout:"",stderr:""};let r=e.timeoutMs??Ew,i=Hm.now(),o;try{o=t(n.command[0],n.command.slice(1),{cwd:n.cwd,encoding:"utf8",timeout:r,maxBuffer:1024*1024*10})}finally{for(let l of n.cleanupPaths??[])Pw(l,{recursive:!0,force:!0})}let s=Math.round(Hm.now()-i),a=o.error?.name==="ETIMEDOUT"||o.signal==="SIGTERM"&&s>=r,c=a?"timed-out":o.status===0?"passed":"failed";return{checker:n.checker,status:c,command:n.command,durationMs:s,exitCode:o.status,signal:o.signal,timedOut:a,diagnostics:Dw(c,o.stdout??"",o.stderr??""),stdout:o.stdout??"",stderr:o.stderr??""}}function Lw(e,t){let n=e.checker;if(n==="none")return{checker:"none",command:["<none>"],cwd:e.projectRoot,missing:"model checker skipped by --checker none"};if(n==="apalache"||n==="auto"&&De(Wm(e),t)){let o=Wm(e);return De(o,t)?{checker:"apalache",command:[o,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:vo(e.specPath)}:Lr("apalache",`Apalache binary is not available: ${o}`)}let r=Ro(e),i=De("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!r)return Lr(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!i)return Lr(n==="sany"?"sany":"tlc","java is not available on PATH");let o=n==="sany"?"sany":n==="tlc"||e.configPath?"tlc":"sany";if(o==="sany")return{checker:o,command:["java","-cp",r,"tla2sany.SANY",e.specPath],cwd:vo(e.specPath)};let s=e.metaDir??Cw(xo(Tw(),"scip-tla-tlc-"));return{checker:o,command:["java","-cp",r,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:vo(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Lr("none",`unknown checker mode: ${n}`)}function Wm(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function Ro(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,Jm(t),xo(e.projectRoot,"tla2tools.jar"),xo(e.projectRoot,"tools","tla2tools.jar")].filter(r=>typeof r=="string"&&r.length>0).find(r=>$w(r))??null}function Jm(e=process.env){return qm("tla2tools.jar",e)}async function zm(e={}){let t=e.cachePath??Jm(e.env),n=e.expectedSha256??Aw,r=e.version??Um,i=e.url??jw;return{...await Vm({cachePath:t,url:i,expectedSha256:n,fetchImpl:e.fetchImpl}),version:r,url:i}}function Dw(e,t,n){if(e==="passed")return[{severity:"info",message:"model checker completed successfully"}];if(e==="timed-out")return[{severity:"error",message:"model checker timed out"}];let r=[...Gm(n),...Gm(t)].slice(0,20);return r.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:r.map(i=>({severity:"error",message:i}))}function Gm(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Lr(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as Fw}from"crypto";import{readFileSync as Qm}from"fs";import{join as Ym}from"path";var Xm=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),Zm=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),ef=new Set(["readFileSync","existsSync","statSync"]),Ow=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,Nw=/^\s*SELECT\b/i;function tf(e){return Ow.test(e)?"write":Nw.test(e)?"read":null}var Mw=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function _w(e,t){let n=e.match(Mw);if(!n)return!1;let r=e.slice(n[0].length);return new RegExp(`^${Le(t)}\\b`).test(r)}function nf(e,t,n,r=[],i=[]){let o=[],s=Vw(e,t,o),a=s.aliases,c=Hw(t),l=Ww(t),d=Gw(t),p=zw(e,t,o),m=Qw(e,t,o);n&&Yw(t,n,i,o);let f=new Map((n?.actions??[]).map(v=>[v.name,v])),g=new Set(p.flatMap(v=>v.referents.map(k=>k.match?.symbol).filter(Boolean))),h=new Set((m?.referents??[]).map(v=>v.match?.symbol).filter(Boolean)),y=Xw(e,t,p,a,c,l,d,g,h,o,f),S=t$(e,p,a,c,l,d,o,f);return r$(e,p,o),i$(t,r,o),{modelParse:n?.modelParse??"unavailable",modelVariables:n?.variables??[],modelOperators:n?.operators??[],modelActionFacts:n?.actions??[],mappedVariables:Object.keys(t.variables).length,mappedActions:Object.keys(t.actions).length,resolvedReferents:wo(p.flatMap(v=>v.referents))+wo(s.referents)+wo(m?.referents??[]),staticWrites:y,staticReads:S,waivers:w$(t),checkedInvariants:[...i],traceStepsChecked:r.length,findings:o,findingGroups:Bw(o)}}function Bw(e){let t=new Map;for(let n of e){let r=`${n.category}:${n.modelElement??"-"}`,i=t.get(r);i||(i={groupKey:r,category:n.category,modelElement:n.modelElement,severity:n.severity,count:0,findingIds:[]},t.set(r,i)),i.count+=1,i.findingIds.push(n.id),i.severity=qw(i.severity,n.severity)}return[...t.values()].sort((n,r)=>r.count-n.count||Fr(r.severity)-Fr(n.severity)||n.groupKey.localeCompare(r.groupKey))}function qw(e,t){return Fr(t)>Fr(e)?t:e}function Fr(e){return e==="error"?2:e==="warning"?1:0}function Vw(e,t,n){let r=[],i=[];for(let[o,s]of Object.entries(t.variables)){let a=new Set(s.aliases),c=!!s.waive;for(let l of s.code){let d=Mr(e,l,n,o);i.push(d);let p=d.match;if(!p){c||n.push(W("missing-referent","error","compiler-symbol",{modelElement:o,codeRef:l,message:`TLA+ variable ${o} maps to missing TypeScript referent ${l}.`,why:["The mapping contract must point at live compiler-indexed code before conformance can be checked."],remediation:`Update variables.${o}.code to a live symbol, or remove the variable from the model mapping.`}));continue}b$(e,o,l,p,n,c),s.aliases.length===0&&a.add(Bo(p.symbol))}for(let l of a)r.push({variable:o,alias:l})}return{aliases:k$(r),referents:i}}function Hw(e){let t=[];for(let[n,r]of Object.entries(e.variables))r.resource&&t.push({variable:n,path:r.resource.path});return t}function Ww(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.statements??[])t.push({variable:n,pattern:i.pattern,regex:new RegExp(i.pattern)});return t}function Gw(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.ormCalls??[]){let{write:o,read:s}=mo(i);t.push({variable:n,table:i.table,writeMethods:new Set(o),readMethods:new Set(s)})}return t}function Uw(e,t,n,r,i,o){return rf(e,t,(s,a,c)=>ht(e,s,a,c,n,r,i,o))}function Jw(e,t,n,r,i,o){return rf(e,t,(s,a,c)=>Nr(e,s,a,c,n,r,i,o))}function rf(e,t,n){let r=Wt(e,t,{semantic:!1});if(!r)return[];let i=[],o=new Set;for(let s of r.callees){if(o.has(s.symbol))continue;o.add(s.symbol);let a=xn(e,s.symbol).match;if(a)for(let c of n(a.relativePath,a.startLine,a.endLine))i.push({...c,via:s.shortName})}return i}function zw(e,t,n){return Object.entries(t.actions).map(([r,i])=>{let o=i.code.map(s=>{let a=fo(s),c="error"in a?s:a.ref,d=Mr(e,c,n,r).match;return d?(S$(e,r,s,d,n),"error"in a||!a.window?{ref:s,match:d}:Kw(a.window,d)?(n.push(W("invalid-line-window","error","compiler-symbol",{modelElement:r,codeRef:s,file:d.relativePath,startLine:d.startLine,endLine:d.endLine,message:`TLA+ action ${r} codeRef line window L${a.window.startLine}-L${a.window.endLine} falls outside ${Q(d.symbol)}'s actual span L${d.startLine+1}-L${d.endLine+1} in ${d.relativePath}.`,why:[`${s} resolves to ${Q(d.symbol)} at ${d.relativePath}:${d.startLine+1}-${d.endLine+1}.`,"The requested window does not fall entirely inside that span."],remediation:`Update the @L${a.window.startLine}-L${a.window.endLine} window in actions.${r}.code to fall within L${d.startLine+1}-L${d.endLine+1}, or drop the window to cover the whole function.`})),{ref:s,match:null}):{ref:s,match:d,window:{startLine:a.window.startLine-1,endLine:a.window.endLine-1}}):(n.push(W("missing-referent","error","compiler-symbol",{modelElement:r,codeRef:s,message:`TLA+ action ${r} maps to missing TypeScript referent ${s}.`,why:["The action cannot be compared to code because the mapped symbol did not resolve in the SCIP index."],remediation:`Update actions.${r}.code to a live function or method symbol.`})),{ref:s,match:null})});return{name:r,mapping:i,referents:o}})}function Kw(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function Qw(e,t,n){let r=t.init;if(!r)return;let i=!!r.waive,o=r.codeRefs.map(s=>{let a=Mr(e,s,n,"Init"),c=a.match;return c?v$(e,s,c,n,i):i||n.push(W("missing-referent","error","compiler-symbol",{modelElement:"Init",codeRef:s,message:`TLA+ Init maps to missing TypeScript referent ${s}.`,why:["The Init mapping must point at live compiler-indexed code before conformance can be checked."],remediation:"Update init.codeRefs to a live function or method symbol, or remove the stale entry."})),a});return{mapping:r,referents:o}}function Yw(e,t,n,r){let i=new Set(t.variables),o=new Set(t.operators),s=new Set(n);for(let a of Object.keys(e.variables))i.has(a)||r.push(W("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ variable ${a} is not declared in the module.`,why:["The mapping names a model variable, but the TLA+ module text does not declare it with VARIABLE(S)."],remediation:`Declare ${a} in the TLA+ module or remove it from the mapping.`}));for(let a of Object.keys(e.actions))o.has(a)||r.push(W("model-text","error","model-text",{modelElement:a,file:t.path,message:`Mapped TLA+ action ${a} is not defined in the module.`,why:["The mapping names a model action, but the TLA+ module text has no matching operator definition."],remediation:`Define ${a} == ... in the TLA+ module or update the mapping action name.`}));for(let a of t.actions){let c=e.actions[a.name];c&&(Km({action:a.name,field:"writes",modelValues:a.writes,mappingValues:c.writes,missingInMappingCategory:"model-mapping-write",missingInModelCategory:"model-mapping-write",findings:r,file:t.path,isWaived:l=>!!c.waive?.writes.includes(l)}),Km({action:a.name,field:"reads",modelValues:a.reads,mappingValues:c.reads,missingInMappingCategory:"model-mapping-read",missingInModelCategory:"model-mapping-read",findings:r,file:t.path}))}for(let a of e.invariants)s.has(a)||r.push(W("missing-invariant","warning","model-text",{modelElement:a,file:t.path,message:`Mapping lists invariant ${a}, but the checker config does not include it.`,why:["The model mapping names an invariant that was not found in INVARIANT lines of the selected config."],remediation:`Add INVARIANT ${a} to the config used for this run, or remove it from the mapping invariants list.`}))}function Km(e){let t=new Set(e.modelValues),n=new Set(e.mappingValues),r=e.isWaived??(()=>!1);for(let i of t)n.has(i)||r(i)||e.findings.push(W(e.missingInMappingCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`TLA+ action ${e.action} ${e.field==="writes"?"writes":"reads"} ${i}, but the mapping does not declare that ${e.field.slice(0,-1)}.`,why:[`SANY-derived model facts list ${i} in ${e.action}.${e.field}, while the mapping omits it.`],remediation:`Add ${i} to actions.${e.action}.${e.field}, or update the TLA+ model if the ${e.field.slice(0,-1)} is unintended.`}));for(let i of n)t.has(i)||r(i)||e.findings.push(W(e.missingInModelCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`Mapping declares ${e.action}.${e.field} includes ${i}, but the SANY model facts do not.`,why:[`The mapping says ${e.action} ${e.field==="writes"?"writes":"reads"} ${i}, but the parsed TLA+ action does not show that model-side fact.`],remediation:`Update the TLA+ action to ${e.field==="writes"?"prime":"reference"} ${i}, remove the mapping declaration, or add a waiver if static evidence cannot represent the model boundary.`}))}function Xw(e,t,n,r,i,o,s,a,c,l,d){let p=[];for(let f of n){let g=[];for(let h of f.referents){if(!h.match)continue;let y=h.window??{startLine:h.match.startLine,endLine:h.match.endLine},S=ht(e,h.match.relativePath,y.startLine,y.endLine,r,i,o,s);g.push(...S),p.push(...S);let v=new Set(f.mapping.writes),k=Uw(e,h.match.symbol,r,i,o,s).filter(R=>v.has(R.variable));g.push(...k),p.push(...k)}e$(f,g,l,d.get(f.name))}let m=t.unmappedWriteScope==="actions"?[]:g$(e,t);for(let f of m)for(let g of ht(e,f,0,Number.POSITIVE_INFINITY,r,i,o,s))p.push(g),Zw(g)&&(g.enclosingSymbol&&(a.has(g.enclosingSymbol)||c.has(g.enclosingSymbol))||l.push(W("unmapped-write","error","static-action",{modelElement:g.variable,codeRef:g.enclosingSymbol??`${g.file}:${g.line+1}`,file:g.file,startLine:g.line,endLine:g.line,message:`Modeled variable ${g.variable} is written outside any mapped TLA+ action.`,why:[`The static source scan found ${g.target} at ${g.file}:${g.line+1}.`,g.enclosingShort?`The write is inside ${g.enclosingShort}, which is not mapped as a model action.`:"The write is outside an indexed callable definition."],remediation:`Map the enclosing code to a TLA+ action, remove the write, or remove ${g.variable} from the modeled slice if it is intentionally out of scope.`})));return Po(p)}function Zw(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function e$(e,t,n,r){let i=new Set(e.mapping.writes),o=new Set(t.map(a=>a.variable)),s=new Set(r?.writes??[]);for(let a of t)r&&!s.has(a.variable)&&!un(e,"write",a.variable)&&n.push(W("model-code-write","error","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`Code for TLA+ action ${e.name} writes ${a.variable}, but the SANY model action does not prime it.`,why:[`The code writes ${a.target} at ${a.file}:${a.line+1}${Or(a.via)}.`,`SANY-derived model facts for ${e.name} list writes: ${r.writes.join(", ")||"none"}.`],remediation:`Prime ${a.variable} in the TLA+ action, remove the code write from this action, or remap the code to the correct action.`})),!i.has(a.variable)&&!un(e,"write",a.variable)&&n.push(W("undeclared-write","error","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`TLA+ action ${e.name} writes modeled variable ${a.variable}, but the mapping does not declare that write.`,why:[`The code writes ${a.target} at ${a.file}:${a.line+1}${Or(a.via)}.`],remediation:`Add ${a.variable} to actions.${e.name}.writes, update the model action, or change the code so it no longer mutates that modeled variable.`}));for(let a of i)!o.has(a)&&!un(e,"write",a)&&n.push(W("missing-write-evidence","warning","unknown",{modelElement:e.name,message:`TLA+ action ${e.name} declares a write to ${a}, but no direct source write was found.`,why:["The write may happen through an alias, callback, dependency, or runtime side effect that static scanning could not prove."],remediation:`Add a more precise variable alias, add the write sink as a mapped action referent, provide a trace, or waive actions.${e.name}.writes.${a} with a specific reason.`}))}function t$(e,t,n,r,i,o,s,a){let c=[];for(let l of t){let d=[];for(let p of l.referents){if(!p.match)continue;let m=p.window??{startLine:p.match.startLine,endLine:p.match.endLine},f=Nr(e,p.match.relativePath,m.startLine,m.endLine,n,r,i,o);d.push(...f),c.push(...f);let g=new Set(l.mapping.reads),h=Jw(e,p.match.symbol,n,r,i,o).filter(y=>g.has(y.variable));d.push(...h),c.push(...h)}n$(l,d,s,a.get(l.name))}return To(c)}function n$(e,t,n,r){let i=new Set(e.mapping.reads),o=new Set(t.map(a=>a.variable)),s=new Set(r?.reads??[]);for(let a of t)r&&!s.has(a.variable)&&n.push(W("model-code-read","warning","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`Code for TLA+ action ${e.name} reads ${a.variable}, but the SANY model action does not reference it.`,why:[`The code reads ${a.target} at ${a.file}:${a.line+1}${Or(a.via)}.`,`SANY-derived model facts for ${e.name} list reads: ${r.reads.join(", ")||"none"}.`],remediation:`Reference ${a.variable} in the TLA+ action, remove the code read from this action, or remap the code to the correct action.`})),!i.has(a.variable)&&!un(e,"read",a.variable)&&n.push(W("undeclared-read","warning","static-action",{modelElement:e.name,codeRef:a.enclosingSymbol??`${a.file}:${a.line+1}`,file:a.file,startLine:a.line,endLine:a.line,message:`TLA+ action ${e.name} reads modeled variable ${a.variable}, but the mapping does not declare that read.`,why:[`The code reads ${a.target} at ${a.file}:${a.line+1}${Or(a.via)}.`],remediation:`Add ${a.variable} to actions.${e.name}.reads, update the model action, or waive the read with a specific reason if it is intentionally outside the model step.`}));for(let a of i)!o.has(a)&&!un(e,"read",a)&&n.push(W("missing-read-evidence","warning","unknown",{modelElement:e.name,message:`TLA+ action ${e.name} declares a read of ${a}, but no direct source read was found.`,why:["The read may happen through an alias, callback, dependency, or runtime side effect that static scanning could not prove."],remediation:`Add a more precise variable alias, add the read source as a mapped action referent, provide a trace, or waive actions.${e.name}.reads.${a} with a specific reason.`}))}function r$(e,t,n){for(let r of t){if(r.mapping.calls.length===0)continue;let i=r.mapping.calls.map(s=>Mr(e,s,n,r.name));for(let s of i)s.match||n.push(W("missing-referent","error","compiler-symbol",{modelElement:r.name,codeRef:s.ref,message:`actions.${r.name}.calls contains missing TypeScript referent ${s.ref}.`,why:["Declared call checks require the expected callee to resolve in the SCIP index."],remediation:`Update actions.${r.name}.calls to a live symbol or remove the stale call expectation.`}));let o=new Set(i.map(s=>s.match?.symbol).filter(Boolean));for(let s of r.referents){if(!s.match)continue;let a=Wt(e,s.match.symbol),c=new Set(a?.callees.map(l=>l.symbol)??[]);for(let l of o)c.has(l)||n.push(W("missing-call","error","compiler-symbol",{modelElement:r.name,codeRef:s.ref,file:s.match.relativePath,startLine:s.match.startLine,endLine:s.match.endLine,message:`TLA+ action ${r.name} no longer calls ${Q(l)} from ${s.ref}.`,why:["The mapping declares a call dependency that is absent from the current compiler-resolved call graph."],remediation:`Update actions.${r.name}.calls, update the TLA+ action, or restore the code path if the call is required.`}))}}}function i$(e,t,n){for(let[r,i]of t.entries()){let o=e.actions[i.action];if(!o){n.push(W("trace","error","trace",{modelElement:i.action,codeRef:i.code,message:`Trace step ${r} uses action ${i.action}, which is not mapped.`,why:["Every observed trace action must map to a TLA+ action before trace conformance can be checked."],remediation:`Add actions.${i.action} to the mapping, or fix the trace action name.`}));continue}let s=R$(i),a=new Set(o.writes);for(let c of s)a.has(c)||n.push(W("trace","error","trace",{modelElement:i.action,codeRef:i.code,message:`Trace step ${r} changed ${c}, but action ${i.action} does not declare that write.`,why:["The runtime trace observed a state change outside the action write set."],remediation:`Update actions.${i.action}.writes, update the TLA+ model, or investigate the code path that changed ${c}.`}))}}function ht(e,t,n,r,i,o=[],s=[],a=[]){let c=o$(e,t,n,r,i,o,s,a);return c||m$(e,t,n,r,i,o,s,a)}function Nr(e,t,n,r,i,o=[],s=[],a=[]){let c=s$(e,t,n,r,i,o,s,a);return c||f$(e,t,n,r,i,o,s,a)}function o$(e,t,n,r,i,o=[],s=[],a=[]){let c=qr(e,t);if(!c)return null;let l=[],d=p=>{if(!(p.startPosition.row>r||p.endPosition.row<n)){a$(e,t,p,i,l),of(e,t,p,o,"write",l),sf(e,t,p,s,"write",l),af(e,t,p,a,"write",l);for(let m of p.children)d(m)}};return d(c.rootNode),Po(l)}function s$(e,t,n,r,i,o=[],s=[],a=[]){let c=qr(e,t);if(!c)return null;let l=[],d=p=>{if(!(p.startPosition.row>r||p.endPosition.row<n)){d$(e,t,p,i,l),of(e,t,p,o,"read",l),sf(e,t,p,s,"read",l),af(e,t,p,a,"read",l);for(let m of p.children)d(m)}};return d(c.rootNode),To(l)}function a$(e,t,n,r,i){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let o=n.childForFieldName("left")??n.namedChild(0);o&&dn(e,t,o,"assignment",r,i);return}if(n.type!=="variable_declarator"){if(n.type==="pair"){let o=n.childForFieldName("key")??n.namedChild(0);o&&dn(e,t,o,"object-field",r,i);return}if(n.type==="update_expression"){let o=n.namedChildren.find(s=>s.type!=="++"&&s.type!=="--")??n.namedChild(0);o&&dn(e,t,o,"update",r,i);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let o=n.namedChild(0);o&&dn(e,t,o,"delete",r,i);return}if(n.type==="call_expression"){let o=n.childForFieldName("function")??n.namedChild(0);if(!o||!lf(o))return;dn(e,t,o,"mutation-call",r,i)}}}function of(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?$o(s):null;if(!a||!(i==="write"?Zm:ef).has(a))return;let d=n.childForFieldName("arguments")?.namedChild(0);if(!d)return;let p=d.text;for(let m of r){if(!p.includes(m.path))continue;let f=je(e,t,n.startPosition.row);o.push({variable:m.variable,alias:m.path,file:t,line:n.startPosition.row,target:`${a}(${p})`,kind:"resource",enclosingSymbol:f?.symbol,enclosingShort:f?Q(f.symbol):void 0})}}function $o(e){if(e.type==="identifier")return e.text;if(e.type==="member_expression"){let t=e.namedChild(e.namedChildCount-1);return t?t.text:null}return null}function sf(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("arguments");if(s)for(let a of s.namedChildren){let c=c$(a);if(c!==null&&tf(c)===i)for(let l of r){if(!l.regex.test(c))continue;let d=je(e,t,n.startPosition.row),p=n.childForFieldName("function")??n.namedChild(0),m=(p&&$o(p))??"call";o.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${m}(${l$(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?Q(d.symbol):void 0})}}}function c$(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function l$(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function af(e,t,n,r,i,o){if(r.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?$o(s):null;if(!a)return;let l=n.childForFieldName("arguments")?.namedChild(0);if(!l)return;let d=l.text.trim();for(let p of r){if(!cf(p,a,d,i))continue;let m=je(e,t,n.startPosition.row);o.push({variable:p.variable,alias:p.table,file:t,line:n.startPosition.row,target:`${a}(${d})`,kind:"orm-call",enclosingSymbol:m?.symbol,enclosingShort:m?Q(m.symbol):void 0})}}function cf(e,t,n,r){return n!==e.table?!1:r==="write"?e.writeMethods.has(t):e.readMethods.has(t)||t==="from"&&e.readMethods.has("select")}function d$(e,t,n,r,i){if(!(!u$(n)||p$(n)))for(let o of r){if(n.text!==o.alias)continue;let s=je(e,t,n.startPosition.row);i.push({variable:o.variable,alias:o.alias,file:t,line:n.startPosition.row,target:n.text,kind:"identifier",enclosingSymbol:s?.symbol,enclosingShort:s?Q(s.symbol):void 0})}}function u$(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function p$(e){let t=e.parent;for(;t;){if(t.type==="assignment_expression"||t.type==="augmented_assignment_expression"){let n=t.childForFieldName("left")??t.namedChild(0);return!!(n&&ko(n,e))}if(t.type==="update_expression"||t.type==="unary_expression"&&/^\s*delete\b/.test(t.text))return!0;if(t.type==="pair"){let n=t.childForFieldName("key")??t.namedChild(0);return!!(n&&ko(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&lf(n)&&ko(n,e))return!0}if(t.type.endsWith("statement")||t.type==="function_declaration"||t.type==="method_definition")return!1;t=t.parent}return!1}function ko(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function lf(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&Xm.has(t.text))}function dn(e,t,n,r,i,o){for(let s of i){if(!x$(s.alias,n.text))continue;let a=je(e,t,n.startPosition.row);o.push({variable:s.variable,alias:s.alias,file:t,line:n.startPosition.row,target:n.text,kind:r,enclosingSymbol:a?.symbol,enclosingShort:a?Q(a.symbol):void 0})}}function m$(e,t,n,r,i,o=[],s=[],a=[]){let l=Qm(Ym(e.config.projectRoot,t),"utf8").split(/\r?\n/),d=[],p=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=p;m+=1){let f=l[m]??"";for(let g of i){if(_w(f,g.alias))continue;let h=Le(g.alias);if(!new RegExp(`(?:\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${h}\\b\\s*\\.\\s*(?:${[...Xm].join("|")})\\s*\\(|\\b${h}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(f))continue;let S=je(e,t,m);d.push({variable:g.variable,alias:g.alias,file:t,line:m,target:f.trim(),kind:"source-scan",enclosingSymbol:S?.symbol,enclosingShort:S?Q(S.symbol):void 0})}df(e,t,m,f,o,Zm,d),uf(e,t,m,f,s,"write",d),pf(e,t,m,f,a,"write",d)}return Po(d)}function f$(e,t,n,r,i,o=[],s=[],a=[]){let l=Qm(Ym(e.config.projectRoot,t),"utf8").split(/\r?\n/),d=[],p=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=p;m+=1){let f=l[m]??"";for(let g of i){let h=Le(g.alias);if(!new RegExp(`\\b${h}\\b`).test(f)||new RegExp(`\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=|\\.|\\[)`).test(f))continue;let y=je(e,t,m);d.push({variable:g.variable,alias:g.alias,file:t,line:m,target:f.trim(),kind:"source-scan",enclosingSymbol:y?.symbol,enclosingShort:y?Q(y.symbol):void 0})}df(e,t,m,f,o,ef,d),uf(e,t,m,f,s,"read",d),pf(e,t,m,f,a,"read",d)}return To(d)}function df(e,t,n,r,i,o,s){if(i.length!==0)for(let a of o){let c=r.indexOf(`${a}(`);if(c===-1)continue;let l=r.slice(c+a.length);for(let d of i){if(!l.includes(d.path))continue;let p=je(e,t,n);s.push({variable:d.variable,alias:d.path,file:t,line:n,target:r.trim(),kind:"resource",enclosingSymbol:p?.symbol,enclosingShort:p?Q(p.symbol):void 0})}}}function uf(e,t,n,r,i,o,s){if(i.length!==0&&tf(r)===o)for(let a of i){if(!a.regex.test(r))continue;let c=je(e,t,n);s.push({variable:a.variable,alias:a.pattern,file:t,line:n,target:r.trim(),kind:"statement",enclosingSymbol:c?.symbol,enclosingShort:c?Q(c.symbol):void 0})}}function pf(e,t,n,r,i,o,s){if(i.length!==0)for(let a of r.matchAll(/\.([A-Za-z_$][\w$]*)\s*\(\s*([^,)\s][^,)]*?)\s*\)/g)){let c=a[1],l=a[2].trim();for(let d of i){if(!cf(d,c,l,o))continue;let p=je(e,t,n);s.push({variable:d.variable,alias:d.table,file:t,line:n,target:r.trim(),kind:"orm-call",enclosingSymbol:p?.symbol,enclosingShort:p?Q(p.symbol):void 0})}}}function g$(e,t){let n=t.scope??[];return n.length===0?[]:e.all("SELECT relative_path FROM documents ORDER BY relative_path").map(i=>i.relative_path).filter(i=>n.some(o=>i.includes(o)))}function Mr(e,t,n,r){let i=xn(e,t),o=i.match??(t.includes("#")?xn(e,t.replace("#","/")).match:null);return i.match&&i.total>1&&!h$(t)&&n.push(W("ambiguous-referent","warning","compiler-symbol",{modelElement:r,codeRef:t,file:i.match.relativePath,startLine:i.match.startLine,endLine:i.match.endLine,message:`Mapping referent ${t} resolved ambiguously to ${Q(i.match.symbol)}.`,why:[`${i.total} indexed definitions share this lookup shape.`,y$(i.candidates)].filter(Boolean),remediation:`Qualify ${t} with a path or fuller symbol name so the mapping cannot drift to another definition.`})),{ref:t,match:o}}function h$(e){return/[/#:]/.test(e)}function y$(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function b$(e,t,n,r,i,o=!1){let s=Co(e,r);if(s===null||$$.has(s)||o)return;let a=Io.has(s);i.push(W("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:a?`TLA+ variable ${t} referent is a type; map the runtime state it describes.`:`TLA+ variable ${t} referent is ${qt(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${Q(r.symbol)} with SCIP kind ${qt(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function S$(e,t,n,r,i){let o=Co(e,r);o===null||mf.has(o)||Io.has(o)&&i.push(W("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:`TLA+ action ${t} referent is a type; map the runtime transition code it describes.`,why:[`${n} resolves to ${Q(r.symbol)} with SCIP kind ${qt(o)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function v$(e,t,n,r,i){let o=Co(e,n);o===null||mf.has(o)||i||Io.has(o)&&r.push(W("invalid-referent-kind","error","compiler-symbol",{modelElement:"Init",codeRef:t,file:n.relativePath,startLine:n.startLine,endLine:n.endLine,message:"TLA+ Init referent is a type; map the runtime initialization code it describes.",why:[`${t} resolves to ${Q(n.symbol)} with SCIP kind ${qt(o)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function Co(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function je(e,t,n){return vn(e,t).filter(i=>i.startLine<=n&&i.endLine>=n).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine))[0]??null}function x$(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${Le(e)}([^A-Za-z0-9_$]|$)`).test(t)}function R$(e){return!e.before||!e.after?[]:[...new Set([...Object.keys(e.before),...Object.keys(e.after)])].filter(n=>JSON.stringify(e.before?.[n])!==JSON.stringify(e.after?.[n]))}function Po(e){let t=new Set,n=[];for(let r of e){let i=`${r.variable}:${r.file}:${r.line}:${r.target}:${r.enclosingSymbol??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function To(e){let t=new Set,n=[];for(let r of e){let i=`${r.variable}:${r.file}:${r.line}:${r.target}:${r.enclosingSymbol??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function k$(e){let t=new Set;return e.filter(n=>{let r=`${n.variable}:${n.alias}`;return t.has(r)?!1:(t.add(r),!0)})}function wo(e){return e.filter(t=>t.match).length}function Or(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function un(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function w$(e){let t=Object.entries(e.actions).flatMap(([o,s])=>{let a=s.waive;return a?[...(a.reads??[]).map(c=>({action:o,kind:"read",variable:c,reason:a.reason,legacy:a.legacy===!0})),...(a.writes??[]).map(c=>({action:o,kind:"write",variable:c,reason:a.reason,legacy:a.legacy===!0}))]:[]}),n=Object.entries(e.variables).flatMap(([o,s])=>{let a=s.waive;return a?[{kind:"referent",variable:o,reason:a.reason,legacy:!1}]:[]}),r=e.init?.waive,i=r?[{kind:"referent",variable:"Init",reason:r.reason,legacy:!1}]:[];return[...t,...n,...i]}var Io=new Set(Wo()),mf=new Set(Ho()),$$=new Set(Go());function W(e,t,n,r){let i=JSON.stringify({category:e,evidence:n,...r});return{id:`TLA${Fw("sha1").update(i).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...r}}import{readFileSync as C$}from"fs";import{basename as P$,join as ff}from"path";var Eo=/^[A-Za-z_][A-Za-z0-9_]*$/;function gf(e,t,n={}){let r=[],i=vn(e,t,{includeClassMemberFallbacks:!0});if(i.length===0)throw new Error(`no indexed definitions found for ${t}; run 'scip-query reindex' or check the path`);let s=C$(ff(e.config.projectRoot,t),"utf8").split(/\r?\n/),a=T=>T.symbol.trimEnd().endsWith("()."),c=i.filter(T=>!a(T)&&!T.isTypeLike&&T.parentTypeName===null&&Eo.test(T.leaf)),l=c.map(T=>({variable:T.leaf,alias:T.leaf})),d=l.length>0?ht(e,t,0,Number.POSITIVE_INFINITY,l):[],p=new Set(d.map(T=>T.variable)),m=c.filter(T=>p.has(T.leaf)?!0:E$(s,T)),f=null,g;if(m.length>0)g=i.filter(T=>a(T)&&T.parentTypeName===null);else{if(f=T$(e,t,i,a),!f){let T=i.some(F=>!a(F)&&!F.isTypeLike&&F.parentTypeName!==null&&Eo.test(F.leaf));throw new Error(`no mutable state discovered in ${t} \u2014 the static write scan found no writes to top-level variables, no top-level let declarations exist, and `+(T?"no class in this file has an instance field the write scan can confirm is mutated by one of its own methods.":"no class instance-field definitions were exposed for this file at all \u2014 the indexer emitted no member rows (neither a primary defn_enclosing_ranges row nor a role=1 mention) for any class in this file, so there is nothing for getDefinitionsForFile to surface even with class-member fallbacks included (docs/plans/2026-07-02-catalog-class-members.md).")+" Pick a file that owns runtime state.")}m=f.fields,g=f.methods,r.push(`state scoped to class ${f.className} (${t}): scaffolded actions are drawn only from its own methods \u2014 other classes or top-level functions in this file are not considered.`)}let h=m.map(T=>j$(T,s,t,r,f?.className)),y=h.map(T=>({variable:T.name,alias:T.leaf})),S=[],v=new Set;for(let T of g){let F=ht(e,t,T.startLine,T.endLine,y);if(F.length===0)continue;let Z=Nr(e,t,T.startLine,T.endLine,y),O=F$(hf(T.leaf),v);S.push({name:O,leaf:T.leaf,codeRef:I$(t,T,f?.className),startLine:T.startLine,writes:[...new Set(F.map(H=>H.variable))].sort(),reads:[...new Set(Z.map(H=>H.variable))].sort()})}S.length===0&&r.push("no top-level callable writes the discovered state; the generated Next relation is empty and the model cannot step. State may be mutated through methods, callbacks, or other files \u2014 narrow or widen the target.");let k=n.moduleName??O$(t),R=n.specDir??ff("specs",k),D=N$(k,h,S,t),B=M$(),z=_$(k,R,t,h,S);return{moduleName:k,file:t,variables:h,actions:S,warnings:r,spec:D,cfg:B,map:z}}function T$(e,t,n,r){let i=new Map;for(let s of n){if(r(s)||s.isTypeLike||s.parentTypeName===null||!Eo.test(s.leaf))continue;let a=i.get(s.parentTypeName);a?a.push(s):i.set(s.parentTypeName,[s])}let o=null;for(let[s,a]of i){let c=n.filter(m=>r(m)&&m.parentTypeName===s),l=a.map(m=>({variable:m.leaf,alias:m.leaf})),d=new Set;for(let m of c)for(let f of ht(e,t,m.startLine,m.endLine,l))d.add(f.variable);let p=a.filter(m=>d.has(m.leaf));p.length!==0&&(!o||p.length>o.fields.length)&&(o={className:s,fields:p,methods:c})}return o}function I$(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function E$(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function j$(e,t,n,r,i){let o=A$(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=L$(e.leaf,o);return a||r.push(`variable ${e.leaf} (${n}:${e.startLine+1}): domain not inferable from the declared type \u2014 fill in the TODO domain before model checking.`),l||r.push(`variable ${e.leaf} (${n}:${e.startLine+1}): initial value not inferable \u2014 fill in the TODO in Init.`),{name:s,leaf:e.leaf,codeRef:i?`${n}/${i}#${e.leaf}`:`${n}/${e.leaf}`,declarationLine:e.startLine,initTla:l,domainTla:a,domainBasis:c}}function A$(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function L$(e,t){let r=t.match(new RegExp(`\\b${B$(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,o=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(r){let l=D$(r);l?(s=`{${l.map(d=>`"${d}"`).join(", ")}}`,a="union-literal"):/^boolean\b/.test(r)?(s="BOOLEAN",a="boolean"):(/\[\]\s*$/.test(r)||/^(Array|ReadonlyArray)</.test(r))&&(a="sequence",s=null)}let c=null;if(o){let l=o.match(/^['"]([^'"]*)['"]/);l?c=`"${l[1]}"`:/^(true|false)\b/.test(o)?c=o.startsWith("true")?"TRUE":"FALSE":/^-?\d+\b/.test(o)?c=o.match(/^-?\d+/)[0]:/^\[\s*\]/.test(o)&&(c="<<>>")}return{domainTla:s,domainBasis:a,initTla:c}}function D$(e){let t=e.split("|").map(r=>r.trim());if(t.length<2)return null;let n=[];for(let r of t){let i=r.match(/^['"]([^'"]*)['"]$/);if(!i)return null;n.push(i[1])}return n}function hf(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function F$(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}${r++}`;return t.add(n),n}function O$(e){let n=P$(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return hf(n||"Model")}function N$(e,t,n,r){let i=t.map(s=>s.name),o=[];o.push(`---- MODULE ${e} ----`),o.push(`\\* Scaffolded by 'scip-query tla scaffold ${r}'.`),o.push("\\* Draft evidence tier: state from the static write scan, domains from"),o.push("\\* declared types, actions from top-level callables that write state."),o.push("\\* Review every TODO before trusting a green model-check run."),o.push("EXTENDS Naturals, Sequences, TLC"),o.push(""),o.push(`VARIABLES ${i.join(", ")}`),o.push(""),o.push(`vars == <<${i.join(", ")}>>`),o.push("");for(let s of t){if(s.domainBasis==="sequence")continue;let a=s.domainTla??'{ "TODO" } \\* TODO: declare the domain';o.push(`${s.name}Domain == ${a}`)}o.push(""),o.push("Init ==");for(let s of t){let a=s.initTla??`${s.name}Domain \\* TODO: replace with the concrete initial value (\\in used)`;o.push(s.initTla!==null?` /\\ ${s.name} = ${s.initTla}`:` /\\ ${s.name} \\in ${a}`)}o.push("");for(let s of n){let a=i.filter(c=>!s.writes.includes(c));o.push(`\\* Derived from ${s.codeRef} (writes: ${s.writes.join(", ")||"none"})`),o.push(`${s.name} ==`),o.push(` /\\ TRUE \\* TODO guard: encode the enabling condition of ${s.leaf}()`);for(let c of s.writes){let d=t.find(p=>p.name===c)?.domainBasis==="sequence"?'Seq({"TODO"})':`${c}Domain`;o.push(` /\\ ${c}' \\in ${d} \\* TODO: tighten to the concrete transition`)}a.length>0&&o.push(` /\\ UNCHANGED <<${a.join(", ")}>>`),o.push("")}if(o.push("Next =="),n.length===0)o.push(" FALSE \\* TODO: no state-writing callables were discovered");else for(let[s,a]of n.entries())o.push(` \\/ ${a.name}`);o.push(""),o.push("Spec == Init /\\ [][Next]_vars"),o.push(""),o.push("TypeOK ==");for(let s of t)s.domainBasis==="sequence"?o.push(` /\\ ${s.name} \\in Seq({"TODO"}) \\* TODO: element domain`):o.push(` /\\ ${s.name} \\in ${s.name}Domain`);return o.push("===="),o.push(""),o.join(`
551
556
  `)}function M$(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
552
557
  `)}function _$(e,t,n,r,i){let o={module:`${t}/${e}.tla`,config:`${t}/${e}.cfg`,scope:[n],derived:{generatedBy:"scip-query tla scaffold",basis:"static-scan",generatedFrom:n},variables:Object.fromEntries(r.map(s=>[s.name,{code:[s.codeRef],aliases:[s.leaf]}])),actions:Object.fromEntries(i.map(s=>[s.name,{code:[s.codeRef],reads:s.reads,writes:s.writes,calls:[]}])),invariants:["TypeOK"],traces:[]};return`${JSON.stringify(o,null,2)}
553
- `}function q$(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yf(e,t){let n=Object.keys(t.variables),r=Object.entries(t.actions).map(([i,o])=>{let s=o.code[0]??"",a=s?Vo(e,s):null;return{action:i,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:o.writes}});return{recorderSource:B$(n),wiring:r,variables:n}}function B$(e){return`/**
558
+ `}function B$(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yf(e,t){let n=Object.keys(t.variables),r=Object.entries(t.actions).map(([i,o])=>{let s=o.code[0]??"",a=s?Vo(e,s):null;return{action:i,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:o.writes}});return{recorderSource:q$(n),wiring:r,variables:n}}function q$(e){return`/**
554
559
  * Generated by 'scip-query tla instrument'. Dependency-free trace recorder.
555
560
  *
556
561
  * Usage inside a mapped action (record the model-visible slice around the
@@ -599,9 +604,9 @@ export function tlaRecord(action: string, before: Record<string, unknown>, after
599
604
  `);return{moduleName:p,moduleText:f,cfgText:g,variables:l,skippedVariables:d,states:s.length,warnings:i}}function Sf(e){let t=e.mappedActions??[],n=K$(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:_r(t,[])};let r=H$(pn(U$(),"scip-tla-trace-"));try{let i=z$(e.specPath);for(let d of W$(i))d.endsWith(".tla")&&V$(pn(i,d),pn(r,d));let o=pn(r,`${n.moduleName}.tla`),s=pn(r,`${n.moduleName}.cfg`);bf(o,n.moduleText),bf(s,n.cfgText);let a=Dr({...e.toolOptions,specPath:o,configPath:s,checker:"tlc"});if(a.status==="skipped")return{status:"unavailable",states:n.states,detail:a.diagnostics[0]?.message??"model checker unavailable",checker:a,generation:n,actionCoverage:_r(t,[])};if(a.status==="passed")return{status:"accepted",states:n.states,detail:`TLC accepted all ${n.states} pinned states under ${e.baseModuleName}!${e.nextOperator??"Next"}.`,checker:a,generation:n,actionCoverage:_r(t,e.steps)};let c=Q$(a.stdout,e.steps),l=c?e.steps.slice(0,c.divergedStep.index):[];return{status:"diverged",states:n.states,...c??{},detail:c?`trace diverges entering state ${c.divergedAtState+1} (step ${c.divergedStep.index}: ${c.divergedStep.action}) \u2014 the model's ${e.nextOperator??"Next"} relation does not accept the recorded transition.`:"TLC rejected the trace but the divergent step could not be parsed from its output; see checker stdout.",checker:a,generation:n,actionCoverage:_r(t,l)}}finally{G$(r,{recursive:!0,force:!0})}}function Q$(e,t){let n=null;for(let o of e.matchAll(/\btraceIdx = (\d+)/g)){let s=Number.parseInt(o[1],10);(n===null||s>n)&&(n=s)}if(n===null||!/deadlock/i.test(e))return null;let r=n-1,i=t[r];return{divergedAtState:n,divergedStep:{index:r,action:i?.action??"unknown"}}}function Y$(e){if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isInteger(e))return e;if(Array.isArray(e)){let t=[];for(let n of e)if(typeof n=="string"||typeof n=="boolean")t.push(n);else if(typeof n=="number"&&Number.isInteger(n))t.push(n);else return;return t}}function vf(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>vf(t)).join(", ")}>>`}function xf(e){return J$(e).replace(/\.tla$/i,"")}import{mkdirSync as kf,writeFileSync as wf}from"fs";import{dirname as X$,join as Ot}from"path";var Z$=async(...e)=>{let{args:t,opts:n}=xc(e),r=A(t,0);if(r==="fetch-tools"){let o=await zm();if(b(n,"json")){I("tla",t,n,o);return}console.log(`tla2tools.jar ${o.status}: ${o.path}`),console.log(`Version: ${o.version}`),console.log(`SHA-256: ${o.sha256}`);return}if(r==="scaffold"){let o=V(t,1);if(!o)throw new Error("tla scaffold requires a target source file");ce(s=>eC(s,t,n,o));return}if(r==="instrument"){let o=V(t,1);ce(s=>tC(s,t,n,o));return}if(r==="trace-check"){let o=V(t,1);if(!o)throw new Error("tla trace-check requires a spec path");ce(s=>nC(s,t,n,o));return}if(r!=="verify")throw new Error(`unknown tla operation: ${r}. Supported operations: verify, scaffold, instrument, trace-check, fetch-tools`);let i=V(t,1);if(!i)throw new Error("tla verify requires a spec path");ce(o=>oC(o,t,n,i))};function eC(e,t,n,r){let i=e.config.projectRoot,o=gf(e,r,{moduleName:w(n,"moduleName"),specDir:w(n,"out")}),s=w(n,"out")??Ot("specs",o.moduleName),a=ue(i,s);if(!a)throw new Error(`scaffold output dir escapes the project root: ${s}`);let c=b(n,"force"),l=[{path:Ot(a,`${o.moduleName}.tla`),body:o.spec},{path:Ot(a,`${o.moduleName}.cfg`),body:o.cfg},{path:Ot(a,`${o.moduleName}.scip-tla.json`),body:o.map}];for(let d of l)if(!c&&mn(d.path))throw new Error(`refusing to overwrite ${d.path} (pass --force to replace scaffold output)`);kf(a,{recursive:!0});for(let d of l)wf(d.path,d.body);if(b(n,"json")){I("tla",t,n,{operation:"scaffold",moduleName:o.moduleName,target:r,written:l.map(d=>d.path),variables:o.variables,actions:o.actions,warnings:o.warnings});return}console.log(`Scaffolded ${o.moduleName} from ${r} (draft \u2014 review every TODO):`);for(let d of l)console.log(` wrote ${d.path}`);console.log(`Variables (${o.variables.length}): ${o.variables.map(d=>`${d.name}${d.domainTla?"":" [TODO domain]"}`).join(", ")}`),console.log(`Actions (${o.actions.length}): ${o.actions.map(d=>`${d.name}(writes: ${d.writes.join(",")||"-"})`).join("; ")}`);for(let d of o.warnings)console.log(`WARNING: ${d}`);console.log(`Next: fill the TODO guards/domains, then run 'scip-query tla verify ${Ot(s,`${o.moduleName}.tla`)}'.`)}function tC(e,t,n,r){let i=e.config.projectRoot,o=w(n,"map")??(r?Er(r):void 0);if(!o)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=Ir(i,o);if(!s.loaded)throw new Error(s.errors.join(`
600
605
  `));let{contract:a,mapDir:c}=s.loaded,l=yf(e,a),d=w(n,"out")??Ot(c,"scip-tla-recorder.ts"),p=ue(i,d);if(!p)throw new Error(`instrument output escapes the project root: ${d}`);if(!b(n,"force")&&mn(p))throw new Error(`refusing to overwrite ${p} (pass --force to replace the recorder)`);if(kf(X$(p),{recursive:!0}),wf(p,l.recorderSource),b(n,"json")){I("tla",t,n,{operation:"instrument",recorder:p,variables:l.variables,wiring:l.wiring});return}console.log(`Wrote trace recorder: ${p}`),console.log("Wire tlaRecord(...) into each mapped action (1 line per action), then run your tests with"),console.log("SCIP_TLA_TRACE=<trace.json> set, and check the result with 'scip-query tla trace-check'."),console.log("Wiring sites:");for(let m of l.wiring){let f=m.file?`${m.file}:${m.line}`:`UNRESOLVED (${m.codeRef})`;console.log(` - ${m.action} -> ${f} writes: ${m.writes.join(", ")||"-"}`)}}function nC(e,t,n,r){let i=e.config.projectRoot,o=ue(i,r);if(!o||!mn(o))throw new Error(`TLA+ spec not found: ${r}`);let s=w(n,"map")??Er(r),a=Ir(i,s);if(!a.loaded)throw new Error(a.errors.join(`
601
606
  `));let{contract:c}=a.loaded,l=Ct(n,"trace"),p=ho(i,[...c.traces,...l]).flatMap(g=>go(i,g).steps);if(p.length===0)throw new Error("no trace steps found: pass --trace <file> (repeatable) or list traces in the mapping contract");let m=Sf({specPath:o,baseModuleName:xf(o),mappedVariables:Object.keys(c.variables),mappedActions:Object.keys(c.actions),steps:p,nextOperator:w(n,"next"),toolOptions:{projectRoot:i,tlaToolsJar:w(n,"tlaTools"),timeoutMs:U(n,"timeoutMs")}}),f=m.status==="accepted"||m.status==="unavailable"&&b(n,"allowUnknown")?0:1;if(b(n,"json")){I("tla",t,n,{operation:"trace-check",...m,exitCode:f}),process.exitCode=f;return}if(console.log(`TLA+ trace-check: ${o}`),console.log(`Trace: ${p.length} step(s) -> ${m.states} pinned state(s)`),m.generation){console.log(`Pinned variables: ${m.generation.variables.join(", ")}`);for(let g of m.generation.warnings)console.log(`WARNING: ${g}`)}console.log(`${m.status.toUpperCase()}: ${m.detail}`),b(n,"coverage")&&rC(m.actionCoverage),process.exitCode=f}function rC(e){if(e.length===0)return;let t=e.filter(r=>r.stepsObserved>0),n=e.filter(r=>r.stepsObserved===0);console.log(`Action coverage: ${t.length}/${e.length} mapped action(s) exercised by this trace.`);for(let r of t)console.log(` - ${r.action}: ${r.stepsObserved} step(s)`);n.length>0&&console.log(` Unexercised: ${n.map(r=>r.action).join(", ")} \u2014 classify each as a pure modeling abstraction (no code twin, expected) or a real coverage gap (record another trace).`)}function iC(e,t,n,r){let i=w(r,"map");if(i)return{mapArg:i};let o=Er(t),s=ue(e,o);if(s&&mn(s))return{mapArg:o};let a=tm(e,n);if(a.status==="ambiguous")throw new Error(`multiple *.scip-tla.json files declare module "${a.moduleName}": ${a.candidates.join(", ")} \u2014 pass --map to disambiguate`);return a.status==="found"?{mapArg:a.mapPath,mappingDiscoveredBy:"module-field"}:{mapArg:o}}function oC(e,t,n,r){let i=e.config.projectRoot,o=ue(i,r);if(!o||!mn(o))throw new Error(`TLA+ spec not found: ${r}`);let{mapArg:s,mappingDiscoveredBy:a}=iC(i,r,o,n),c=Ir(i,s);if(!c.loaded)throw new Error(c.errors.join(`
602
- `));let{contract:l,mapPath:d,mapDir:p}=c.loaded,m=w(n,"config")??l.config,f=Qp(i,p,m),g=aC(w(n,"checker")??"auto"),h=w(n,"tlaTools"),y=sC(i,r,o,h)??Yp(i,r),S=Zp(f),v=Ct(n,"trace"),R=ho(i,[...l.traces,...v]).map(O=>({tracePath:O,...go(i,O)})),D=R.flatMap(O=>O.steps),q=new Set(v),z=R.filter(O=>q.has(O.tracePath)).flatMap(O=>O.errors),T=nf(e,l,y,D,S);for(let O of[...c.errors,...z])T.findings.push({id:`TLA-CONTRACT-${T.findings.length+1}`,severity:"error",evidence:"contract",category:"contract",message:O,why:["The verifier can only make accurate claims after the mapping and trace inputs are valid."],remediation:"Fix the mapping or trace input and rerun scip-query tla verify."});let F=Dr({projectRoot:i,specPath:o,configPath:f??void 0,checker:g,tlaToolsJar:h,apalacheBin:w(n,"apalache"),length:C(n,"length",10),timeoutMs:U(n,"timeoutMs")});F.status==="skipped"&&g!=="none"&&T.findings.push({id:"TLA-MODEL-CHECKER-UNAVAILABLE",severity:"warning",evidence:"unknown",category:"contract",message:F.diagnostics.map(O=>O.message).join("; "),why:["The TLA+ model was not checked by SANY, TLC, or Apalache in this run."],remediation:"Install the requested checker, run 'scip-query tla fetch-tools', set TLA_TOOLS_JAR, pass --apalache, or rerun with --checker none intentionally."});let Z={operation:"verify",specPath:o,mapPath:d,...a?{mappingDiscoveredBy:a}:{},...f?{configPath:f}:{},checker:F,conformance:T,exitCode:cC(F,T,b(n,"allowUnknown"))};if(b(n,"json")){I("tla",t,n,Z),process.exitCode=Z.exitCode;return}lC(Z,b(n,"full")),process.exitCode=Z.exitCode}function sC(e,t,n,r){let i=Ro({projectRoot:e,specPath:n,tlaToolsJar:r,checker:"sany"});if(!i)return null;let o=qp({specPath:n,jarPath:i});return o?Xp(e,t,o):null}var $f=[{id:"tla",command:"tla <operation> [spec]",description:"TLA+ model workflow: verify a model and mapping contract, scaffold a draft model from indexed code, generate a trace recorder, or check a recorded trace against the next-state relation",options:P([u("--map <file>","scip-query TLA mapping JSON file"),u("--config <file>","TLA+ checker config file"),u("--checker <mode>","Checker mode: auto, sany, tlc, apalache, none",void 0,"auto"),u("--tla-tools <jar>","Path to tla2tools.jar"),u("--apalache <binary>","Path to apalache-mc binary"),u("--length <n>","Bounded checker length for Apalache",x,10),u("--timeout-ms <n>","Model checker subprocess timeout in milliseconds (verify and trace-check; default 120000)",Be),u("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",ot,[]),u("--next <operator>","trace-check: next-state operator the harness requires between states (default Next; use for dual-spec models, e.g. NextCurrent)",void 0,"Next"),u("--coverage","trace-check: print the per-action coverage table (steps exercised per mapped action, counted from accepted trace steps only); --json always includes it"),u("--allow-unknown","Exit zero when only unknown findings remain"),u("--out <path>","Output directory (scaffold) or file (instrument)"),u("--module-name <name>","Module name for scaffolded specs"),u("--force","Overwrite existing scaffold/instrument output"),u("--full","verify: print every finding ungrouped instead of (category, modelElement) groups with 3 exemplars each")]),renderShape:"custom",docs:$("Formal Models",["scip-query tla verify specs/Queue.tla --map specs/Queue.scip-tla.json","scip-query tla scaffold src/queue/store.ts","scip-query tla trace-check specs/Queue.tla --trace traces/run1.json --coverage","scip-query tla trace-check specs/Queue.tla --trace traces/run1.json --trace traces/run2.json --coverage","scip-query tla trace-check specs/DualSpec.tla --trace traces/run1.json --next NextCurrent","scip-query tla verify specs/Queue.tla --timeout-ms 300000","scip-query tla verify specs/Queue.tla --full","scip-query tla fetch-tools"]),handler:Z$}];function aC(e){if(!Kp(e))throw new Error(`unknown checker mode: ${e}`);return e}function cC(e,t,n){return e.status==="failed"||e.status==="timed-out"||t.findings.some(r=>r.severity==="error")||!n&&t.findings.some(r=>r.evidence==="unknown")?1:0}var Rf=3;function lC(e,t){console.log(`TLA+ verify: ${e.specPath}`),console.log(`Mapping: ${e.mapPath}${e.mappingDiscoveredBy==="module-field"?" (matched by module field)":""}`),e.configPath&&console.log(`Config: ${e.configPath}`),console.log(`Checker: ${e.checker.checker} ${e.checker.status} (${e.checker.durationMs}ms, exit ${e.checker.exitCode??e.checker.signal??"n/a"})`);for(let o of e.checker.diagnostics)console.log(` [${o.severity}] ${o.message}`);let n=e.conformance.findings.filter(o=>o.severity==="error"),r=e.conformance.findings.filter(o=>o.evidence==="unknown"),i=uC(e);console.log(`
607
+ `));let{contract:l,mapPath:d,mapDir:p}=c.loaded,m=w(n,"config")??l.config,f=Qp(i,p,m),g=aC(w(n,"checker")??"auto"),h=w(n,"tlaTools"),y=sC(i,r,o,h)??Yp(i,r),S=Zp(f),v=Ct(n,"trace"),R=ho(i,[...l.traces,...v]).map(O=>({tracePath:O,...go(i,O)})),D=R.flatMap(O=>O.steps),B=new Set(v),z=R.filter(O=>B.has(O.tracePath)).flatMap(O=>O.errors),T=nf(e,l,y,D,S);for(let O of[...c.errors,...z])T.findings.push({id:`TLA-CONTRACT-${T.findings.length+1}`,severity:"error",evidence:"contract",category:"contract",message:O,why:["The verifier can only make accurate claims after the mapping and trace inputs are valid."],remediation:"Fix the mapping or trace input and rerun scip-query tla verify."});let F=Dr({projectRoot:i,specPath:o,configPath:f??void 0,checker:g,tlaToolsJar:h,apalacheBin:w(n,"apalache"),length:C(n,"length",10),timeoutMs:U(n,"timeoutMs")});F.status==="skipped"&&g!=="none"&&T.findings.push({id:"TLA-MODEL-CHECKER-UNAVAILABLE",severity:"warning",evidence:"unknown",category:"contract",message:F.diagnostics.map(O=>O.message).join("; "),why:["The TLA+ model was not checked by SANY, TLC, or Apalache in this run."],remediation:"Install the requested checker, run 'scip-query tla fetch-tools', set TLA_TOOLS_JAR, pass --apalache, or rerun with --checker none intentionally."});let Z={operation:"verify",specPath:o,mapPath:d,...a?{mappingDiscoveredBy:a}:{},...f?{configPath:f}:{},checker:F,conformance:T,exitCode:cC(F,T,b(n,"allowUnknown"))};if(b(n,"json")){I("tla",t,n,Z),process.exitCode=Z.exitCode;return}lC(Z,b(n,"full")),process.exitCode=Z.exitCode}function sC(e,t,n,r){let i=Ro({projectRoot:e,specPath:n,tlaToolsJar:r,checker:"sany"});if(!i)return null;let o=Bp({specPath:n,jarPath:i});return o?Xp(e,t,o):null}var $f=[{id:"tla",command:"tla <operation> [spec]",description:"TLA+ model workflow: verify a model and mapping contract, scaffold a draft model from indexed code, generate a trace recorder, or check a recorded trace against the next-state relation",options:P([u("--map <file>","scip-query TLA mapping JSON file"),u("--config <file>","TLA+ checker config file"),u("--checker <mode>","Checker mode: auto, sany, tlc, apalache, none",void 0,"auto"),u("--tla-tools <jar>","Path to tla2tools.jar"),u("--apalache <binary>","Path to apalache-mc binary"),u("--length <n>","Bounded checker length for Apalache",x,10),u("--timeout-ms <n>","Model checker subprocess timeout in milliseconds (verify and trace-check; default 120000)",qe),u("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",ot,[]),u("--next <operator>","trace-check: next-state operator the harness requires between states (default Next; use for dual-spec models, e.g. NextCurrent)",void 0,"Next"),u("--coverage","trace-check: print the per-action coverage table (steps exercised per mapped action, counted from accepted trace steps only); --json always includes it"),u("--allow-unknown","Exit zero when only unknown findings remain"),u("--out <path>","Output directory (scaffold) or file (instrument)"),u("--module-name <name>","Module name for scaffolded specs"),u("--force","Overwrite existing scaffold/instrument output"),u("--full","verify: print every finding ungrouped instead of (category, modelElement) groups with 3 exemplars each")]),renderShape:"custom",docs:$("Formal Models",["scip-query tla verify specs/Queue.tla --map specs/Queue.scip-tla.json","scip-query tla scaffold src/queue/store.ts","scip-query tla trace-check specs/Queue.tla --trace traces/run1.json --coverage","scip-query tla trace-check specs/Queue.tla --trace traces/run1.json --trace traces/run2.json --coverage","scip-query tla trace-check specs/DualSpec.tla --trace traces/run1.json --next NextCurrent","scip-query tla verify specs/Queue.tla --timeout-ms 300000","scip-query tla verify specs/Queue.tla --full","scip-query tla fetch-tools"]),handler:Z$}];function aC(e){if(!Kp(e))throw new Error(`unknown checker mode: ${e}`);return e}function cC(e,t,n){return e.status==="failed"||e.status==="timed-out"||t.findings.some(r=>r.severity==="error")||!n&&t.findings.some(r=>r.evidence==="unknown")?1:0}var Rf=3;function lC(e,t){console.log(`TLA+ verify: ${e.specPath}`),console.log(`Mapping: ${e.mapPath}${e.mappingDiscoveredBy==="module-field"?" (matched by module field)":""}`),e.configPath&&console.log(`Config: ${e.configPath}`),console.log(`Checker: ${e.checker.checker} ${e.checker.status} (${e.checker.durationMs}ms, exit ${e.checker.exitCode??e.checker.signal??"n/a"})`);for(let o of e.checker.diagnostics)console.log(` [${o.severity}] ${o.message}`);let n=e.conformance.findings.filter(o=>o.severity==="error"),r=e.conformance.findings.filter(o=>o.evidence==="unknown"),i=uC(e);console.log(`
603
608
  Conformance: ${e.conformance.mappedVariables} variable(s), ${e.conformance.mappedActions} action(s), ${e.conformance.resolvedReferents} resolved referent(s).`),console.log(`Proof: ${i}`);for(let o of pC(e))console.log(`WARNING: ${o}`);if(e.conformance.waivers.length>0){console.log("Waivers:");for(let o of e.conformance.waivers){let s=o.legacy?" legacy":"",a=o.action?`${o.action} ${o.kind}`:`variable ${o.kind}`;console.log(` - ${a} ${o.variable}:${s} ${o.reason}`)}}if(e.conformance.findings.length===0){console.log(e.conformance.waivers.length===0?`PASS: model, mapping, and checked code evidence agree (model parsed by: ${e.conformance.modelParse}).`:`PASS: model checker and unwaived conformance checks passed (model parsed by: ${e.conformance.modelParse}); see waived facts above.`);return}if(console.log(`Findings: ${n.length} error(s), ${r.length} unknown(s), ${e.conformance.findings.length} total.`),t){for(let o of e.conformance.findings)Cf(o);return}dC(e.conformance)}function dC(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
604
609
  Finding groups (${e.findingGroups.length}) \u2014 pass --full for every finding ungrouped:`);for(let n of e.findingGroups){console.log(`
605
610
  [${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let i of n.findingIds.slice(0,Rf)){let o=t.get(i);o&&Cf(o)}let r=n.count-Rf;r>0&&console.log(` ... and ${r} more in this group (use --full to show all)`)}}function uC(e){let t=`${e.checker.checker} ${e.checker.status==="passed"?"PASS":e.checker.status.toUpperCase()}`,n=e.conformance.waivers.filter(s=>s.kind==="write").length,r=e.conformance.waivers.filter(s=>s.kind==="read").length,i=e.conformance.waivers.filter(s=>s.kind==="referent").length,o=e.conformance.findings.filter(s=>s.category==="missing-call").length;return[`checker: ${t}`,`model parsed by: ${e.conformance.modelParse}`,`writes: ${e.conformance.staticWrites.length} verified, ${n} waived`,`reads: ${e.conformance.staticReads.length} verified, ${r} waived`,`calls: ${o===0?"checked":`${o} missing`}`,`traces: ${e.conformance.traceStepsChecked} steps (key-diff; 'tla trace-check' proves acceptance)`,...i>0?[`referents: ${i} waived`]:[]].join(" | ")}function pC(e){let t=[],n=e.conformance.waivers.filter(i=>i.kind==="write").length,r=e.conformance.waivers.filter(i=>i.kind==="read").length;return n>0&&e.conformance.staticWrites.length===0&&t.push("NOTHING PROVEN ABOUT WRITES: every write fact found in this run was waived or unobserved."),r>0&&e.conformance.staticReads.length===0&&t.push("NOTHING PROVEN ABOUT READS: every read fact found in this run was waived or unobserved."),t}function Cf(e){let t=e.file&&e.startLine!==void 0&&e.endLine!==void 0?` ${M(e.file,e.startLine,e.endLine)}`:e.file?` ${e.file}`:"";console.log(`
606
- [${e.severity}] ${e.category} (${e.evidence})${t}`),console.log(` ${e.message}`);for(let n of e.why)console.log(` why: ${n}`);console.log(` fix: ${e.remediation}`)}var Pf=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","architecture","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","tla","plan-context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","dataflow","slice","redundant-reexports","duplicate-bodies","twin-drift","twin-ab","not-implemented","decorative-checkers","test-quality","similar-signatures"],mC=[Dm,Mm,Fm,Ar,Nm,_m,$f,Om],Tf=mC.flat(),fC=new Map(Tf.map(e=>[e.id,e]));for(let e of Tf)if(!Pf.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Nt=Pf.map(e=>gC(e));function gC(e){let t=fC.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var hC=Nt.slice(0,jo("plan-context")),yC=Nt.slice(qr("drift"),jo("self-audit")),bC=Nt.slice(qr("convergence"),jo("slice")),SC=Nt.slice(qr("redundant-reexports")),nF=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[u("-l, --language <lang>","Index only this language (can be repeated)",ot,[]),u("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),u("--force","Rebuild even if source inputs are unchanged"),u("--allow-partial","Write an incomplete index when one or more detected languages fail"),u("--indexer-concurrency <n>","Number of language indexers to run at once",Be),u("--json","Output as JSON, including per-shard reuse diagnostics")],renderShape:"custom",docs:$("Indexing",["scip-query reindex"]),handler:rp},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:$("Indexing"),handler:ip},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[u("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:$("Indexing"),handler:op},...hC,{id:Kr,command:Kr,description:"Internal diff-impact batch worker",hidden:!0,options:[u("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:sp},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:P([u("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:$("Impact"),handler:ap},...yC,{id:zr,command:zr,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:cp},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded candidate analyses on large indexes"),u("--json","Output as JSON for programmatic consumption"),u("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),u("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:$("Health",["scip-query health --json","scip-query health --baseline"]),handler:lp},{id:"bench",command:"bench",description:"Benchmark indexing and command runtimes for this repository",options:[u("--json","Output as JSON for programmatic consumption"),u("--cold-index","Temporarily clear this project index cache and measure a cold rebuild"),u("--include-heavy","Include expensive full-detector commands in the command matrix"),u("--command <cmd>","Benchmark a specific scip-query command (can be repeated)",ot,[]),u("--timeout-ms <n>","Per-command timeout in milliseconds",Be,18e4),u("--progress","Print benchmark command start/finish progress to stderr"),u("--profile","Enable low-overhead phase profiling in benchmarked commands"),u("--profile-out <path>","Append benchmark and phase profile events as JSONL")],renderShape:"custom",docs:$("Maintenance",["scip-query bench","scip-query bench --json --cold-index"]),handler:dp},{id:"work-audit",command:"work-audit <profile>",description:"Rank exact repeated computations in a profiling JSONL file by measured avoidable time",options:[u("--top <n>","Maximum repeated-work groups to show",Be,20),u("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",docs:$("Maintenance",["scip-query work-audit profile.jsonl","scip-query work-audit profile.jsonl --json"]),handler:up},{id:"typescript-semantic-compare",command:"typescript-semantic-compare",description:"Compare tsserver reference answers against the ts-morph baseline",hidden:!0,options:[u("-s, --scope <path>","Limit compared definitions to files matching path"),u("--limit <n>","Maximum definitions to compare unless --full is set",Be),u("--max-mismatches <n>","Maximum mismatch details to include in output",$t),u("--full","Compare every indexed TypeScript-like definition"),u("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",handler:pp},...bC,{id:"install-skills",command:"install-skills",description:`Install skills (${Xn.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:$("Maintenance"),handler:gp},{id:"setup-hooks",command:"setup-hooks",description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[u("--shared","Deprecated compatibility flag; hooks remain checkout-local and untracked"),u("--remove","Remove managed project hooks and remember the opt-out"),u("--force","Reinstall hooks even after a previous --remove opt-out"),u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:hp},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:fl},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:gl},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:$("Maintenance"),handler:yp},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[u("--matrix","Render the project capability matrix (default output)"),u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:bp},{id:"capability-matrix",command:"capability-matrix",description:"Deprecated alias for capabilities --matrix",options:[u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:Sp},...SC,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:$("Maintenance"),handler:xp},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance",["scip-query config-validate"]),handler:Rp},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding as a file under .scipquery/suppressions/ with a required reason",options:P([u("--reason <text>","Required human reason for accepting the finding"),u("--check <check>","Optional detector/check name to narrow the suppression"),u("--file <path>","Optional file path to narrow the suppression"),u("--expires-at <iso>","Optional ISO date after which the suppression expires")]),renderShape:"custom",docs:$("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:kp},{id:"effectiveness",command:"effectiveness",description:"Per-check effectiveness from the committed outcome ledger: caught, comparison-verified fixes, suppressed, unverified disappearances, and precision",options:P([u("--since <window>","Only count findings first caught in this window (30d, 12w, or an ISO date)"),u("--check <check>","Restrict to one diff-gate check")]),renderShape:"custom",docs:$("Maintenance",["scip-query effectiveness --since 30d","scip-query effectiveness --check echo --json"]),handler:wp},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:$p},{id:"setup",command:"setup",description:"Bootstrap this project: enable automatic indexing, install agent skills, refresh the index, verify capabilities, and report health",options:P([u("--guided","Open the interactive checklist (the default in a terminal)"),u("--yes","Accept recommended setup defaults without prompting"),u("--git-hook","Also install a git pre-commit hook that runs diff-gate"),u("--no-hooks","Skip Codex and Claude Code lifecycle hook installation"),u("--no-skills","Skip user-level agent skill installation"),u("--no-parsers","Skip Tree-sitter AST parser installation and repair"),u("--no-health","Skip the optional full health audit and dossier"),u("--dossier-dir <path>","Directory for generated setup health dossier files")]),renderShape:"custom",docs:$("Maintenance",["scip-query setup","scip-query setup --json"]),handler:Tp},{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:[u("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:Pp},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[u("--force","Overwrite an existing workflow"),u("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-ci"]),handler:Ip},{id:"uninstall",command:"uninstall",description:"Remove scip-query-owned skill links, project hooks, and managed agent setup blocks",options:P([u("--global","Remove scip-query-owned skill symlinks from user-level agent skill roots"),u("--project","Remove project-local hooks and managed AGENTS.md/CLAUDE.md blocks"),u("--dry-run","List what would be removed without changing files")]),renderShape:"custom",docs:$("Maintenance",["scip-query uninstall --dry-run","scip-query uninstall --project"]),handler:Ep},{id:"watch",command:"watch",description:"Watch in the foreground or manage the per-project background refresh service",options:P([u("--daemon","Ensure the demand-started background service is running"),u("--status","Show background/foreground watcher state"),u("--stop","Stop the watcher or background service for this project"),u("--debounce <ms>","Ms to wait after last change (default: 250)",$t),u("--cooldown <ms>","Min ms between reindexes; 0 disables spacing (default: 0)",$t),u("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",$t),u("--idle-timeout <ms>","Ms before clean-idle daemon exit; 0 keeps it running (default: 600000)",$t)]),renderShape:"custom",docs:$("Maintenance",["scip-query watch","scip-query watch --daemon","scip-query watch --status --json","scip-query watch --stop"]),handler:jp},{id:"status",command:"status",description:"Show index status for this project",options:[u("--json","Output as JSON for programmatic consumption"),u("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:$("Maintenance"),handler:Dp}];function qr(e){let t=Nt.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function jo(e){return qr(e)+1}export{nF as commandDescriptors};
607
- //# sourceMappingURL=command-descriptors-QJEYYND2.js.map
611
+ [${e.severity}] ${e.category} (${e.evidence})${t}`),console.log(` ${e.message}`);for(let n of e.why)console.log(` why: ${n}`);console.log(` fix: ${e.remediation}`)}var Pf=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","architecture","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","tla","plan-context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","dataflow","slice","redundant-reexports","duplicate-bodies","twin-drift","twin-ab","not-implemented","decorative-checkers","test-quality","similar-signatures"],mC=[Dm,Mm,Fm,Ar,Nm,_m,$f,Om],Tf=mC.flat(),fC=new Map(Tf.map(e=>[e.id,e]));for(let e of Tf)if(!Pf.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Nt=Pf.map(e=>gC(e));function gC(e){let t=fC.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var hC=Nt.slice(0,jo("plan-context")),yC=Nt.slice(Br("drift"),jo("self-audit")),bC=Nt.slice(Br("convergence"),jo("slice")),SC=Nt.slice(Br("redundant-reexports")),nF=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[u("-l, --language <lang>","Index only this language (can be repeated)",ot,[]),u("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),u("--force","Rebuild even if source inputs are unchanged"),u("--allow-partial","Write an incomplete index when one or more detected languages fail"),u("--indexer-concurrency <n>","Number of language indexers to run at once",qe),u("--json","Output as JSON, including per-shard reuse diagnostics")],renderShape:"custom",docs:$("Indexing",["scip-query reindex"]),handler:rp},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:$("Indexing"),handler:ip},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[u("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:$("Indexing"),handler:op},...hC,{id:Kr,command:Kr,description:"Internal diff-impact batch worker",hidden:!0,options:[u("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:sp},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:P([u("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:$("Impact"),handler:ap},...yC,{id:zr,command:zr,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:cp},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded candidate analyses on large indexes"),u("--json","Output as JSON for programmatic consumption"),u("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),u("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:$("Health",["scip-query health --json","scip-query health --baseline"]),handler:lp},{id:"bench",command:"bench",description:"Benchmark indexing and command runtimes for this repository",options:[u("--json","Output as JSON for programmatic consumption"),u("--cold-index","Temporarily clear this project index cache and measure a cold rebuild"),u("--include-heavy","Include expensive full-detector commands in the command matrix"),u("--command <cmd>","Benchmark a specific scip-query command (can be repeated)",ot,[]),u("--timeout-ms <n>","Per-command timeout in milliseconds",qe,18e4),u("--progress","Print benchmark command start/finish progress to stderr"),u("--profile","Enable low-overhead phase profiling in benchmarked commands"),u("--profile-out <path>","Append benchmark and phase profile events as JSONL")],renderShape:"custom",docs:$("Maintenance",["scip-query bench","scip-query bench --json --cold-index"]),handler:dp},{id:"work-audit",command:"work-audit <profile>",description:"Rank exact repeated computations in a profiling JSONL file by measured avoidable time",options:[u("--top <n>","Maximum repeated-work groups to show",qe,20),u("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",docs:$("Maintenance",["scip-query work-audit profile.jsonl","scip-query work-audit profile.jsonl --json"]),handler:up},{id:"typescript-semantic-compare",command:"typescript-semantic-compare",description:"Compare tsserver reference answers against the ts-morph baseline",hidden:!0,options:[u("-s, --scope <path>","Limit compared definitions to files matching path"),u("--limit <n>","Maximum definitions to compare unless --full is set",qe),u("--max-mismatches <n>","Maximum mismatch details to include in output",$t),u("--full","Compare every indexed TypeScript-like definition"),u("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",handler:pp},...bC,{id:"install-skills",command:"install-skills",description:`Install skills (${Xn.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:$("Maintenance"),handler:gp},{id:"setup-hooks",command:"setup-hooks",description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[u("--shared","Deprecated compatibility flag; hooks remain checkout-local and untracked"),u("--remove","Remove managed project hooks and remember the opt-out"),u("--force","Reinstall hooks even after a previous --remove opt-out"),u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:hp},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:fl},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:gl},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:$("Maintenance"),handler:yp},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[u("--matrix","Render the project capability matrix (default output)"),u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:bp},{id:"capability-matrix",command:"capability-matrix",description:"Deprecated alias for capabilities --matrix",options:[u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:Sp},...SC,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:$("Maintenance"),handler:xp},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance",["scip-query config-validate"]),handler:Rp},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding as a file under .scipquery/suppressions/ with a required reason",options:P([u("--reason <text>","Required human reason for accepting the finding"),u("--check <check>","Optional detector/check name to narrow the suppression"),u("--file <path>","Optional file path to narrow the suppression"),u("--expires-at <iso>","Optional ISO date after which the suppression expires")]),renderShape:"custom",docs:$("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:kp},{id:"effectiveness",command:"effectiveness",description:"Per-check effectiveness from the committed outcome ledger: caught, comparison-verified fixes, suppressed, unverified disappearances, and precision",options:P([u("--since <window>","Only count findings first caught in this window (30d, 12w, or an ISO date)"),u("--check <check>","Restrict to one diff-gate check")]),renderShape:"custom",docs:$("Maintenance",["scip-query effectiveness --since 30d","scip-query effectiveness --check echo --json"]),handler:wp},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[u("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:$p},{id:"setup",command:"setup",description:"Bootstrap this project: enable automatic indexing, install agent skills, refresh the index, verify capabilities, and report health",options:P([u("--guided","Open the interactive checklist (the default in a terminal)"),u("--yes","Accept recommended setup defaults without prompting"),u("--git-hook","Also install a git pre-commit hook that runs diff-gate"),u("--no-hooks","Skip Codex and Claude Code lifecycle hook installation"),u("--no-skills","Skip user-level agent skill installation"),u("--no-parsers","Skip Tree-sitter AST parser installation and repair"),u("--no-health","Skip the optional full health audit and dossier"),u("--dossier-dir <path>","Directory for generated setup health dossier files")]),renderShape:"custom",docs:$("Maintenance",["scip-query setup","scip-query setup --json"]),handler:Tp},{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:[u("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:Pp},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[u("--force","Overwrite an existing workflow"),u("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-ci"]),handler:Ip},{id:"uninstall",command:"uninstall",description:"Remove scip-query-owned skill links, project hooks, and managed agent setup blocks",options:P([u("--global","Remove scip-query-owned skill symlinks from user-level agent skill roots"),u("--project","Remove project-local hooks and managed AGENTS.md/CLAUDE.md blocks"),u("--dry-run","List what would be removed without changing files")]),renderShape:"custom",docs:$("Maintenance",["scip-query uninstall --dry-run","scip-query uninstall --project"]),handler:Ep},{id:"watch",command:"watch",description:"Watch in the foreground or manage the per-project background refresh service",options:P([u("--daemon","Ensure the demand-started background service is running"),u("--status","Show background/foreground watcher state"),u("--stop","Stop the watcher or background service for this project"),u("--debounce <ms>","Ms to wait after last change (default: 250)",$t),u("--cooldown <ms>","Min ms between reindexes; 0 disables spacing (default: 0)",$t),u("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",$t),u("--idle-timeout <ms>","Ms before clean-idle daemon exit; 0 keeps it running (default: 600000)",$t)]),renderShape:"custom",docs:$("Maintenance",["scip-query watch","scip-query watch --daemon","scip-query watch --status --json","scip-query watch --stop"]),handler:jp},{id:"status",command:"status",description:"Show index status for this project",options:[u("--json","Output as JSON for programmatic consumption"),u("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:$("Maintenance"),handler:Dp}];function Br(e){let t=Nt.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function jo(e){return Br(e)+1}export{nF as commandDescriptors};
612
+ //# sourceMappingURL=command-descriptors-MFU4BCJ7.js.map