scip-query 0.19.0 → 0.19.3

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 (184) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +17 -1
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/{chunk-YHYTDWFT.js → chunk-24ET4VLC.js} +2 -2
  5. package/dist/{chunk-GBB2RUDN.js → chunk-26JI77AY.js} +130 -130
  6. package/dist/{chunk-MFBXBLHA.js → chunk-2E7QY4B5.js} +2 -2
  7. package/dist/{chunk-PXJIEMND.js → chunk-2ROSOG2I.js} +2 -2
  8. package/dist/{chunk-XKWEMFHP.js → chunk-2WCXKANA.js} +2 -2
  9. package/dist/{chunk-EZGT3NJX.js → chunk-33RLKB6L.js} +2 -2
  10. package/dist/{chunk-GJ3FR5WG.js → chunk-34MLC6UI.js} +2 -2
  11. package/dist/{chunk-G6RQVDTI.js → chunk-4BUMNEYQ.js} +2 -2
  12. package/dist/{chunk-XTSVYYAL.js → chunk-4CZJ4YJB.js} +2 -2
  13. package/dist/{chunk-TCVRJ56J.js → chunk-4FMT4HPC.js} +2 -2
  14. package/dist/{chunk-7FG5M53V.js → chunk-53SUJOJA.js} +2 -2
  15. package/dist/{chunk-AEDB4WXE.js → chunk-5FUAFNMP.js} +2 -2
  16. package/dist/chunk-5GCAM4JE.js +122 -0
  17. package/dist/{chunk-YBAC3RON.js → chunk-5GOBZI34.js} +2 -2
  18. package/dist/{chunk-LJD7V7UO.js → chunk-5OR4QRPR.js} +2 -2
  19. package/dist/{chunk-X36LKKVG.js → chunk-5OZCNAVM.js} +2 -2
  20. package/dist/{chunk-7EI4MU5A.js → chunk-5TZ2MQBG.js} +2 -2
  21. package/dist/{chunk-GNJHHPZE.js → chunk-64QITTX7.js} +2 -2
  22. package/dist/{chunk-HOXI4F5I.js → chunk-6EWBPAA3.js} +2 -2
  23. package/dist/{chunk-EZHARAL4.js → chunk-6FIA5BEB.js} +2 -2
  24. package/dist/{chunk-4ZCNFENR.js → chunk-77IOFJVY.js} +2 -2
  25. package/dist/{chunk-T5CSWYAZ.js → chunk-AD7WUFFT.js} +2 -2
  26. package/dist/{chunk-OGHGTD6Z.js → chunk-AEM24WSF.js} +2 -2
  27. package/dist/{chunk-S65OEY2G.js → chunk-AFVU2GB2.js} +2 -2
  28. package/dist/{chunk-SATRCB5O.js → chunk-AOSFSYEA.js} +2 -2
  29. package/dist/{chunk-3OSRXJKK.js → chunk-APLNTJPJ.js} +2 -2
  30. package/dist/{chunk-TDGCALH6.js → chunk-AYRHVJXW.js} +2 -2
  31. package/dist/{chunk-MDDF67O2.js → chunk-B26UX7ZD.js} +2 -2
  32. package/dist/{chunk-JFGUBZWE.js → chunk-C3KCSAQ4.js} +2 -2
  33. package/dist/{chunk-XESK6725.js → chunk-C3VQZFP2.js} +2 -2
  34. package/dist/{chunk-FLIF3JWA.js → chunk-CAKPEQZB.js} +2 -2
  35. package/dist/{chunk-PKAPOFF5.js → chunk-CIYUFF24.js} +2 -2
  36. package/dist/{chunk-J3U47L4Q.js → chunk-DO775SYA.js} +2 -2
  37. package/dist/{chunk-AM2LGOEX.js → chunk-EGKWRX5I.js} +2 -2
  38. package/dist/{chunk-PAZFJMXB.js → chunk-EHU4TZJJ.js} +2 -2
  39. package/dist/{chunk-YYR7ADNB.js → chunk-EII5ZHL2.js} +2 -2
  40. package/dist/{chunk-F5L7WEZF.js → chunk-EYF5HOUZ.js} +2 -2
  41. package/dist/{chunk-RIGY5DDE.js → chunk-FB6IKAKZ.js} +2 -2
  42. package/dist/{chunk-BGUYAA3Q.js → chunk-FBUNGRKI.js} +2 -2
  43. package/dist/{chunk-M2TRDR25.js → chunk-FC5K7T35.js} +1 -1
  44. package/dist/{chunk-KWBA6FDD.js → chunk-FRXB74RQ.js} +2 -2
  45. package/dist/{chunk-BYPVNKJT.js → chunk-FTRNGQGR.js} +2 -2
  46. package/dist/{chunk-54UYBTZW.js → chunk-FUFNRZFJ.js} +2 -2
  47. package/dist/{chunk-TDZXQAH7.js → chunk-FYE4PWWP.js} +2 -2
  48. package/dist/{chunk-QNMOZ3CJ.js → chunk-GAE7WCBK.js} +2 -2
  49. package/dist/{chunk-2ZNZSNVW.js → chunk-HAC5EI2T.js} +2 -2
  50. package/dist/{chunk-WT7TOU2C.js → chunk-HCSTQGQE.js} +2 -2
  51. package/dist/{chunk-UXOVHGT6.js → chunk-HFBNIIZX.js} +2 -2
  52. package/dist/{chunk-JHK2DMUQ.js → chunk-HGFDYOVB.js} +1 -1
  53. package/dist/{chunk-UJL3N6TC.js → chunk-HHOJH3RJ.js} +2 -2
  54. package/dist/{chunk-X65VYV2S.js → chunk-HNTLCR4F.js} +2 -2
  55. package/dist/{chunk-RJLU7IMR.js → chunk-IICQP2DY.js} +2 -2
  56. package/dist/{chunk-J65FQLDL.js → chunk-IXAALOUP.js} +2 -2
  57. package/dist/{chunk-XDVT7QPG.js → chunk-J4MYRIYT.js} +2 -2
  58. package/dist/{chunk-TAB7AWKO.js → chunk-J5XJWCB3.js} +2 -2
  59. package/dist/{chunk-DWN7QDTV.js → chunk-JFO2UVQP.js} +2 -2
  60. package/dist/{chunk-FMC3BI4I.js → chunk-JRCJEHRG.js} +2 -2
  61. package/dist/{chunk-4XTPZ5CR.js → chunk-KMOMNTB4.js} +2 -2
  62. package/dist/{chunk-ZL5Y23AJ.js → chunk-LM72NQ7T.js} +1 -1
  63. package/dist/{chunk-4ZHJAHLE.js → chunk-LSJDKJIB.js} +2 -2
  64. package/dist/{chunk-VV5WJLRO.js → chunk-MP43RX4O.js} +1 -1
  65. package/dist/{chunk-D5OXYOJP.js → chunk-MQ2B33LQ.js} +1 -1
  66. package/dist/{chunk-MTFHE7ZO.js → chunk-MRYPDVOS.js} +2 -2
  67. package/dist/{chunk-GMZYT44R.js → chunk-NLNZK7RL.js} +5 -5
  68. package/dist/{chunk-ZXWFN7CK.js → chunk-OAM22BCR.js} +2 -2
  69. package/dist/{chunk-TOYQTO44.js → chunk-OLG2YPLS.js} +2 -2
  70. package/dist/{chunk-PBADFBRR.js → chunk-OQ6TCHBB.js} +2 -2
  71. package/dist/{chunk-3KQOIXLO.js → chunk-PCIFZHWS.js} +2 -2
  72. package/dist/{chunk-KD6TPIXM.js → chunk-PJENL245.js} +2 -2
  73. package/dist/{chunk-F334Z5UA.js → chunk-PLDIXTKR.js} +2 -2
  74. package/dist/{chunk-BOXAKNN6.js → chunk-PNESKY2Z.js} +2 -2
  75. package/dist/{chunk-QHOUNTDZ.js → chunk-PTYQQHZM.js} +2 -2
  76. package/dist/{chunk-2FAJTZSX.js → chunk-QKW7ISEW.js} +2 -2
  77. package/dist/{chunk-AWSRND4W.js → chunk-QNO3QIMN.js} +2 -2
  78. package/dist/{chunk-DV6B262O.js → chunk-SJ6XSCG7.js} +2 -2
  79. package/dist/{chunk-XPYXEEDO.js → chunk-SOS256TP.js} +2 -2
  80. package/dist/{chunk-DQIJMKNE.js → chunk-TDUU63FC.js} +2 -2
  81. package/dist/chunk-TOIS2VAI.js +4 -0
  82. package/dist/{chunk-TC3X33N6.js → chunk-TYEGFDOP.js} +2 -2
  83. package/dist/chunk-UJKZQLDB.js +2 -0
  84. package/dist/chunk-V27BEQJN.js +7 -0
  85. package/dist/{chunk-J6BR4MD6.js → chunk-VIKEPD4D.js} +2 -2
  86. package/dist/{chunk-XDSB47KO.js → chunk-WAU7HVDI.js} +2 -2
  87. package/dist/chunk-WFWQWQK6.js +3 -0
  88. package/dist/chunk-WWCZCH7W.js +3 -0
  89. package/dist/{chunk-QB5WSOTY.js → chunk-XAMVIPE2.js} +2 -2
  90. package/dist/{chunk-A45K6VUK.js → chunk-XWE7PZQH.js} +2 -2
  91. package/dist/{chunk-547VY366.js → chunk-XWJ3JYRG.js} +2 -2
  92. package/dist/{chunk-QN67MWDU.js → chunk-XYBNOILR.js} +2 -2
  93. package/dist/{chunk-IWK562KR.js → chunk-XYNWAZ6J.js} +2 -2
  94. package/dist/{chunk-UVMME4FI.js → chunk-YGBHQOB2.js} +2 -2
  95. package/dist/{chunk-ZNSLF5AC.js → chunk-YGQBJUS6.js} +2 -2
  96. package/dist/{chunk-6DHPQS72.js → chunk-YILKXTIY.js} +2 -2
  97. package/dist/{chunk-X3OOU7CF.js → chunk-Z7M7X3ZG.js} +2 -2
  98. package/dist/{chunk-G6QQCX45.js → chunk-ZJGZCBYT.js} +2 -2
  99. package/dist/cli.js +1 -1
  100. package/dist/{command-descriptors-SWFWGIFK.js → command-descriptors-QJEYYND2.js} +168 -166
  101. package/dist/direct-navigation-TT23TDBS.js +3 -0
  102. package/dist/index.js +1 -1
  103. package/dist/queries/affected.js +1 -1
  104. package/dist/queries/architecture.js +1 -1
  105. package/dist/queries/bottlenecks.js +1 -1
  106. package/dist/queries/by-kind.js +1 -1
  107. package/dist/queries/call-graph.js +1 -1
  108. package/dist/queries/change-surface.js +1 -1
  109. package/dist/queries/cleanup-plan.js +1 -1
  110. package/dist/queries/co-change.js +1 -1
  111. package/dist/queries/code.js +1 -1
  112. package/dist/queries/complexity-hotspots.js +1 -1
  113. package/dist/queries/complexity.js +1 -1
  114. package/dist/queries/convergence.js +1 -1
  115. package/dist/queries/coupling.js +1 -1
  116. package/dist/queries/cycles.js +1 -1
  117. package/dist/queries/dataflow.js +1 -1
  118. package/dist/queries/dead.js +1 -1
  119. package/dist/queries/decorative-checkers.js +1 -1
  120. package/dist/queries/deep-chains.js +1 -1
  121. package/dist/queries/deps.js +1 -1
  122. package/dist/queries/diff-gate.js +1 -1
  123. package/dist/queries/diff-impact.js +1 -1
  124. package/dist/queries/doc-drift.js +1 -1
  125. package/dist/queries/drift.js +1 -1
  126. package/dist/queries/duplicate-bodies.js +1 -1
  127. package/dist/queries/extract-candidates.js +1 -1
  128. package/dist/queries/fan.js +1 -1
  129. package/dist/queries/health.js +1 -1
  130. package/dist/queries/hierarchy.js +1 -1
  131. package/dist/queries/hotspots.js +1 -1
  132. package/dist/queries/imports.js +1 -1
  133. package/dist/queries/incomplete-migration.js +1 -1
  134. package/dist/queries/index.js +1 -1
  135. package/dist/queries/isolated.js +1 -1
  136. package/dist/queries/locality-candidates.js +1 -1
  137. package/dist/queries/members.js +1 -1
  138. package/dist/queries/methods.js +1 -1
  139. package/dist/queries/not-implemented.js +1 -1
  140. package/dist/queries/outline.js +1 -1
  141. package/dist/queries/passthrough-candidates.js +1 -1
  142. package/dist/queries/plan-context.js +1 -1
  143. package/dist/queries/react-component-duplicates.js +1 -1
  144. package/dist/queries/react-hook-candidates.js +1 -1
  145. package/dist/queries/react-large-component-pressure.js +1 -1
  146. package/dist/queries/recent-duplicates.js +1 -1
  147. package/dist/queries/redundant-reexports.js +1 -1
  148. package/dist/queries/refs.js +1 -1
  149. package/dist/queries/self-audit.js +1 -1
  150. package/dist/queries/similar-chains.js +1 -1
  151. package/dist/queries/similar-files.js +1 -1
  152. package/dist/queries/similar-signatures.js +1 -1
  153. package/dist/queries/similar.js +1 -1
  154. package/dist/queries/slice.js +1 -1
  155. package/dist/queries/stale-abstractions.js +1 -1
  156. package/dist/queries/surface.js +1 -1
  157. package/dist/queries/symbols.js +1 -1
  158. package/dist/queries/system.js +1 -1
  159. package/dist/queries/test-quality.js +1 -1
  160. package/dist/queries/trace.js +1 -1
  161. package/dist/queries/twin-ab.js +1 -1
  162. package/dist/queries/twin-drift.js +1 -1
  163. package/dist/queries/unused-imports.js +1 -1
  164. package/dist/queries/unused-params.js +1 -1
  165. package/dist/queries/vue-component-duplicates.js +1 -1
  166. package/dist/queries/vue-composable-candidates.js +1 -1
  167. package/dist/queries/vue-large-view-pressure.js +1 -1
  168. package/dist/queries/wrapper-candidates.js +1 -1
  169. package/dist/reindex-worker.js +24 -24
  170. package/dist/reindex.js +38 -38
  171. package/dist/runtime.d.ts +6 -1
  172. package/dist/runtime.js +2 -2
  173. package/dist/rust-semantic-session-server.js +1 -1
  174. package/dist/rust-semantic-session-worker.js +1 -1
  175. package/dist/rust-semantic-worker.js +1 -1
  176. package/dist/watch-server.js +5 -5
  177. package/package.json +1 -1
  178. package/dist/chunk-42QYU6FD.js +0 -3
  179. package/dist/chunk-6SHX42QQ.js +0 -6
  180. package/dist/chunk-AERYQJ52.js +0 -3
  181. package/dist/chunk-IXORBCMR.js +0 -120
  182. package/dist/chunk-NEG77KKH.js +0 -4
  183. package/dist/chunk-OYYZLJVT.js +0 -2
  184. package/dist/direct-navigation-RKMPBXMI.js +0 -3
@@ -1,49 +1,49 @@
1
1
  #!/usr/bin/env node
2
- import{c as bc,d as zr,e as Fn,f as Sc,g as vc,h as xc,j as Rc}from"./chunk-NEG77KKH.js";import{a as ot,b as v,c as qe,d as fe,e as $t,f as u,g as cc,h as P,i as $,j as oe,k as se,l as ve,m as Ut,n as yc}from"./chunk-MTFHE7ZO.js";import{$ as $n,$a as Ds,$b as Ca,$c as nc,A as Oo,Aa as ls,Ab as oa,Ac as Ne,Ad as pc,B as Sn,Bb as sa,Bd as Se,C as Fo,Ca as ds,Cb as aa,Cc as qa,Cd as mc,D as No,Da as us,Db as ca,Dc as Ba,Dd as de,E as vn,Ea as ps,Eb as la,Ec as Va,Ed as On,Fa as ms,Fb as da,Fc as Ha,Fd as fc,G as Bt,Ga as fs,Gb as Vr,Gc as Wa,Gd as L,H as Mo,Ha as gs,Hb as xt,Hc as Ga,Hd as B,I as _o,Ia as hs,Ib as In,Ic as Ua,Id as k,J as qo,Ja as ys,Jb as jn,Jc as Ja,Jd as U,K as Ae,Ka as bs,Kb as ua,Kc as za,Kd as b,L as Ue,La as Ss,Lb as pa,Lc as Ka,Ld as Ct,M as Bo,Mb as ma,Mc as Qa,Md as C,N as yt,Na as vs,Nb as fa,Nc as Ya,Nd as A,O as xn,Oa as xs,Ob as ga,Oc as En,Od as gc,P as Rn,Pa as Rs,Pb as ha,Pc as Xa,Pd as I,Q as Vo,Qa as ks,Qb as ya,Qc as Za,Qd as hc,R as Ho,Ra as ws,Rb as ba,Rc as Ln,Rd as G,S as Wo,Sa as $s,Sb as Sa,Sc as ec,T as kn,Ta as Cs,Tb as va,Tc as Hr,U as Go,Ua as Ps,Ub as xa,Uc as tc,V as bt,Va as Ts,Vb as be,Vc as Wr,W as St,Wa as Is,Wb as Ra,X as Uo,Xa as js,Xb as Gt,Xc as Y,Y as Jo,Ya as Es,Yb as ka,Z as wn,Za as Ls,Zb as wa,Zc as Me,_ as zo,_a as As,_b as $a,_c as wt,aa as Ko,ab as Wt,ac as Pa,ba as Cn,bb as Os,bc as Ta,bd as ce,c as gn,cb as Fs,cc as Ia,d as pe,da as Qo,db as Ns,dc as ja,dd as Je,e as hn,ea as Yo,eb as Ms,ed as Gr,f as q,fa as Pn,fb as _s,fc as Ea,fd as _e,g as J,ga as qr,gb as qs,gc as La,gd as ie,hb as Bs,hc as Aa,hd as M,ia as Xo,ib as Vs,id as An,ja as nt,jb as Hs,jd as j,kb as Ws,kd as Ur,lb as Gs,lc as De,ld as Jr,m as Mt,ma as Vt,mb as Us,mc as Oe,md as Pe,n as _t,na as Zo,nb as Js,nc as Rt,nd as rc,o as qt,oa as es,ob as zs,oc as Da,od as ic,p as Le,pa as ts,pb as Ks,pc as me,pd as Dn,q as Io,qa as ns,qb as Br,qc as kt,qd as oc,r as yn,ra as Ht,rb as Qs,rc as Ce,rd as sc,s as jo,sa as rs,sb as Ys,sc as Oa,sd as ac,t as _r,ta as is,tb as Xs,tc as Fa,u as Eo,ua as Tn,ub as Zs,uc as Na,ud as le,v as Lo,va as os,vb as ea,vc as rt,vd as K,w as Ao,wa as ss,wb as ta,wc as Ma,wd as lc,x as Do,xa as as,xb as na,xc as _a,xd as dc,y as bn,ya as vt,yb as ra,yc as it,yd as uc,z as Q,za as cs,zb as ia,zc as Fe,zd as ze}from"./chunk-GBB2RUDN.js";import{execFileSync as il,spawn as Ag}from"child_process";import{existsSync as dt,mkdirSync as li,readFileSync as ol,rmSync as Dg,writeFileSync as Un}from"fs";import{homedir as Og}from"os";import{dirname as Jn,isAbsolute as Fg,join as Qt,resolve as Ng}from"path";import{execFileSync as ng}from"child_process";import{existsSync as kc,readdirSync as bf}from"fs";import{isAbsolute as Sf,join as Kr,resolve as vf}from"path";var xf={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",Sf(r)?r:vf(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",wc(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",wc(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=Kr(e,"vendor","bin","scip-php"),r=Kr(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",kc(r)?r:kc(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function st(e){return xf[e]}function wc(e,t){let n;try{n=bf(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Kr(e,i);return null}import{createRequire as Rf}from"module";var kf=Rf(import.meta.url);function $c(e,t=[]){let n=wf(),r=is(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 wf(){try{return kf.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as Pt,spawnSync as $f}from"child_process";import{existsSync as xe,mkdtempSync as Ic,readFileSync as Cf,readdirSync as Pf,rmSync as jc,symlinkSync as Tf,writeFileSync as If}from"fs";import{tmpdir as Ec}from"os";import{join as ae}from"path";var jf=3e5,Ef=12;function Xr(e,t,n={}){let r=Zr(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],dirtyWorkingTree:Qr(e),batches:[]};let i=Of(t,r),o=n.timeoutMs??jf,s=qf(e,t),a=Qr(e),c=Ic(ae(Ec(),"scip-cleanup-verify-")),l=[],d=new Map;try{Pt("git",["-C",e,"worktree","add","--detach","--force",c,"HEAD"],{stdio:"ignore"}),Bf(e,c);for(let p of r)d.set(p.label,Pc(p,c,o).rawErrors);for(let p of t.batches){Ac(c,p);let m=null;for(let f of r){let g=Pc(f,c,o),h=Lf(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,Ef)};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{jc(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 Lf(e,t,n){let r=Af(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 Af(e,t){let n=Df(e),r=new Map,i=[];for(let o of t){let s=Lc(o),a=(r.get(s)??0)+1;r.set(s,a),a>(n.get(s)??0)&&i.push(o)}return i}function Df(e){let t=new Map;for(let n of e){let r=Lc(n);t.set(r,(t.get(r)??0)+1)}return t}function Of(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 Lc(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var Cc=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],Ff=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function Zr(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:Cc,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:Cc,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=Nf();n&&t.push(n)}if(Ff.some(n=>xe(ae(e,n)))){let n=Mf(e);n&&t.push(n)}for(let n of _f(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 Nf(){return Ae("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"}:Ae("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function Mf(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:[...hn],strength:"reference-aware"}:Ae("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...hn],strength:"reference-aware"}:Ae("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...hn],strength:"reference-aware"}:null}function _f(e){let t=[];if(xe(ae(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=Pf(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 qf(e,t){let n=new Set(Qr(e));return[...new Set(t.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>n.has(i)).sort()}function Qr(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 Bf(e,t){for(let n of["node_modules"]){let r=ae(e,n),i=ae(t,n);if(xe(r)&&!xe(i))try{Tf(r,i,"junction")}catch{}}}function Ac(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)&&If(o,Vf(Cf(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function ei(e,t){for(let n of t)Ac(e,n)}function Dc(e,t){let n=Ic(ae(Ec(),"scip-cleanup-patch-"));try{return Pt("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),ei(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{jc(n,{recursive:!0,force:!0})}}}function ti(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 ni(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 Vf(e,t,n={}){let r=e.split(`
4
- `),i=(n.rust===!0?Hf(e):Io(e)).split(`
5
- `),o=new Set;for(let s of t){let a=Wf(r,s.start),c=Uf(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
- `)}function Hf(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 Wf(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 Gf=200;function Uf(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>Gf)break}return n}function Pc(e,t,n){let r=$f(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:Tc(i)};let o=Jf(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(tg),diagnostics:s,parseBasis:o.parseBasis,outputTail:Tc(i)}}function Jf(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:zf(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:Kf(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=Qf(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:Yf(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:Xf(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:Zf(t),parseBasis:"clj-kondo-json"}:{diagnostics:eg(t),parseBasis:"heuristic"}}function zf(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 Kf(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 Qf(e){let t=Oc(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 Yf(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 Xf(e){let t=[];for(let n of e.split(`
8
- `)){if(!n.trim().startsWith("{"))continue;let r=Yr(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 Zf(e){let t=Oc(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 eg(e){return e.split(`
9
- `).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function tg(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 Oc(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return Yr(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(r=>r>=0));return Number.isFinite(n)?Yr(t.slice(n)):null}function Yr(e){try{return JSON.parse(e)}catch{return null}}function Tc(e,t=10){return e.split(`
10
- `).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var Mc={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"]},rg={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"},ig={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=kn(st(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),i=pg(e,n,t),o=ri({semantics:i},"typescript"),s=Zr(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:r,semantics:i,semantic:o,checkers:s,gitAvailable:gg(e)}}function Ke(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=>lg(e,c,{hasIndexedGraph:dg(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.`},...og(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 og(e){return sg(e).map(t=>{let n=ri(e,t),r=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${ag(t)} semantic provider`,status:r,evidence:"semantic",reason:cg(t,n)}})}function sg(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of qc(e))t.add(n.language);return[...t].sort((n,r)=>Fc(n)-Fc(r))}function Fc(e){return e==="typescript"?0:1}function ag(e){return e==="typescript"?"TypeScript":"Rust"}function cg(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 lg(e,t,n){let r=e.indexers.find(d=>d.language===t),i=r?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=i!=="unavailable",s=ug(t,n.runtimeProbe),a=mg(e,t),c=fg(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 ${Mc[t].join(", ")} files.`}}}function dg(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function ug(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)??Nc(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=_c(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)??Nc(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 Nc(e){let t=rg[e];return t?yn(t):_c(e)==="regex-only"?"regex":"unavailable"}function _c(e){let t=ig[e],n=t?Do(t):null;return n?.imports??n?.exports??n?.reExports??null}function pg(e,t,n){let r=[];return t.includes("typescript")&&r.push({language:"typescript",...$c(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")&&r.push({language:"rust",...Go(e)}),r}function qc(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function ri(e,t){return qc(e).find(n=>n.language===t)}function mg(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=ri(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 fg(e,t){let n=new Set(Mc[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function gg(e){try{return ng("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as hg,existsSync as Tt,readFileSync as It,rmSync as Hc,writeFileSync as oi}from"fs";import{join as ct}from"path";var at="<!-- scip-query:agent-setup:begin -->",Nn="<!-- scip-query:agent-setup:end -->",ii="# scip-query:agent-setup";function Jt(){if(process.stdin.isTTY)return"";try{return It(0,"utf-8")}catch{return""}}function Mn(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 _n(e,t={}){let n={written:[],unchanged:[],skipped:[]};return yg(e,n),t.gitHook&&bg(e,n),n}function Wc(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Vc(e,"AGENTS.md",t,n),Vc(e,"CLAUDE.md",t,n),Sg(e,t,n),n}function yg(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.",Nn].join(`
12
- `);Bc(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",Nn].join(`
13
- `);Bc(e,"CLAUDE.md",i,t)}function Bc(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]*?${Nn}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
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(`
4
+ `),i=(n.rust===!0?tg(e):Do(e)).split(`
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
+ `)}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(`
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
+ `);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
 
15
15
  `)}${n}
16
16
  `:`${n}
17
- `;s===o?r.unchanged.push(t):(oi(i,s),r.written.push(t))}function Vc(e,t,n,r){let i=ct(e,t);if(!Tt(i)){r.unchanged.push(t);return}let o=It(i,"utf-8");if(!o.includes(at)){r.unchanged.push(t);return}let s=new RegExp(`${at}[\\s\\S]*?${Nn}`),a=o.replace(s,"").replace(/\n{3,}/g,`
17
+ `;s===o?r.unchanged.push(t):(ai(i,s),r.written.push(t))}function Jc(e,t,n,r){let i=ct(e,t);if(!Tt(i)){r.unchanged.push(t);return}let o=It(i,"utf-8");if(!o.includes(at)){r.unchanged.push(t);return}let s=new RegExp(`${at}[\\s\\S]*?${Mn}`),a=o.replace(s,"").replace(/\n{3,}/g,`
18
18
 
19
- `).trim();r.removed.push(t),!n.dryRun&&(a.length===0?Hc(i,{force:!0}):oi(i,`${a}
20
- `))}function bg(e,t){let n=ct(e,".git","hooks");if(!Tt(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let r=ct(n,"pre-commit"),i=["#!/bin/sh",ii,"scip-query diff-gate || {",' echo "scip-query diff-gate failed \u2014 fix findings or commit with --no-verify to knowingly accept." >&2'," exit 1","}",""].join(`
21
- `);if(Tt(r)){let o=It(r,"utf-8");if(o.includes(ii)){if(o===i){t.unchanged.push(".git/hooks/pre-commit");return}}else{t.skipped.push({target:".git/hooks/pre-commit",reason:"a pre-commit hook already exists \u2014 add `scip-query diff-gate` to it manually"});return}}oi(r,i),hg(r,493),t.written.push(".git/hooks/pre-commit")}function Sg(e,t,n){let r=ct(e,".git","hooks","pre-commit");if(!Tt(r)){n.unchanged.push(".git/hooks/pre-commit");return}if(!It(r,"utf-8").includes(ii)){n.skipped.push({target:".git/hooks/pre-commit",reason:"pre-commit hook is not managed by scip-query"});return}n.removed.push(".git/hooks/pre-commit"),t.dryRun||Hc(r,{force:!0})}import{createHash as vg}from"crypto";import{existsSync as Bn,mkdirSync as xg,readFileSync as Vn,readdirSync as Rg,rmSync as Gc,writeFileSync as Uc}from"fs";import{join as Be}from"path";var Hn=Be(".scipquery","events"),kg=Be(".scipquery","ledger"),Jc="events.jsonl";function zc(e){return Be(e,kg)}function si(e){return Be(zc(e),Jc)}function Kc(e,t){let n=si(e),r=Bn(n),i=[...r?Qc(n):[],...t];if(i.length>0){let o=Be(e,Hn);xg(o,{recursive:!0});for(let s of i)wg(o,s)}r&&$g(e)}function wg(e,t){let n=`${JSON.stringify({ts:t.ts,check:t.check,findingId:t.findingId,event:t.event,commit:t.commit,...t.comparisonBaseCommit?{comparisonBaseCommit:t.comparisonBaseCommit}:{},...t.verifiedAgainstCommit?{verifiedAgainstCommit:t.verifiedAgainstCommit}:{},...t.symbol?{symbol:t.symbol}:{}},null,2)}
22
- `,r=vg("sha256").update(n).digest("hex").slice(0,16).toUpperCase(),i=Be(e,`${t.ts}-${r}.json`);try{Uc(i,n,{flag:"wx"})}catch(o){if(o.code!=="EEXIST")throw o;if(Vn(i,"utf-8")!==n)throw new Error(`outcome event filename collision: ${i}`,{cause:o})}}function $g(e){Gc(si(e));let t=Be(zc(e),".gitattributes");if(!Bn(t))return;let n=Vn(t,"utf-8").split(`
23
- `).filter(r=>r.trim()!==`${Jc} merge=union`).join(`
24
- `).replace(/^\n+|\n+$/g,"");n===""?Gc(t):Uc(t,`${n}
25
- `)}function Wn(e){let t=[],n=Be(e,Hn);if(Bn(n))for(let i of Rg(n).sort()){if(!i.endsWith(".json"))continue;let o=Yc(Vn(Be(n,i),"utf-8"));o&&t.push(o)}let r=si(e);return Bn(r)&&t.push(...Qc(r)),Cg(t)}function Qc(e){let t=[];for(let n of Vn(e,"utf-8").split(`
26
- `)){let r=Yc(n);r&&t.push(r)}return t}function Yc(e){if(e.trim()==="")return null;let t;try{t=JSON.parse(e)}catch{return null}return Tg(t)?t:null}function Cg(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 Pg=["caught","resolved","suppressed","reopened"];function Tg(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"&&Pg.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 Gn(e,t,n={}){let r=(n.now??Date.now)(),i=Eg(t),o=$a(e),s=e.config.projectRoot,a=n.headCommit?n.headCommit(s):nt(s)?.headCommit??null,c=n.resolveCommit?n.resolveCommit(s,t.base):jg(s,t.base),l=Ig({previous:o,observed:i,result:t,projectRoot:s,commit:a,comparisonBaseCommit:c,runtime:n}),d=Ca(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=Ra(o,d,p,a,r,{...c?{comparisonBaseCommit:c}:{},verifiedAgainstByFinding:l.verifiedAgainstByFinding});return(n.appendEvents??Kc)(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 Ig(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&&!In(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??Wn)(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)??[]),x=S?.comparisonBaseCommit??S?.commit;if(lt(`candidate ${y} anchor=${String(x)} current=${String(e.comparisonBaseCommit)}`),!S?.comparisonBaseCommit&&S?.commit&&S.commit===e.commit){n.add(h.check);continue}if(!x||!e.commit||!e.comparisonBaseCommit){r.add(y);continue}if(x===e.comparisonBaseCommit){n.add(h.check);continue}let w=m.get(x)??[];w.push(h),m.set(x,w)}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 x=new Set(S.checksRun),w=Lg(S);for(let R of y){let D=be(R.check,R.findingId);if(!x.has(R.check)){r.add(D);continue}n.add(R.check);let _=w.find(O=>O.key===D);if(_){lt(`replay retained exact ${D}`),t.push(_.observed),_.symbol&&o.set(_.observed.findingId,_.symbol);continue}let z=Gt(p.get(D)??[]),T=z?.symbol?w.find(O=>O.check===R.check&&O.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 jg(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 Eg(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 Lg(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 sl="SCIP_QUERY_SKIP_HOOK_INSTALL",ai="SCIP_QUERY_STOP_HOOK_MODE",Mg="scip-query hook-",_g="scip-query diff-gate --hook",Xc="# scip-query:local-hooks:begin",Zc="# 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 jt(e,t={}){let n=al(),r=t.env??process.env;if(Hg(r))return n.skipped.push({target:"project agent hooks",reason:`${sl}=1`}),n;let i=Qg(e);return t.shared&&n.warnings.push("--shared is deprecated; project hooks are always checkout-local and will not be committed."),Bg(e,n,t.dryRun),t.remove?(tl(e,Kt[0],n,{dryRun:t.dryRun}),tl(e,Kt[1],n,{writeDeclinedTombstone:!0,dryRun:t.dryRun}),n):(el(e,Kt[0],n,{provider:"codex",commandPrefix:i,force:t.force}),el(e,Kt[1],n,{provider:"claude",commandPrefix:i,force:t.force}),t.removeLegacyUserHooks!==!1&&qg({homeDir:t.homeDir,result:n}),n)}function qg(e={}){let t=e.result??al(),n=e.homeDir??Og();return ci({configPath:Qt(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),ci({configPath:Qt(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function al(){return{installed:[],updated:[],unchanged:[],removed:[],gitExcluded:[],warnings:[],skipped:[]}}function el(e,t,n,r){if(di(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);Gg({provider:r.provider,rootDir:Jn(i),configPath:i,label:t.label,createRoot:!0,commandPrefix:r.commandPrefix,force:r.force,result:n})}function tl(e,t,n,r){if(di(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook removal will not modify it"});return}Ug({configPath:Qt(e,t.relativePath),label:t.label,result:n,writeDeclinedTombstone:r.writeDeclinedTombstone,dryRun:r.dryRun})}function Bg(e,t,n=!1){let r=Vg(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=>!di(e,d.relativePath));if(i.length===0)return;let o=[Xc,...i.map(d=>`/${d.relativePath}`),Zc].join(`
27
- `),s=dt(r)?ol(r,"utf-8"):"",a=new RegExp(`${Le(Xc)}[\\s\\S]*?${Le(Zc)}\\n?`,"g"),c=s.replace(a,"").replace(/\n*$/,""),l=`${c}${c?`
19
+ `).trim();r.removed.push(t),!n.dryRun&&(a.length===0?zc(i,{force:!0}):ai(i,`${a}
20
+ `))}function Eg(e,t){let n=ct(e,".git","hooks");if(!Tt(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let r=ct(n,"pre-commit"),i=["#!/bin/sh",si,"scip-query diff-gate || {",' echo "scip-query diff-gate failed \u2014 fix findings or commit with --no-verify to knowingly accept." >&2'," exit 1","}",""].join(`
21
+ `);if(Tt(r)){let o=It(r,"utf-8");if(o.includes(si)){if(o===i){t.unchanged.push(".git/hooks/pre-commit");return}}else{t.skipped.push({target:".git/hooks/pre-commit",reason:"a pre-commit hook already exists \u2014 add `scip-query diff-gate` to it manually"});return}}ai(r,i),Tg(r,493),t.written.push(".git/hooks/pre-commit")}function jg(e,t,n){let r=ct(e,".git","hooks","pre-commit");if(!Tt(r)){n.unchanged.push(".git/hooks/pre-commit");return}if(!It(r,"utf-8").includes(si)){n.skipped.push({target:".git/hooks/pre-commit",reason:"pre-commit hook is not managed by scip-query"});return}n.removed.push(".git/hooks/pre-commit"),t.dryRun||zc(r,{force:!0})}import{createHash as Ag}from"crypto";import{existsSync as Vn,mkdirSync as Lg,readFileSync as Hn,readdirSync as Dg,rmSync as Qc,writeFileSync as Yc}from"fs";import{join as Ve}from"path";var Wn=Ve(".scipquery","events"),Fg=Ve(".scipquery","ledger"),Xc="events.jsonl";function Zc(e){return Ve(e,Fg)}function ci(e){return Ve(Zc(e),Xc)}function el(e,t){let n=ci(e),r=Vn(n),i=[...r?tl(n):[],...t];if(i.length>0){let o=Ve(e,Wn);Lg(o,{recursive:!0});for(let s of i)Og(o,s)}r&&Ng(e)}function Og(e,t){let n=`${JSON.stringify({ts:t.ts,check:t.check,findingId:t.findingId,event:t.event,commit:t.commit,...t.comparisonBaseCommit?{comparisonBaseCommit:t.comparisonBaseCommit}:{},...t.verifiedAgainstCommit?{verifiedAgainstCommit:t.verifiedAgainstCommit}:{},...t.symbol?{symbol:t.symbol}:{}},null,2)}
22
+ `,r=Ag("sha256").update(n).digest("hex").slice(0,16).toUpperCase(),i=Ve(e,`${t.ts}-${r}.json`);try{Yc(i,n,{flag:"wx"})}catch(o){if(o.code!=="EEXIST")throw o;if(Hn(i,"utf-8")!==n)throw new Error(`outcome event filename collision: ${i}`,{cause:o})}}function Ng(e){Qc(ci(e));let t=Ve(Zc(e),".gitattributes");if(!Vn(t))return;let n=Hn(t,"utf-8").split(`
23
+ `).filter(r=>r.trim()!==`${Xc} merge=union`).join(`
24
+ `).replace(/^\n+|\n+$/g,"");n===""?Qc(t):Yc(t,`${n}
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(`
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}
30
- `;!n&&l!==s&&(li(Jn(r),{recursive:!0}),Un(r,l)),t.gitExcluded.push(...i.map(d=>d.label))}function Vg(e){try{let t=il("git",["-C",e,"rev-parse","--git-path","info/exclude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();return t?Fg(t)?t:Ng(e,t):null}catch{return null}}function di(e,t){try{return il("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore"}),!0}catch{return!1}}function Hg(e=process.env){let t=e[sl];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function Wg(e=process.env){let t=e[ai]?.toLowerCase();return t==="block"||t==="blocking"?"block":t==="warn"?"warn":"feedback"}function Gg(e){if(!e.createRoot&&!dt(e.rootDir))return;let t=ui(e.configPath,e.label,e.result);if(!t)return;if(t.scipQueryHooks==="declined"&&!e.force){e.result.skipped.push({target:e.label,reason:"scip-query hooks were previously removed; rerun with --force"});return}let n=Jg(t,e.provider,e.commandPrefix);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let r=dt(e.configPath);li(Jn(e.configPath),{recursive:!0}),Un(e.configPath,`${JSON.stringify(n,null,2)}
31
- `),e.result[r?"updated":"installed"].push(e.label)}function ci(e){if(!dt(e.configPath))return;let t=ui(e.configPath,e.label,e.result);if(!t)return;let n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:{},r={...n},i=!1;for(let s of["SessionStart","UserPromptSubmit","Stop"]){let a=Array.isArray(n[s])?n[s]:[],c=cl(a);(c.length!==a.length||JSON.stringify(c)!==JSON.stringify(a))&&(i=!0,c.length>0?r[s]=c:delete r[s])}if(!i)return;let o={...t};Object.keys(r).length>0?o.hooks=r:delete o.hooks,e.dryRun||(Object.keys(o).length===0?Dg(e.configPath,{force:!0}):Un(e.configPath,`${JSON.stringify(o,null,2)}
32
- `)),e.result.removed.push(e.label)}function Ug(e){let t=e.result.removed.length;if(ci(e),!e.writeDeclinedTombstone)return;let n=ui(e.configPath,e.label,e.result);if(!n)return;let r={...n,scipQueryHooks:"declined"};e.dryRun||(li(Jn(e.configPath),{recursive:!0}),Un(e.configPath,`${JSON.stringify(r,null,2)}
33
- `)),e.result.removed.length===t&&e.result.removed.push(`${e.label} (declined)`)}function ui(e,t,n){if(!dt(e))return{};try{let r=JSON.parse(ol(e,"utf-8"));if(!r||typeof r!="object"||Array.isArray(r)){n.skipped.push({target:t,reason:"existing hook config is not a JSON object"});return}return r}catch(r){n.skipped.push({target:t,reason:`could not parse existing hook config: ${r instanceof Error?r.message:String(r)}`});return}}function Jg(e,t,n="scip-query"){let r=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},i={...e,hooks:{...r}};i.scipQueryHooks==="declined"&&delete i.scipQueryHooks;for(let o of["SessionStart","UserPromptSubmit","Stop"]){let s=Array.isArray(r[o])?r[o]:[];i.hooks[o]=[...cl(s),Kg(t,o,n)]}return i}function cl(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!zg(n)):[]})).filter(t=>t.hooks.length>0)}function zg(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(Mg)||t===_g)}function Kg(e,t,n){return t==="SessionStart"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:60,statusMessage:"Refreshing scip-query context"}]}:t==="UserPromptSubmit"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:60,statusMessage:"Checking scip-query freshness"}]}:{hooks:[{type:"command",command:`${n} hook-stop`,timeout:30,statusMessage:"Running scip-query diff gate"}]}}function Qg(e){let t=Qt(e,"node_modules",".bin","scip-query");return dt(t)?t:"scip-query"}async function ll(){let e=await eh(Jt());e&&console.log(JSON.stringify(e))}function Yg(e){if(Mn(e))return;let t=ul(e),n=pl(t);if(!(!n||!dt(n.paths.dbPath)))return lh(n,r=>{let i={minTogether:6,skip:[]},o=xt(r,i),s=Gn(r,o,{replayGate:a=>xt(r,{...i,base:a})});return s.warning&&console.error(`note: ${s.warning}`),o})}function dl(){let e=Yg(Jt());!e||e.findings.length===0||console.log(JSON.stringify(Xg(e,Wg())))}function Xg(e,t="feedback"){let n=zt(e),r=Zg(e);return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${r}
30
+ `;!n&&l!==s&&(ui(zn(r),{recursive:!0}),Jn(r,l)),t.gitExcluded.push(...i.map(d=>d.label))}function eh(e){try{let t=ll("git",["-C",e,"rev-parse","--git-path","info/exclude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();return t?zg(t)?t:Kg(e,t):null}catch{return null}}function pi(e,t){try{return ll("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore"}),!0}catch{return!1}}function th(e=process.env){let t=e[ul];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function nh(e=process.env){let t=e[li]?.toLowerCase();return t==="block"||t==="blocking"?"block":t==="warn"?"warn":"feedback"}function rh(e){if(!e.createRoot&&!dt(e.rootDir))return;let t=mi(e.configPath,e.label,e.result);if(!t)return;if(t.scipQueryHooks==="declined"&&!e.force){e.result.skipped.push({target:e.label,reason:"scip-query hooks were previously removed; rerun with --force"});return}let n=oh(t,e.provider,e.commandPrefix);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let r=dt(e.configPath);ui(zn(e.configPath),{recursive:!0}),Jn(e.configPath,`${JSON.stringify(n,null,2)}
31
+ `),e.result[r?"updated":"installed"].push(e.label)}function di(e){if(!dt(e.configPath))return;let t=mi(e.configPath,e.label,e.result);if(!t)return;let n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:{},r={...n},i=!1;for(let s of["SessionStart","UserPromptSubmit","Stop"]){let a=Array.isArray(n[s])?n[s]:[],c=ml(a);(c.length!==a.length||JSON.stringify(c)!==JSON.stringify(a))&&(i=!0,c.length>0?r[s]=c:delete r[s])}if(!i)return;let o={...t};Object.keys(r).length>0?o.hooks=r:delete o.hooks,e.dryRun||(Object.keys(o).length===0?Ug(e.configPath,{force:!0}):Jn(e.configPath,`${JSON.stringify(o,null,2)}
32
+ `)),e.result.removed.push(e.label)}function ih(e){let t=e.result.removed.length;if(di(e),!e.writeDeclinedTombstone)return;let n=mi(e.configPath,e.label,e.result);if(!n)return;let r={...n,scipQueryHooks:"declined"};e.dryRun||(ui(zn(e.configPath),{recursive:!0}),Jn(e.configPath,`${JSON.stringify(r,null,2)}
33
+ `)),e.result.removed.length===t&&e.result.removed.push(`${e.label} (declined)`)}function mi(e,t,n){if(!dt(e))return{};try{let r=JSON.parse(dl(e,"utf-8"));if(!r||typeof r!="object"||Array.isArray(r)){n.skipped.push({target:t,reason:"existing hook config is not a JSON object"});return}return r}catch(r){n.skipped.push({target:t,reason:`could not parse existing hook config: ${r instanceof Error?r.message:String(r)}`});return}}function oh(e,t,n="scip-query"){let r=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},i={...e,hooks:{...r}};i.scipQueryHooks==="declined"&&delete i.scipQueryHooks;for(let o of["SessionStart","UserPromptSubmit","Stop"]){let s=Array.isArray(r[o])?r[o]:[];i.hooks[o]=[...ml(s),ah(t,o,n)]}return i}function ml(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!sh(n)):[]})).filter(t=>t.hooks.length>0)}function sh(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(Qg)||t===Yg)}function ah(e,t,n){return t==="SessionStart"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:60,statusMessage:"Refreshing scip-query context"}]}:t==="UserPromptSubmit"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:60,statusMessage:"Checking scip-query freshness"}]}:{hooks:[{type:"command",command:`${n} hook-stop`,timeout:30,statusMessage:"Running scip-query diff gate"}]}}function ch(e){let t=Qt(e,"node_modules",".bin","scip-query");return dt(t)?t:"scip-query"}async function fl(){let e=await ph(Jt());e&&console.log(JSON.stringify(e))}function lh(e){if(_n(e))return;let t=hl(e),n=yl(t);if(!(!n||!dt(n.paths.dbPath)))return xh(n,r=>{let i={minTogether:6,skip:[]},o=xt(r,i),s=Un(r,o,{replayGate:a=>xt(r,{...i,base:a})});return s.warning&&console.error(`note: ${s.warning}`),o})}function gl(){let e=lh(Jt());!e||e.findings.length===0||console.log(JSON.stringify(dh(e,nh())))}function dh(e,t="feedback"){let n=zt(e),r=uh(e);return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${r}
34
34
 
35
35
  This is non-error Stop hook feedback. Fix true findings, or explain why a finding is intentionally accepted before finishing.`}}:{systemMessage:`${r}
36
36
 
37
- Stop hook allowed this turn to finish. Review these findings when relevant. Set ${ai}=feedback to ask the agent to continue without a hook error, or ${ai}=block to enforce the gate.`}}function Zg(e){return zt(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}async function eh(e){let t=ul(e),n=ch(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit")return;let r=pl(t);if(!r)return;let i=await nh(r,n),o=n==="SessionStart"?ih(r.projectRoot,r.config,r.paths):oh(String(t.prompt??""),r.config),s=[i,o].filter(a=>!!a?.trim()).join(`
38
- `);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}var th={prepare:nc,ensureService:bc,freshness:Fe,requestRefresh:vc,startOneShot(e){Ag("scip-query",["reindex","--allow-partial"],{cwd:e,detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_AUTO_INSTALL:"1"}}).unref()}};async function nh(e,t,n=th){let r=Ce(e.config);if(r.autoRefresh===!1)return;n.prepare?.(e.projectRoot,e.config,e.paths);let i=n.freshness(e.projectRoot,e.config,e.paths);if(r.enabled){let o=n.ensureService({commandName:`agent-${t}`,projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:Ne,config:e.config});return o.kind==="failed"?`scip-query watch service did not start: ${o.message}. Run 'scip-query watch --daemon' to repair it.`:o.kind==="skipped"?i.state==="fresh"?void 0:`scip-query index is ${i.state}; automatic watch service wake was skipped (${o.reason}).`:(rh(o,i.state,e.paths.cacheDir,n),i.state!=="fresh"?`scip-query index is ${i.state}; ${o.kind==="started"?"started":"woke"} the watch service and requested refresh.`:o.kind==="started"?"scip-query watch service started for this project.":void 0)}if(i.state!=="fresh"){if(t==="UserPromptSubmit")return`scip-query index is ${i.state}; evidence commands will note staleness. Run 'scip-query reindex' to refresh.`;try{return n.startOneShot(e.projectRoot),`scip-query index is ${i.state}; started background refresh with auto-install disabled.`}catch(o){let s=o instanceof Error?o.message:String(o);return`scip-query auto-refresh skipped: index is ${i.state}, but background refresh failed to start: ${s}`}}}function rh(e,t,n,r){t==="fresh"||e.kind==="started"||e.state.watcher.state!=="idle"||r.requestRefresh(Pn(n).activityPath,`agent hook observed ${t} index while service was idle`)}function ih(e,t,n){let r=Fe(e,t,n),i=ge(e,t),s=Ke(i).capabilities.filter(c=>c.status!=="available").map(c=>c.label),a=i.languages.length>0?i.languages.join(", "):"none detected";return[`scip-query is available in this repository. Index state: ${r.state} (${r.reason})`,r.lastRefresh?`Last refresh: ${r.lastRefresh.result} by ${r.lastRefresh.trigger.kind} at ${r.lastRefresh.completedAt}.`:void 0,`Detected languages: ${a}.`,s.length>0?`Unavailable or partial capabilities: ${s.join(", ")}.`:"Core capabilities are available.","Use the scip-query router skill when exploring, planning, verifying, debugging, diagramming, or cleaning up code.","For non-trivial edits, plan with scip-concrete-plan anchored by `scip-query plan-context <target>`, then verify with scip-verify."].filter(c=>c!==void 0).join(`
39
- `)}function oh(e,t={},n=process.env){if(ah(t,n)==="off")return"";let r=sh(e);return r?`scip-query routing reminder:
40
- ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup","adopt","install","bootstrap"],message:"Setup request: use scip-setup; keep CI setup out of the default path."},{id:"debug",skillNames:["scip-debug","scip-triage-issue"],keywords:["debug","bug","regression","failing","fails","error","wrong"],message:"Debug or bug request: use scip-debug. For issue-quality triage, use scip-triage-issue."},{id:"review",skillNames:["scip-maintainability","scip-api-impact","scip-verify"],keywords:["review","maintainability","architecture","boundary"],message:"Review request: use scip-maintainability, scip-api-impact, or scip-verify depending on whether this is architecture, API impact, or post-change verification."},{id:"implementation",skillNames:["scip-concrete-plan","scip-verify"],keywords:["implement","build","change","refactor","fix","add","update"],message:"Implementation request: plan first with scip-concrete-plan and `scip-query plan-context <target>`, then verify with scip-verify."},{id:"exploration",skillNames:["scip-explore"],keywords:["explain","how does","walk me through","trace","understand"],message:"Exploration request: use scip-explore before answering behavioral questions."},{id:"diagram",skillNames:["scip-diagram"],keywords:["diagram","visualize","visualise","flow map","architecture map"],message:"Diagram request: use scip-diagram and back every node and edge with scip-query evidence."},{id:"health",skillNames:["scip-cleanup-audit","scip-cleanup-improve"],keywords:["health","score","dossier","cleanup","dead code","duplicate","debloat","as high as","maximize","maximise"],message:"Health or cleanup request: use scip-cleanup-audit before editing; use scip-cleanup-improve when the user wants confirmed issues fixed autonomously."}];function sh(e){let t=nl.find(i=>i.skillNames.some(o=>rl(e,o)));if(t)return t;let n=0,r=[];for(let i of nl){let o=i.keywords.filter(s=>rl(e,s)).length;n+=o,o>0&&r.push(i)}return n<2||r.length===0?null:r[0]}function ah(e,t){return t.SCIP_QUERY_ROUTER==="off"?"off":e.hooks?.router??"single"}function rl(e,t){let n=t.trim().split(/\s+/).map(r=>Le(r)).join("\\s+");return new RegExp(`(?<![A-Za-z0-9_-])${n}(?![A-Za-z0-9_-])`,"i").test(e)}function ul(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function ch(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function pl(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=Xo(t);if(n)try{let r=me(n),i=De(n,r);return{projectRoot:n,config:r,paths:i}}catch{return}}function lh(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,sharedEvidenceDbPath:Za(e.projectRoot,e.config),entryRoots:e.config.entryRoots,semantic:e.config.semantic,suppressions:e.config.suppressions,declaredCouplings:e.config.declaredCouplings,locality:e.config.locality,architecture:e.config.architecture,coverageContracts:e.config.coverageContracts,docs:e.config.docs},r=new Oe(n,Rt(e.projectRoot));try{return t(r)}finally{r.close()}}import{existsSync as Kn,mkdirSync as gh,symlinkSync as hh,readlinkSync as fi,unlinkSync as gi,readdirSync as bl}from"fs";import{join as Te,dirname as Zt,resolve as Qe,relative as yh,isAbsolute as bh}from"path";import{homedir as Qn,platform as Sh}from"os";import{fileURLToPath as Sl}from"url";import{execFileSync as ml}from"child_process";import{createRequire as dh}from"module";import{existsSync as uh}from"fs";import{platform as Yt,arch as fl}from"os";var gl="v0.8.1",pi="https://github.com/sourcegraph/scip",hl="SCIP_QUERY_SCIP_BIN";function ph(e){if(e.isOnPath("scip"))return{source:"path",path:"scip"};let t=e.env[hl];if(t&&e.fileExists(t))return{source:"env",path:t};if(e.platform==="win32"){let n=e.resolveSidecar(e.arch);if(n&&e.fileExists(n))return{source:"sidecar",path:n}}return null}function mh(e){let t=dh(import.meta.url);for(let n of e==="arm64"?["arm64","x64"]:[e])try{return t.resolve(`scip-query-scip-windows/scip-win32-${n}.exe`)}catch{}return null}function zn(e=process.env){return ph({platform:Yt(),arch:fl(),env:e,isOnPath:Ue,fileExists:uh,resolveSidecar:mh})?.path??null}function Xt(){return zn()!==null}function fh(){let e=Yt(),t=fl(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let o=`scip-${n}-${r}.${i}`;return{url:`${pi}/releases/download/${gl}/${o}`,filename:o}}function mi(){let e=fh();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Yt()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
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 ${hl} to a local scip.exe path.
37
+ Stop hook allowed this turn to finish. Review these findings when relevant. Set ${li}=feedback to ask the agent to continue without a hook error, or ${li}=block to enforce the gate.`}}function uh(e){return zt(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}async function ph(e){let t=hl(e),n=vh(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit")return;let r=yl(t);if(!r)return;let i=await fh(r,n),o=n==="SessionStart"?hh(r.projectRoot,r.config,r.paths):yh(String(t.prompt??""),r.config),s=[i,o].filter(a=>!!a?.trim()).join(`
38
+ `);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}var mh={prepare:ac,ensureService:kc,freshness:Pe,requestRefresh:$c,startOneShot(e){Gg("scip-query",["reindex","--allow-partial"],{cwd:e,detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_AUTO_INSTALL:"1"}}).unref()}};async function fh(e,t,n=mh){let r=Ce(e.config);if(r.autoRefresh===!1)return;n.prepare?.(e.projectRoot,e.config,e.paths);let i=n.freshness(e.projectRoot,e.config,e.paths);if(r.enabled){let o=n.ensureService({commandName:`agent-${t}`,projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:Ne,config:e.config});return o.kind==="failed"?`scip-query watch service did not start: ${o.message}. Run 'scip-query watch --daemon' to repair it.`:o.kind==="skipped"?i.state==="fresh"?void 0:`scip-query index is ${i.state}; automatic watch service wake was skipped (${o.reason}).`:(gh(o,i.state,e.paths.cacheDir,n),i.state!=="fresh"?`scip-query index is ${i.state}; ${o.kind==="started"?"started":"woke"} the watch service and requested refresh.`:o.kind==="started"?"scip-query watch service started for this project.":void 0)}if(i.state!=="fresh"){if(t==="UserPromptSubmit")return`scip-query index is ${i.state}; evidence commands will note staleness. Run 'scip-query reindex' to refresh.`;try{return n.startOneShot(e.projectRoot),`scip-query index is ${i.state}; started background refresh with auto-install disabled.`}catch(o){let s=o instanceof Error?o.message:String(o);return`scip-query auto-refresh skipped: index is ${i.state}, but background refresh failed to start: ${s}`}}}function gh(e,t,n,r){t==="fresh"||e.kind==="started"||e.state.watcher.state!=="idle"||r.requestRefresh(Tn(n).activityPath,`agent hook observed ${t} index while service was idle`)}function hh(e,t,n){let r=Pe(e,t,n),i=ge(e,t),s=Qe(i).capabilities.filter(c=>c.status!=="available").map(c=>c.label),a=i.languages.length>0?i.languages.join(", "):"none detected";return[`scip-query is available in this repository. Index state: ${r.state} (${r.reason})`,r.lastRefresh?`Last refresh: ${r.lastRefresh.result} by ${r.lastRefresh.trigger.kind} at ${r.lastRefresh.completedAt}.`:void 0,`Detected languages: ${a}.`,s.length>0?`Unavailable or partial capabilities: ${s.join(", ")}.`:"Core capabilities are available.","Use the scip-query router skill when exploring, planning, verifying, debugging, diagramming, or cleaning up code.","For non-trivial edits, plan with scip-concrete-plan anchored by `scip-query plan-context <target>`, then verify with scip-verify."].filter(c=>c!==void 0).join(`
39
+ `)}function yh(e,t={},n=process.env){if(Sh(t,n)==="off")return"";let r=bh(e);return r?`scip-query routing reminder:
40
+ ${r.message}`:""}var al=[{id:"setup",skillNames:["scip-setup"],keywords:["setup","adopt","install","bootstrap"],message:"Setup request: use scip-setup; keep CI setup out of the default path."},{id:"debug",skillNames:["scip-debug","scip-triage-issue"],keywords:["debug","bug","regression","failing","fails","error","wrong"],message:"Debug or bug request: use scip-debug. For issue-quality triage, use scip-triage-issue."},{id:"review",skillNames:["scip-maintainability","scip-api-impact","scip-verify"],keywords:["review","maintainability","architecture","boundary"],message:"Review request: use scip-maintainability, scip-api-impact, or scip-verify depending on whether this is architecture, API impact, or post-change verification."},{id:"implementation",skillNames:["scip-concrete-plan","scip-verify"],keywords:["implement","build","change","refactor","fix","add","update"],message:"Implementation request: plan first with scip-concrete-plan and `scip-query plan-context <target>`, then verify with scip-verify."},{id:"exploration",skillNames:["scip-explore"],keywords:["explain","how does","walk me through","trace","understand"],message:"Exploration request: use scip-explore before answering behavioral questions."},{id:"diagram",skillNames:["scip-diagram"],keywords:["diagram","visualize","visualise","flow map","architecture map"],message:"Diagram request: use scip-diagram and back every node and edge with scip-query evidence."},{id:"health",skillNames:["scip-cleanup-audit","scip-cleanup-improve"],keywords:["health","score","dossier","cleanup","dead code","duplicate","debloat","as high as","maximize","maximise"],message:"Health or cleanup request: use scip-cleanup-audit before editing; use scip-cleanup-improve when the user wants confirmed issues fixed autonomously."}];function bh(e){let t=al.find(i=>i.skillNames.some(o=>cl(e,o)));if(t)return t;let n=0,r=[];for(let i of al){let o=i.keywords.filter(s=>cl(e,s)).length;n+=o,o>0&&r.push(i)}return n<2||r.length===0?null:r[0]}function Sh(e,t){return t.SCIP_QUERY_ROUTER==="off"?"off":e.hooks?.router??"single"}function cl(e,t){let n=t.trim().split(/\s+/).map(r=>Le(r)).join("\\s+");return new RegExp(`(?<![A-Za-z0-9_-])${n}(?![A-Za-z0-9_-])`,"i").test(e)}function hl(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function vh(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function yl(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=rs(t);if(n)try{let r=me(n),i=Fe(n,r);return{projectRoot:n,config:r,paths:i}}catch{return}}function xh(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,sharedEvidenceDbPath:ic(e.projectRoot,e.config),entryRoots:e.config.entryRoots,semantic:e.config.semantic,suppressions:e.config.suppressions,declaredCouplings:e.config.declaredCouplings,locality:e.config.locality,architecture:e.config.architecture,coverageContracts:e.config.coverageContracts,docs:e.config.docs},r=new Oe(n,Rt(e.projectRoot));try{return t(r)}finally{r.close()}}import{existsSync as Qn,mkdirSync as Ph,symlinkSync as Th,readlinkSync as hi,unlinkSync as yi,readdirSync as kl}from"fs";import{join as Ie,dirname as Zt,resolve as Ye,relative as Ih,isAbsolute as Eh}from"path";import{homedir as Yn,platform as jh}from"os";import{fileURLToPath as wl}from"url";import{execFileSync as bl}from"child_process";import{createRequire as Rh}from"module";import{existsSync as kh}from"fs";import{platform as Yt,arch as Sl}from"os";var vl="v0.8.1",fi="https://github.com/sourcegraph/scip",xl="SCIP_QUERY_SCIP_BIN";function wh(e){if(e.isOnPath("scip"))return{source:"path",path:"scip"};let t=e.env[xl];if(t&&e.fileExists(t))return{source:"env",path:t};if(e.platform==="win32"){let n=e.resolveSidecar(e.arch);if(n&&e.fileExists(n))return{source:"sidecar",path:n}}return null}function $h(e){let t=Rh(import.meta.url);for(let n of e==="arm64"?["arm64","x64"]:[e])try{return t.resolve(`scip-query-scip-windows/scip-win32-${n}.exe`)}catch{}return null}function Kn(e=process.env){return wh({platform:Yt(),arch:Sl(),env:e,isOnPath:ze,fileExists:kh,resolveSidecar:$h})?.path??null}function Xt(){return Kn()!==null}function Ch(){let e=Yt(),t=Sl(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let o=`scip-${n}-${r}.${i}`;return{url:`${fi}/releases/download/${vl}/${o}`,filename:o}}function gi(){let e=Ch();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Yt()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
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
- `:` ${pi}/releases/tag/${gl}
44
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function yl(e){if(Yt()==="darwin"&&Ue("brew")){e("Installing scip CLI via Homebrew...");try{if(ml("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),Ue("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(Ue("go")){e("Installing scip CLI via go install...");try{if(ml("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),Ue("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: ${pi}/releases`),!1}var vh=Sh()==="win32",Yn=["_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 Xn(e={}){let t=e.quiet?()=>{}:console.log,n=Sl(import.meta.url),r=Qe(Zt(n),"..","skills"),i=[Te(Qn(),".claude","skills"),Te(Qn(),".codex","skills"),Te(Qn(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of i){let a=Zt(s);if(!Kn(a))continue;gh(s,{recursive:!0});let c=Rl(s);xh(s,r,c,o,t);for(let l of Yn){let d=Te(r,l),p=Te(s,l);if(!Kn(d)){o.skipped.push(`${c}/${l}`);continue}if(Kn(p)){try{let m=fi(p);if(Qe(m)===Qe(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}gi(p)}hh(d,p,vh?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function xh(e,t,n,r,i){let o=new Set(Yn);for(let s of bl(e)){if(o.has(s))continue;let a=Te(e,s),c;try{c=Qe(Zt(a),fi(a))}catch{continue}xl(c,t)&&(gi(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function vl(e={}){let t=Sl(import.meta.url),n=Qe(Zt(t),"..","skills"),r=e.homeDir??Qn(),i=[Te(r,".claude","skills"),Te(r,".codex","skills"),Te(r,".agents","skills")],o={removed:[],left:[],skipped:[]};for(let s of i){if(!Kn(s))continue;let a=Rl(s);for(let c of bl(s)){let l=Te(s,c),d;try{let p=fi(l);d=Qe(Zt(l),p)}catch{o.left.push(`${a}/${c} (not a symlink)`);continue}if(!xl(d,n)){o.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(o.removed.push(`${a}/${c}`),!e.dryRun)try{gi(l)}catch(p){o.skipped.push(`${a}/${c} (${p instanceof Error?p.message:String(p)})`)}}}return o}function xl(e,t){let n=yh(Qe(t),Qe(e));return n===""||!n.startsWith("..")&&!bh(n)}function Rl(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as Hu}from"child_process";import{performance as et}from"perf_hooks";import{existsSync as ke,readFileSync as qx,renameSync as Bx,rmSync as Vx,unlinkSync as Hx,writeFileSync as Wx}from"fs";import{dirname as Rr,extname as Gx,join as mt,resolve as Ux}from"path";import{execFileSync as wS}from"child_process";import{createHash as $S}from"crypto";import{closeSync as CS,copyFileSync as pr,existsSync as Re,mkdirSync as ur,mkdtempSync as PS,openSync as TS,readdirSync as IS,readFileSync as mr,renameSync as zd,rmSync as Ze,statSync as jS,writeFileSync as ES}from"fs";import{basename as dr,dirname as V,extname as LS,join as ne,resolve as Bd}from"path";import{platform as AS}from"os";import Rh from"better-sqlite3";import{execFileSync as kh}from"child_process";import{existsSync as wh,readdirSync as $h,readFileSync as Ch}from"fs";import{extname as Zn,join as kl}from"path";function ut(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>er({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function er(e){let t=new Set((e.extensions??Lo).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!wh(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Rt(e.projectRoot),r=Ph(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Rh(e.dbPath);try{let o=Ih(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=Ch(kl(e.projectRoot,m),"utf-8"),g=s.run(jh(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 Ph(e,t){let n=Th(e,t);if(n)return n;let r=[],i=o=>{let s=o?kl(e,o):e,a;try{a=$h(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Ao.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(Zn(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function Th(e,t){try{return kh("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
46
- `).filter(r=>r&&t.has(Zn(r).toLowerCase())).sort()}catch{return null}}function Ih(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 jh(e){return Zn(e).toLowerCase()===".vue"?"vue":Zn(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as Lh}from"crypto";import{appendFileSync as Ah,existsSync as Dh,mkdirSync as Oh,readFileSync as Fh}from"fs";import{dirname as Il,join as $l}from"path";function hi(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 tr(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=hi(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"),wl(r,i,s)):s.size>0?wl(r,i,s):{mode:"closure",changedFiles:r,affectedFiles:Eh(r,t,i),reasons:[]}}function wl(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function Eh(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 Nh="<global-symbols>";function Mh(e){let t=[];for(let n of e.all(`
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(`
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(`
@@ -70,7 +70,7 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
70
70
  FROM defn_enclosing_ranges r
71
71
  JOIN documents d ON d.id = r.document_id
72
72
  JOIN global_symbols g ON g.id = r.symbol_id
73
- `))t.push({relativePath:n.relative_path,kind:"definition",values:yi(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
73
+ `))t.push({relativePath:n.relative_path,kind:"definition",values:vi(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
74
74
  SELECT d.relative_path,
75
75
  c.chunk_index,
76
76
  m.role,
@@ -85,7 +85,7 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
85
85
  JOIN chunks c ON c.id = m.chunk_id
86
86
  JOIN documents d ON d.id = c.document_id
87
87
  JOIN global_symbols g ON g.id = m.symbol_id
88
- `))t.push({relativePath:n.relative_path,kind:"mention",values:yi(n,[n.chunk_index,n.role])});for(let n of e.all(`
88
+ `))t.push({relativePath:n.relative_path,kind:"mention",values:vi(n,[n.chunk_index,n.role])});for(let n of e.all(`
89
89
  SELECT g.symbol,
90
90
  g.display_name,
91
91
  g.kind,
@@ -99,9 +99,9 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
99
99
  ) AND NOT EXISTS (
100
100
  SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
101
101
  )
102
- `))t.push({relativePath:Nh,kind:"global-symbol",values:yi(n)});return _h(t)}function _h(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=Lh("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 qh(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 bi(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 Si(e,t=Bh){let n=t.now();if(!t.databaseExists(e.previousDbPath))return nr(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return nr(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=wn(e.previousSnapshot,e.currentSnapshot),a=new Set(o),c=s.changes.length>0&&!hi(s).fullProject&&s.changes.every(m=>a.has(m.path)),l=tr(s,c?t.dependencyGraph(r):new Map,o),d=qh(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:bi(l,d,o.length)}}catch(o){return nr(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{Cl(r),Cl(i)}}function jl(e,t,n,r=Date.now()){return nr(e,t,r,r,n)}function El(e){let t=Il(e);return{latestPath:$l(t,"affected-shadow-latest.json"),historyPath:$l(t,"affected-shadow.jsonl")}}function Ll(e,t=n=>Fh(n,"utf-8")){let n=El(e),r;try{r=JSON.parse(t(n.latestPath))}catch(S){let x=Uh(S),w=x?"telemetry-missing":Gh(S);return Ye(n,w,x?void 0:S instanceof Error?S.message:String(S))}if(q(r)&&typeof r.version=="number"&&r.version!==1)return Ye(n,"unsupported-record-version",`Unsupported version ${r.version}.`);if(!Hh(r))return Ye(n,"telemetry-malformed");if(r.status==="unavailable")return Wh(r.reason)?{state:"unavailable",...n,reason:r.reason,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,...typeof r.error=="string"?{error:r.error}:{}}:Ye(n,"telemetry-malformed");if(r.status!=="evaluated")return Ye(n,"telemetry-malformed");let i=r.plan,o=r.comparison,s=r.evaluation;if(!q(r.manifest)||!q(i)||!q(o)||!q(s))return Ye(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"||!Pl(g)||!Pl(h))return Ye(n,"telemetry-malformed");let y=m.length===0?1:(m.length-f.length)/m.length;return!Tl(c,p)||!Tl(d,m)||s.passed!==(f.length===0)||Math.abs(g-y)>Number.EPSILON||f.some(S=>!m.includes(S)||p.includes(S))?Ye(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 Al(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 Dl(e,t,n=Vh){let r=El(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}function yi(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 Bh={now:()=>Date.now(),databaseExists:e=>Dh(e),openDatabase:(e,t,n)=>new Oe({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>gn(e),dependencyGraph:e=>bn(e),factDigests:e=>Mh(e)},Vh={appendHistory:(e,t)=>{Oh(Il(e),{recursive:!0}),Ah(e,`${JSON.stringify(t)}
104
- `)},writeLatest:(e,t)=>St(e,t,{spacing:2,trailingNewline:!0})};function nr(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 Cl(e){try{e?.close()}catch{}}function Hh(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 Wh(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="oracle-error"}function Pl(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function Tl(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Ye(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function Gh(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function Uh(e){return e instanceof Error&&e.code==="ENOENT"}import{createHash as Jh}from"crypto";import{copyFileSync as zh,existsSync as Ol,rmSync as Fl}from"fs";import{resolve as Kh}from"path";import _l from"better-sqlite3";var Qh={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}]},Yh={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 ql(e){let t=Date.now(),n=Xh(e.affectedFiles);if(Zh(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Fl(e.candidateDbPath,{force:!0}),!Ol(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Ol(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");Nl(e.previousDbPath,"previous SQLite generation",!1),Nl(e.miniDbPath,"incremental SQLite mini database"),zh(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new _l(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),vi(r,"main","candidate SQLite generation"),vi(r,"incremental","incremental SQLite mini database"),ey(r,n),ty(r,n.length);let i=xi(r,"main",!0),o=Xe(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{ny(r),ry(r),iy(r),e.onStage?.("after-delete"),oy(r),e.onStage?.("after-symbol-reconciliation"),sy(r),e.onStage?.("after-insert"),ay(r),cy(r,n.length,o),e.onStage?.("before-commit")}).immediate(),Bl(r,"main","candidate SQLite generation");let c=[...ly(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{Fl(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function Xh(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 Zh(e,t,n){let r=[e,t,n].map(i=>Kh(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Nl(e,t,n=!0){let r=new _l(e,{readonly:!0,fileMustExist:!0});try{vi(r,"main",t),n&&Bl(r,"main",t)}finally{r.close()}}function vi(e,t,n){for(let[r,i]of Object.entries(Qh)){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(Yh)){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}`)}Ml(e,t,"documents",["relative_path"],n),Ml(e,t,"global_symbols",["symbol"],n)}function Ml(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 Bl(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 ey(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 ty(e,t){let n=Xe(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=Xe(e,`SELECT COUNT(*) AS value
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
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
@@ -111,7 +111,7 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
111
111
  FROM incremental.documents d
112
112
  LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
113
113
  WHERE p.relative_path IS NULL
114
- LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function ny(e){e.exec(`
114
+ LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function Sy(e){e.exec(`
115
115
  CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
116
116
  INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
117
117
  SELECT g.symbol
@@ -138,7 +138,7 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
138
138
  FROM incremental.mentions m
139
139
  JOIN incremental.global_symbols g ON g.id = m.symbol_id
140
140
  WHERE m.role = 1;
141
- `)}function ry(e){let t=e.prepare(`WITH changed_symbols AS (
141
+ `)}function vy(e){let t=e.prepare(`WITH changed_symbols AS (
142
142
  SELECT symbol FROM temp.incremental_old_defined_symbols
143
143
  UNION
144
144
  SELECT symbol FROM temp.incremental_new_defined_symbols
@@ -161,7 +161,7 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
161
161
  SELECT u.symbol
162
162
  FROM unaffected_definitions u
163
163
  JOIN changed_symbols c ON c.symbol = u.symbol
164
- LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function iy(e){e.exec(`
164
+ LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function xy(e){e.exec(`
165
165
  DELETE FROM main.mentions
166
166
  WHERE chunk_id IN (
167
167
  SELECT c.id
@@ -183,7 +183,7 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
183
183
  );
184
184
  DELETE FROM main.documents
185
185
  WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
186
- `)}function oy(e){e.exec(`
186
+ `)}function Ry(e){e.exec(`
187
187
  UPDATE main.global_symbols
188
188
  SET display_name = NULL,
189
189
  kind = NULL,
@@ -225,7 +225,7 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
225
225
  WHERE source.symbol = main.global_symbols.symbol
226
226
  )
227
227
  WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
228
- `)}function sy(e){let t=Xe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=Xe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=Xe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
228
+ `)}function ky(e){let t=Ze(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=Ze(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=Ze(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
229
229
  SELECT id + ?, language, relative_path, position_encoding, text
230
230
  FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
231
231
  SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
@@ -240,15 +240,15 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
240
240
  r.start_line, r.start_char, r.end_line, r.end_char
241
241
  FROM incremental.defn_enclosing_ranges r
242
242
  JOIN incremental.global_symbols source ON source.id = r.symbol_id
243
- JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function ay(e){e.exec(`
243
+ JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function wy(e){e.exec(`
244
244
  DELETE FROM main.global_symbols
245
245
  WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
246
246
  AND NOT EXISTS (
247
247
  SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
248
248
  );
249
- `)}function cy(e,t,n){let r=Xe(e,"SELECT COUNT(*) AS value FROM main.documents"),i=Xe(e,`SELECT COUNT(*) AS value
249
+ `)}function $y(e,t,n){let r=Ze(e,"SELECT COUNT(*) AS value FROM main.documents"),i=Ze(e,`SELECT COUNT(*) AS value
250
250
  FROM main.documents d
251
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),s=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||s!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function ly(e){let t=xi(e,"main",!0),n=xi(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function xi(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
251
+ JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),s=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||s!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function Cy(e){let t=wi(e,"main",!0),n=wi(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function wi(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
252
252
  FROM ${t}.documents d
253
253
  ${r}
254
254
  ORDER BY d.relative_path`).all(),o=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
@@ -270,11 +270,12 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
270
270
  JOIN ${t}.documents d ON d.id = c.document_id
271
271
  JOIN ${t}.global_symbols g ON g.id = m.symbol_id
272
272
  ${r}
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=Jh("sha256");for(let f of p.sort())m.update(f).update(`
274
- `);l.set(d,m.digest("hex"))}return l}function Xe(e,t){return e.prepare(t).get().value}import{readFileSync as dy,writeFileSync as uy}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 Hl(e){let t=e.readFingerprint(),n=py(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return my(e.cachePath,e.readFingerprint(),r),r}function py(e,t){try{let n=JSON.parse(dy(e,"utf-8"));return Vl(n.fingerprint)===Vl(t)?{result:n.result}:null}catch{return null}}function my(e,t,n){uy(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
275
- `)}function Vl(e){return JSON.stringify(e)}import{createHash as fy}from"crypto";import{existsSync as Ri,readFileSync as gy,readdirSync as hy}from"fs";import{dirname as ki,join as rr,relative as yy,resolve as wi,sep as Wl}from"path";function Gl(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let s=Kl(o.path,t);s?r[s].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Ul(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=Kl(a,e);c&&c!==i&&s.add(c)}}return by(e,r)}function Jl(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 $i(e){if(e===".")return"root";let t=fy("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function zl(e,t){let n=wi(e),r={};for(let i of t)r[i]=Sy(n,i);return r}function Kl(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 by(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 Sy(e,t){let n=t==="."?e:rr(e,t),r=vy(n),i=xy(n),o=i?Ry(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 vy(e){let t=rr(e,"package.json");if(!Ri(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Ci(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 xy(e){let t=rr(e,"tsconfig.json");if(Ri(t))return t;let n;try{n=hy(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?rr(e,n[0]):void 0}function Ry(e,t){let n=Ci(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=ky(n.value,e,t),i=Ql(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function ky(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=ki(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=Yl(a,i,n);c&&o.add(c)}return[...o]}function Ql(e,t,n,r){let i=wy(t);if(i)return{pathsTargets:$y(i,ki(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Cy(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let s=Ci(o);return s.ok?Ql(o,s.value,n,r+1):{pathsTargets:[],failed:!0}}function wy(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 $y(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=Yl(o,t,n);s&&r.add(s)}return[...r]}function Cy(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=wi(ki(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Wl).includes("node_modules")&&pe(n,i)&&Ri(i))return i}function Yl(e,t,n){let r=e.replace(/\/?\*+$/,""),i=wi(t,r===""?".":r);if(!pe(n,i))return;let s=yy(n,i).split(Wl).join("/");return s===""?".":s}function Py(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]!==`
276
- `;)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 Ci(e){try{let t=gy(e,"utf-8"),n=JSON.parse(Py(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{existsSync as Ty,readFileSync as Iy,readdirSync as jy,statSync as Ey}from"fs";import te from"path";var Ly=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function en(e,t=[]){let n=te.resolve(e),r=t.flatMap(c=>Dy(n,c));if(r.length>0)return Xl(n,Zl(r));let i=Ay(n),o=Zl(i),s=Fy(n,o)?[n,...o]:o,a=s.length>0?s:[n];return Xl(n,a)}function Xl(e,t){return[...new Set(t.map(n=>My(e,n)))].sort((n,r)=>n.localeCompare(r))}function Ay(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=jy(r,{withFileTypes:!0})}catch{continue}for(let o of i){let s=te.join(r,o.name);if(o.isDirectory()){!Ly.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&Oy(s)&&t.push(te.dirname(s))}}return t}function Dy(e,t){let n=t.trim();if(!n)return[];let r=te.resolve(e,n);if(!pe(e,r))return[];try{let i=Ey(r);if(i.isDirectory())return[r];if(i.isFile()&&ed(te.basename(r)))return[te.dirname(r)]}catch{return[]}return[]}function Oy(e){if(!ed(te.basename(e)))return!1;let t=td(e);return t?te.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function ed(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function Zl(e){let t=[...new Set(e.map(n=>te.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&_y(n,r)))}function Fy(e,t){if(t.length===0||t.some(r=>te.resolve(r)===e))return!1;let n=te.join(e,"tsconfig.json");return Ty(n)&&Ny(n)}function Ny(e){let n=td(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!te.extname(r))):!1}function td(e){try{let t=JSON.parse(Iy(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function My(e,t){let n=te.relative(e,t);return n?n.split(te.sep).join("/"):"."}function _y(e,t){let n=te.relative(e,t);return!!n&&!n.startsWith("..")&&!te.isAbsolute(n)}import{createHash as sb}from"crypto";import{existsSync as Ti,readFileSync as fd,statSync as ab,writeFileSync as Ii}from"fs";import{join as cb}from"path";import{readFileSync as nd}from"fs";import{createRequire as qy}from"module";import{dirname as By,isAbsolute as QP,relative as YP,resolve as XP,sep as ZP}from"path";var rd=qy(import.meta.url),Vy=1,id="0.4.0";function Pi(){let e=Hy();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Hy(){try{let e=rd.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(nd(e,"utf8"));if(t.version!==id)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${id}`};let n=By(e),r=rd.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(nd(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:Wy(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Wy(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Vy}`}import{createHash as Gy}from"crypto";import{readFileSync as Uy}from"fs";import{dirname as Jy,join as ir}from"path";var or=2,zy="typescript-index";function od(e){let t=ir(e,zy);return{rootDir:t,requestDir:ir(t,"requests"),responseDir:ir(t,"responses")}}function sd(e){try{let t=JSON.parse(Uy(ir(Jy(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:Gy("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 Ky}from"crypto";import{existsSync as Qy,mkdirSync as ad,readFileSync as Yy,rmSync as cd}from"fs";import{resolve as ld}from"path";var Xy=12e4,Zy=5,sr=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=es(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??ib(),this.runtime=n.runtime??ob}request(t){let n=Pn(this.cacheDir),r=od(this.cacheDir),i=qr(n.statePath);if(!dd(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),s=ld(r.requestDir,`${o}.json`),a=ld(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;ad(r.requestDir,{recursive:!0}),ad(r.responseDir,{recursive:!0}),St(s,{protocolVersion:or,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(Qy(a))return eb(Yy(a,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=qr(n.statePath);if(!dd(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Zy)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{cd(s,{force:!0}),cd(a,{force:!0})}}};function dd(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Qo,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===or&&n.isProcessAlive(e.pid)&&(r||i)}function eb(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==or||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=tb(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 tb(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(nb)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let s=o.bytesBase64===null?null:rb(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 nb(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 rb(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function ib(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Xy}var ob={now:Date.now,randomId:Ky,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:bt};function lb(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=wn(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=tr(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=db([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=ud(e.currentSnapshot,e.projectFiles,e.producerIdentity),s=ud(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==s)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let a=md(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!a)return{eligible:!1,reason:"prior document identity unavailable"};let c=md(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:pd(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:pd(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 db(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 gd(e){let t=Date.now();try{if(!Ti(e.previousDbPath)||!Ti(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Pi();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=gn(o,{includeIgnored:!1}).filter(Ht).sort(),a=bn(o)}finally{o.close()}let c=performance.now()-n,l=lb({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:Ti(cb(e.projectRoot,"tsconfig.json"))});if(!l.eligible)throw new Error(l.reason);let d=sd(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let m=new sr({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=ab(e.previousShardPath).size>=Ga;n=performance.now();let h=g?null:fd(e.previousShardPath),y=g?{completeIndexBytes:null,affectedIndexBytes:Ba(m.fragments)}:Wa({packageVersion:r.packageVersion,baseIndexBytes:h,fragments:m.fragments}),S=performance.now()-n;n=performance.now(),g?Ua({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,nextGenerationIdentity:l.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:m.fragments}):(Va({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:h,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.previousFragmentGeneration,documentIdentities:l.previousDocumentIdentities,allowUntrackedDocuments:!0}),Ha({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.nextFragmentGeneration,fragments:m.fragments,documentIdentities:l.nextDocumentIdentities}));let x=performance.now()-n;n=performance.now(),y.completeIndexBytes&&Ii(e.candidateShardPath,y.completeIndexBytes),Ii(e.candidateAffectedScipPath,y.affectedIndexBytes);let w=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:x,writeMs:w}};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 ${x.toFixed(0)}ms, write ${w.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 hd(e){let t=Pi();if(!t.available)throw new Error(t.reason);let n=Ja({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:fd(e.baseShardPath),packageVersion:t.packageVersion});Ii(e.candidateShardPath,n)}function ud(e,t,n){let r=e.files.filter(i=>Uo(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 ji(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function pd(e,t){return ji(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function md(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),s=ss({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,ji(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return a}function ji(e){return sb("sha256").update(e).digest("hex")}import{execFile as ub}from"child_process";import{existsSync as ar,renameSync as Li,rmSync as Ai,statSync as pb}from"fs";import{cpus as mb}from"os";import{join as yd}from"path";function fb(e,t,n){if(!e.defaultOutputPath)return;let r=yd(t,e.defaultOutputPath);n!==r&&ar(r)&&Li(r,n)}function gb(e,t,n){if(!e.defaultOutputPath)return null;let r=yd(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Ai(i,{force:!0}),ar(r)?(Li(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function hb(e){e&&(Ai(e.defaultOutputPath,{force:!0}),e.backupPath&&ar(e.backupPath)&&Li(e.backupPath,e.defaultOutputPath))}function yb(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,mb().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function bd(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=yb(o.length,r),c=await Sb(o,a,l=>Ei(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 Ei(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 Ei(l,t,n));return s.sort((l,d)=>e.findIndex(p=>p.id===l.id)-e.findIndex(p=>p.id===d.id))}async function Ei(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Ai(e.scipPath,{force:!0});let r=gb(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{let a=Bo(e.binary,e.args);await bb(a.binary,a.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),fb(e.config,t,e.scipPath)}catch(a){let c=a instanceof Error?a.message:String(a),l=`${e.resolvedBinary} indexer failed: ${c.split(`
277
- `)[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{hb(r)}if(!ar(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=pb(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 bb(e,t,n){return new Promise((r,i)=>{ub(e,[...t],n,o=>{o?i(o):r()})})}async function Sb(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 vb}from"child_process";import{platform as xb}from"os";function cr(e,t){let n=e.installMethods,r=xn(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(Ue(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{vb(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:xb()==="win32"});let o=Rn(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 nS from"better-sqlite3";import{existsSync as rS}from"fs";import{dirname as iS,join as oS,resolve as sS}from"path";import{readFileSync as kb,rmSync as wb,statSync as $b,mkdtempSync as Cb}from"fs";import{tmpdir as Pb}from"os";import{join as Di}from"path";import{Worker as Tb}from"worker_threads";function Rb(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Et(){return{skippedReferences:0,skippedReferenceReasons:Rb(),skippedReferenceSamples:[]}}function lr(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 Sd(e){return e.length>=8&&xd(e.length)>1}function vd(e){let t=xd(e.vueFiles.length),n=jb(e.vueFiles),r=Lb(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=Cb(Di(Pb(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=Ib(),l=Date.now();try{for(let m=0;m<r.length;m++)new Tb(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[m],resultPath:Di(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(kb(Di(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),...Et()};for(let m of d)lr(p,m);return p}finally{wb(o,{recursive:!0,force:!0})}}function xd(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 Ib(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function jb(e){let t=Eb(),n=[];for(let r of e){let i=Rd(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 Eb(){return Number.POSITIVE_INFINITY}function Lb(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Ab(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 Ab(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Rd(e.fileName)-e.startOffset)}function Rd(e){try{return $b(e).size}catch{return 1}}import{createRequire as Db}from"module";import{existsSync as Ob,readFileSync as Fi}from"fs";import{dirname as kd,extname as Fb,join as wd,relative as Nb,resolve as Mb}from"path";import{pathToFileURL as _b}from"url";function qb(e){e.transaction(()=>{e.prepare(`
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
+ `);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(`
278
279
  DELETE FROM mentions
279
280
  WHERE chunk_id IN (
280
281
  SELECT c.id
@@ -289,12 +290,12 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
289
290
  FROM documents
290
291
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
291
292
  )
292
- `).run()})()}function $d(e,t){return e.prepare(`
293
+ `).run()})()}function Od(e,t){return e.prepare(`
293
294
  SELECT relative_path AS relativePath
294
295
  FROM documents
295
296
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
296
297
  ORDER BY relative_path
297
- `).all().map(r=>Mb(t,r.relativePath))}function Cd(e,t){let{vueCore:n,ts:r,volarTs:i}=Bb(e),{parsed:o,vueOptions:s}=Vb(n,r,t),a=kd(t),c=n.createVueLanguagePlugin(r,o.options,s,f=>f),l=Hb(n,r,c),d=Wb(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 Bb(e){let t=Db(_b(wd(e,"package.json")).href);return{vueCore:Oi(t,"@vue/language-core",e),ts:Oi(t,"typescript",e),volarTs:Oi(t,"@volar/typescript",e)}}function Vb(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,kd(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Hb(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!Ob(o))return;let s=Fi(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??Qb(o))});return r.current=i,i}function Wb(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Oi(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 Pd(e,t,n){let r=Gb(e);return i=>{if(!i.name)return null;let o=Ve(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:Ub(c.starts,a.line,2,i.name)}}function Gb(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: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
299
  SELECT
299
300
  d.relative_path AS relativePath,
300
301
  der.start_line AS startLine,
@@ -305,22 +306,22 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
305
306
  JOIN documents d ON d.id = der.document_id
306
307
  JOIN global_symbols gs ON gs.id = der.symbol_id
307
308
  ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
308
- `).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 Ub(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 Td(e,t,n){let r=Zb(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
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(`
309
310
  INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
310
311
  VALUES (?, ?, ?, ?)
311
- `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let d=Ve(t,l),p=Nd(r.name,r.version,d);o.run(p,"default",7,`Vue component|${d}`);let m=eS(i,r,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Id(e,t,n,r,i){return e.transaction(()=>(qb(e),Jb(e,t,n,r),zb(e,i)))()}function Jb(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 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
313
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
313
314
  VALUES (?, ?, ?, ?, X'00')
314
315
  `),s=e.prepare(`
315
316
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
316
317
  VALUES (?, ?, 1)
317
- `);for(let a of n){let c=r.get(a);if(!c)continue;let l=Ve(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 jd(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(Ni(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Ed(e){let t=new Set,n=[];for(let r of e){let i=Ld(r);t.has(i)||(t.add(i),n.push(r))}return n}function Ld(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function zb(e,t){let n=Xb(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 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
319
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
319
320
  VALUES (?, ?, ?, ?, X'00')
320
321
  `),i=e.prepare(`
321
322
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
322
323
  VALUES (?, ?, 0)
323
- `),o=new Set,s=0,a=0;for(let c of t){let l=Ld(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*Ad(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 Dd(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Ni(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Kb(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 Od(e,t){return Ve(e,t).startsWith("node_modules/")}function Ve(e,t){return Nb(e,t).replaceAll("\\","/")}function Qb(e){switch(Fb(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 Fd(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Fi(t,"utf-8"),r={text:n,lineStarts:Yb(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Kb}}function Yb(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Xb(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 Zb(e){try{let t=JSON.parse(Fi(wd(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 eS(e,t,n,r){let i=Ve(n,r),o=Nd(t.name,t.version,i);return e.get(o)?.id??null}function Nd(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function _d(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>aS({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function qi(e){return pt(ut(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),pt(_d({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function aS(e){let t=sS(e.projectRoot,e.tsconfig);if(!rS(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new nS(e.dbPath);try{let r=$d(n,e.projectRoot),i=oS(iS(e.dbPath),"augment-vue-meta.json");return Hl({cachePath:i,readFingerprint:()=>dS(n,e.projectRoot,e.tsconfig),compute:()=>cS({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 cS(e){let t=Td(e.db,e.projectRoot,e.vueFiles),n=lS(e,t),r=Ed(n.occurrences),i=Id(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:SS(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:bS(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function lS(e,t){if(Sd(e.vueFiles))return vd({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=uS({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return pS({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function dS(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=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
325
  SELECT
325
326
  (SELECT COUNT(*) FROM documents) AS documents,
326
327
  (SELECT COUNT(*) FROM global_symbols) AS symbols,
@@ -329,22 +330,22 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
329
330
  (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
330
331
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
331
332
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
332
- `).get();return{version:3,tsconfig:n,files:$n(t),db:r}}function uS(e){let t=Fd();return{projectRoot:e.projectRoot,context:Cd(e.projectRoot,e.configPath),symbolLookup:Pd(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function pS(e){let t=[],n=Et(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=mS(e,i);t.push(...o.occurrences),lr(n,o)}return{occurrences:t,...n}}function mS(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Md(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 Md(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),s=Ve(e.projectRoot,t.fileName),a=[...Ad(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:xS(a),processedStarts:new Set};return fS({...e,fileName:t.fileName,sourceInfo:n,sourceFile:s,map:o,tokenContext:c})}function fS(e){let t=[],n=Et();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||gS(e.sourceInfo.text,r.start))continue;let i=Dd(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!Od(e.projectRoot,d.fileName));if(!s){Mi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let a=Ve(e.projectRoot,s.fileName),c=hS(e.sourceFile,r.text,a);if(c){Mi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let l=jd(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(l===null){Mi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}qd(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a,l),e.tokenContext.processedStarts.add(r.start),vS(t,e,r,i,a,l)}return{occurrences:t,...n}}function gS(e,t){let n=e.lastIndexOf(`
333
- `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function hS(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Md(e,t,n){let r=Et();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:Ve(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Mi(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 _i(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 yS(e,t){let n=_i(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=_i(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function bS(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(..._i(e.filter(c=>c.reason===o),a))}return r.slice(0,t)}function SS(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return yS(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function vS(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of RS(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&&(qd(e,t.sourceReader,t.sourceInfo,t.sourceFile,a,i,o),t.tokenContext.processedStarts.add(s))}}function qd(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 xS(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function RS(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=kS(r,l.textSpan.start,o,i.text);d!==null&&a.push(d)}return a}function kS(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Ni(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function Lt(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=OS(e),s=Date.now();ur(V(o.outputScip),{recursive:!0}),ur(V(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",()=>fv(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:a.length}),l,d;if(e.skipIfUnchanged!==!1&&!Xa(t,o.outputDb)&&Bd(o.outputScip)===Bd(ne(V(o.outputDb),"index.scip"))){let g=nt(t);if(l=g?En(g,c):void 0,l){let h=Ln(l);if(h){if(!DS(o,c))try{Hr({snapshot:l,manifest:h,targetCacheDir:V(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${l.generationId.slice(0,12)}`)}catch(y){r(`Shared generation attach failed; continuing locally: ${Vi(y)}`)}}else{let y=await tc(l);if(y.kind==="owner")d=y.release;else if(y.kind==="generation-ready"){let S=Ln(l);if(S)try{Hr({snapshot:l,manifest:S,targetCacheDir:V(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${l.generationId.slice(0,12)} after waiting`)}catch(x){r(`Shared generation attach failed after waiting; continuing locally: ${Vi(x)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=qa(ne(V(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!p)throw d?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${V(o.outputDb)}.`);let m;try{m=await _t("reindex.lock",()=>av(ne(V(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=null,h=Mt("reindex.reuse-check",()=>(g=FS({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r}),g),()=>({languages:a.length,reused:g!==null}));if(h)return Vd({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),h;await _t("reindex.scip-cli-ready",()=>ZS(i,r));let y=MS(o);f=y.runDir;let S,x=await _t("reindex.fresh",async()=>(S=await _S({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:y,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),S),()=>({languages:a.length,reused:S?.reused,skipped:S?.skipped.length}));return Vd({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),x}catch(g){throw iu(o.metaPath,gr({trigger:e.trigger,result:"failed",start:s,error:g instanceof Error?g.message:String(g)})),g}finally{f&&Ze(f,{recursive:!0,force:!0}),m(),p.release(),d?.()}}function Vd(e){if(e.snapshot){if(Ln(e.snapshot)){Wr(e.snapshot,V(e.paths.outputDb),"local-fresh");return}try{let t=nt(e.projectRoot),n=t?En(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}ec({snapshot:e.snapshot,sourceCacheDir:V(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=nt(e.projectRoot);return(r?En(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),Wr(e.snapshot,V(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: ${Vi(t)}`)}}}function DS(e,t){if(!Re(e.outputScip)||!Re(e.outputDb)||!ru(e.metaPath,t))return!1;let n=it(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Vi(e){return e instanceof Error?e.message:String(e)}function OS(e){let t=e.outputScip??ne(e.projectRoot,"index.scip"),n=e.outputDb??ne(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:ne(V(n),"meta.json")}}function FS(e){let t=it(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!Re(e.paths.outputScip)||!Re(e.paths.outputDb)||!ru(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=gr({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return iu(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:NS(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function NS(e,t,n,r){let i=tu(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:tn(i[o]),outputBytes:nn(Wi(e.outputDb,o)),durationMs:0}))}function MS(e){let t=PS(ne(V(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:ne(t,dr(e.outputScip)),tempOutputDb:ne(t,dr(e.outputDb)),tempMetaPath:ne(t,dr(e.metaPath))}}async function _S(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await _t("reindex.language-indexers",async()=>(n=await BS(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(", ")}`),qS({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:s})){let f=Mt("reindex.publish",()=>QS(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",()=>KS(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 qS(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 BS(e,t){let n=US({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[O,Z]of n)Z.reused&&(r.push({language:O,scipPath:Z.scipPath}),i.add(O));for(let O of i)e.onStatus(`Reusing cached ${O} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),s=it(e.paths.outputDb,e.paths.metaPath),a=on(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?gd({projectRoot:e.projectRoot,cacheDir:V(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:rn(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:rn(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:Hi(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(d?["typescript"]:[]),m=d?void 0:VS(e,n),{preparedRuns:f,skippedLanguages:g,languageOutputScipPaths:h}=ev({languages:e.languages.filter(O=>!i.has(O)&&!p.has(O)),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(O=>O.language!=="typescript"||m.missedProjectIds.has(O.id)):f,S=await bd(y,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),x=[];if(m){WS(e.paths.outputDb,S);let O=h.typescript??e.tempPaths.tempOutputScip;x=GS({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:O,reusedProjects:m.reusedProjects})}let w=[...S,...x],{indexedOutputs:R}=nv(w,g),D=d?[{language:"typescript",scipPath:d.scipPath}]:[],_=[...r,...D,...R];rv(_,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:nn(d.scipPath)??void 0}]:[],T=JS(n,[...S,...z],m?{outputDb:e.paths.outputDb,classification:m.classification}:void 0);return{indexedOutputs:_,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:zS(n,e.languages),shards:T,typescriptProjectShardContext:m?{projects:m.allProjects,fingerprints:m.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function VS(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=zl(e.projectRoot,r),o=Gl(n.fingerprint.files,r),s=Ul(r,i),a=Jl(r,o,s),c=on(e.paths.metaPath),d=HS(c,a,g=>Re(fr(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 HS(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(He(s)!==He(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 WS(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=fr(e,r);ur(V(i),{recursive:!0}),pr(n.scipPath,i)}}function GS(e){return e.reusedProjects.map((t,n)=>{let r=fr(e.outputDb,t),i=rn(e.tempOutputScip,"typescript-project-cached",n);return pr(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:nn(i)??void 0}})}function US(e){let t=on(e.paths.metaPath),n=tu(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Wi(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(He(a)!==He(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 JS(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:nn(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:nn(fr(n.outputDb,i)),durationMs:0});return r}function tn(e){return $S("sha256").update(He(e)).digest("hex").slice(0,16)}function nn(e){try{return jS(e).size}catch{return null}}function zS(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function KS(e,t,n,r,i,o,s,a){let c=!a||a.completeScipUpdated,l=!1;c&&(Hd(e.paths.outputDb,n),l=Wd(n,e.tempPaths.tempOutputScip,e.onStatus));let d=iv({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..."),hd({cacheDir:V(e.paths.outputDb),generationIdentity:a.nextFragmentGeneration,baseShardPath:a.scipPath,candidateShardPath:a.candidateScipPath});let x=n.map(w=>w.language==="typescript"?{language:w.language,scipPath:a.candidateScipPath}:w);return Hd(e.paths.outputDb,x),l=Wd(x,e.tempPaths.tempOutputScip,e.onStatus),l}});if(pt(ut(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&a){let x=null,w=null;try{x=new Oe({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),w=new Oe({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let R=as(x,e.fingerprint,a.referenceFragmentsByFile,w);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{x?.close(),w?.close()}}let p=Hi(e.paths.metaPath),m=d.mode==="incremental"&&a?sv(a,d.changedDocumentPaths):Si({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=gr({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(x=>x.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",h={...o};g&&delete h.typescript;let{metadata:y,pruneProjects:S}=Qd({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:h,typescriptProjectShardContext:s,lastRefresh:f});return y.scipCompanion=g?"deferred":"current",Yd(e.paths.outputDb,S),Gi(e.tempPaths.tempMetaPath,y),Ma({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(V(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[a.nextFragmentGeneration]:[]),Kd(e.paths.outputDb,m,e.onStatus),f}function QS(e,t,n,r,i,o){let s=Hi(e.paths.metaPath),a=null;try{pr(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(p){a=jl("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??=Si({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=gr({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=Qd({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return Yd(e.paths.outputDb,d),Gi(e.paths.metaPath,l),_a(e.paths.outputDb,e.paths.metaPath),Kd(e.paths.outputDb,a,e.onStatus),c}function Hi(e){return Jo(on(e)?.fingerprint)}function Kd(e,t,n){try{Dl(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 Qd(e){let t=YS({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 YS(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=on(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 Yd(e,t){let n=nu(e);if(t===null){Ze(n,{recursive:!0,force:!0});return}let r;try{r=IS(n)}catch{return}for(let i of XS(r,t))Ze(ne(n,i),{force:!0})}function XS(e,t){let n=new Set(t.map(r=>`${$i(r)}.scip`));return e.filter(r=>!n.has(r))}function Hd(e,t){for(let n of t){let r=Wi(e,n.language);ur(V(r),{recursive:!0}),n.scipPath!==r&&pr(n.scipPath,r)}}async function ZS(e,t){if(!zn()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
334
- Install from: https://github.com/sourcegraph/scip/releases`);if(AS()==="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..."),!yl(t))throw new Error(`The scip CLI is required but could not be installed.
335
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function ev(e){let t=[],n=[],r=e.languages.map((o,s)=>({language:o,scipPath:e.languages.length>1?rn(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=tv({...e,language:o,scipPath:s});for(let c of a)"skipped"in c?Xd(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function tv(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Bi({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??en(e.projectRoot,e.typescriptProjects);return t.length===0?[Bi({...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)=>Bi({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:rn(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Bi(e){let t=st(e.language),n=xn(t),r=Ho(t,e.projectRoot);if(!r&&!Vo(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...`),!cr(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??Rn(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:Wo(t,e.env,i)}}}function nv(e,t){let n=new Map;for(let i of e)if(i.skipped)Xd(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)Qa(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&zd(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function Xd(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 rv(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
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.
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
+ 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(`
336
337
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
337
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.
338
339
  `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
339
- `))}function Wd(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=Ya(e.map(o=>o.scipPath),t);return eu(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&zd(e[0].scipPath,t);return!1}function iv(e){let t;if(ov(e)){let i=ne(e.run.tempPaths.runDir,"typescript-affected.db");try{Zd(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();Gd(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=ql({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),Ze(i,{force:!0}),Ze(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 Gd(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function ov(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 sv(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:bi(e.plan,o,e.projectFileCount)}}function Gd(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||Zd(e,r);let o=zn();if(!o)throw new Error("scip CLI is not available");wS(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 Zd(e,t){let n=Ka(e);eu(n,t)}function eu(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function rn(e,t,n){let r=LS(e)||".scip",i=dr(e,r);return ne(V(e),`${i}.${n+1}.${t}${r}`)}async function av(e,t){for(let n=0;n<2;n++){let r=cv(e,t);if(r)return r;let i=lv(e);if(i&&dv(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await pv(i.pid))throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${V(e)}; refusing to steal an active lock.`);Ze(e,{force:!0});continue}if(i&&!bt(i.pid)){Ze(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${V(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${V(e)}.`)}function cv(e,t){let n;try{n=TS(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 ES(n,JSON.stringify(r)+`
340
- `),()=>{try{CS(n)}finally{Ze(e,{force:!0})}}}function lv(e){try{let t=JSON.parse(mr(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:V(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function dv(e,t){return e?.kind==="manual-cli"&&uv(t?.trigger)}function uv(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function pv(e){return Ud(e,"SIGTERM"),await Jd(e,2e3)?!0:(Ud(e,"SIGKILL"),Jd(e,1e3))}function Ud(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function Jd(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!bt(e))return!0;await mv(50)}return!bt(e)}function mv(e){return new Promise(t=>setTimeout(t,e))}function fv(e,t,n){return Ko(e,t,n)}function tu(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"?gv(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&hv(n),...o,clojureConfigPath:s,files:$n(e,{language:r,markerFiles:i})}]}))}function gv(e){return e?.trim()||void 0}function hv(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Wi(e,t){return ne(V(e),"language-indexes",`${t}.scip`)}function nu(e){return ne(V(e),"language-indexes","typescript-projects")}function fr(e,t){return ne(nu(e),`${$i(t)}.scip`)}function on(e){try{return JSON.parse(mr(e,"utf-8"))}catch{return null}}function ru(e,t){try{let n=JSON.parse(mr(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&He(n.fingerprint)===He(t)&&He([...n.indexedLanguages??[]].sort())===He(t.languages)}catch{return!1}}function Gi(e,t){St(e,t,{spacing:2,trailingNewline:!0})}function iu(e,t){try{let n=JSON.parse(mr(e,"utf-8"));if(n.version!==2&&n.version!==3)return;Gi(e,{...n,lastRefresh:t})}catch{}}function gr(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 He(e){return JSON.stringify(e)}var Ui=864e5;function ou(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=yv(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 w of d){f+=w.events.filter(_=>_.event==="reopened").length;let R=w.events[w.events.length-1],D=`${w.check}\0${w.findingId}`;if(R.event==="resolved"&&s.has(D))g+=1;else if(R.event==="resolved"){let _=Gt(w.events.slice(0,-1)),z=_?.comparisonBaseCommit??_?.commit,T=R.comparisonBaseCommit??R.commit;z&&(T===z||R.verifiedAgainstCommit===z)?(p+=1,S.push((R.ts-w.caughtAt)/Ui)):h+=1}else R.event==="suppressed"?m+=1:y+=1}let x=p+m;c.push({check:l,caught:d.length,fixed:p,suppressed:m,reopened:f,moved:g,unverified:h,open:y,precision:x>0?p/x:null,medianDaysToFix:S.length>0?bv(S):null})}return{totalEvents:r.length,windowStart:t.sinceMs??null,checks:c.sort((l,d)=>l.check.localeCompare(d.check))}}function yv(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 su(e,t){let n=/^(\d+)([dw])$/.exec(e.trim());if(n){let i=Number(n[1]),o=n[2]==="w"?7*Ui:Ui;return t-i*o}let r=Date.parse(e);return Number.isNaN(r)?null:r}function bv(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 Sv}from"child_process";import{statSync as vv}from"fs";import{isAbsolute as xv,join as Rv,relative as kv}from"path";import{watch as wv}from"chokidar";import $v from"ignore";var hr=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=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.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=Rt(t.projectRoot),this.extraIgnore=$v(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let t=wv(this.projectRoot,{ignoreInitial:!0,ignored:(n,r)=>this.isIgnoredWatchPath(n,r?.isDirectory()??!1)});t.on("all",(n,r)=>{this.stopped||this.handleFileChange(r)}),t.on("error",n=>{this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`))}),this.fsWatchers.push(t)}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=au(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}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")||this.scheduleReindex({kind:"watch-source",detail:n})}relativeWatchPath(t){let n=xv(t)?t:Rv(this.projectRoot,t);return kv(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=au(this.pendingTrigger,t),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let n=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:n}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-t;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=Date.now();this.setStatus({state:"indexing",startedAt:r}),this.runReindex(n).then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(t){return new Promise((n,r)=>{let i=Date.now(),o=me(this.projectRoot),s=Object.keys(o).length>0?o:this.config,a=De(this.projectRoot,s),c=s.indexer?.typescript,l=s.indexer?.clojure,d=Sv(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=Zo(this.projectRoot,t),r={head:Vt(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:n};try{let i=vv(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 au(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}import{existsSync as Jv}from"fs";import{existsSync as lu,mkdirSync as du,readFileSync as uu,writeFileSync as pu}from"fs";import{homedir as Cv}from"os";import{dirname as mu,isAbsolute as Pv,join as Ji,relative as cu,resolve as Tv}from"path";function fu(e,t={}){let n=t.dossierDir?Tv(e.projectRoot,t.dossierDir):Ji(e.projectRoot,"docs","scip-query"),r={markdownPath:Ji(n,"health-dossier.md"),jsonPath:Ji(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},i=Nv({...e,generatedAt:new Date().toISOString(),healthDossier:r},e.projectRoot);try{return Dv(r.markdownPath,Iv(i),r),Ov(r.jsonPath,i,r),r}catch(o){return{...r,status:"failed",error:o instanceof Error?o.message:String(o)}}}function Iv(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${Ki(e.health)}`,"","## Items That Need Attention","",...jv(e),"","## Blocked Or Unavailable Checks","",...Ev(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","",...Lv(e),"","## JSON","",`Machine-readable report: \`${Av(e)}\``,""].join(`
341
- `)}`}function jv(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 Ev(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 Lv(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 Ki(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function Av(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function Dv(e,t,n){if(du(mu(e),{recursive:!0}),(lu(e)?uu(e,"utf-8"):null)===t){n.unchanged.push(e);return}pu(e,t),n.written.push(e)}function Ov(e,t,n){du(mu(e),{recursive:!0});let r=`${JSON.stringify(t,null,2)}
342
- `,i=lu(e)?uu(e,"utf-8"):null;if(i&&Fv(i,r)){n.unchanged.push(e);return}pu(e,r),n.written.push(e)}function Fv(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 Nv(e,t){return zi(e,t)}function zi(e,t){return typeof e=="string"?Mv(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 Mv(e,t){if(e===t)return".";if(!Pv(e))return e;let n=cu(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let r=cu(Cv(),e).replace(/\\/g,"/");return r&&!r.startsWith("..")?`~/${r}`:e}return n}import{spawnSync as _v}from"child_process";import{readFileSync as hu}from"fs";import{dirname as gu,join as qv,resolve as Bv}from"path";import{fileURLToPath as Vv}from"url";var yr={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 Hv(e,t){let n=new Set(["tree-sitter"]);for(let r of e)for(let i of yr[r]?.packages??[])n.add(i);return[...n].filter(r=>t[r]).sort().map(r=>`${r}@${t[r]}`)}function Qi(e){return[...new Set(e.filter(t=>yr[t]!==void 0))].sort()}function yu(e,t={}){let n=t.runtime??Uv,r=t.packageRoot??Wv(),i=Qi(e),o=i.filter(p=>n.probe(yr[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=Gv(r),c=Hv(s,a),l=n.install(r,c);l.ok&&n.resetProbe();let d=i.filter(p=>n.probe(yr[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 Wv(){let e=gu(Vv(import.meta.url));for(;;){let t=qv(e,"package.json");try{if(JSON.parse(hu(t,"utf8")).name==="scip-query")return e}catch{}let n=gu(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function Gv(e){return JSON.parse(hu(Bv(e,"package.json"),"utf8")).optionalDependencies??{}}var Uv={probe:e=>yn(e)==="ast",resetProbe:jo,install:(e,t)=>{let n=_v(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 vu(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 xu(e={}){let t=[],n=Me(),{projectRoot:r,paths:i,dbPath:o}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,a=e.languages?Fa(r,n.config,e.languages):null,c=a?.config??n.config,l=kt(c,{projectRoot:r}),d=l.filter(E=>E.level==="error"),p=null,m=null;if(d.length===0&&c.watch?.enabled!==s)try{p=Na(r,c,s)}catch(E){m=At(E)}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:[]}:Xn({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(E=>`Pruned ${E}`),...h.skipped.map(E=>`Skipped ${E}`)]});let y=p?kt(f,{projectRoot:r}):l,S=y.filter(E=>E.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(E=>`${E.level.toUpperCase()} ${E.path}: ${E.message}`)});let x=ge(r,f);N(t,{id:"readiness",label:"Indexer readiness",status:x.languages.length===0?"failed":x.indexers.some(E=>!E.runnable)?"warn":"ok",message:x.languages.length===0?"No supported project languages detected.":`Detected languages: ${x.languages.join(", ")}`,details:x.indexers.map(E=>`${E.runnable?"OK":E.installed?"WARN":"MISSING"} ${E.language}: ${E.binaryLabel}${E.note?` - ${E.note}`:""}`)});let w=e.installAstParsers===!1?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:yu(x.languages);N(t,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers===!1?"skipped":w.unavailable.length>0?"warn":"ok",message:e.installAstParsers===!1?"Skipped by setup choice.":w.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${w.availableAfter.length}/${w.supportedLanguages.length} selected language parser(s) available${w.installed.length>0?`; installed ${w.installed.join(", ")}`:""}.`,details:[...w.unavailable.length>0?[`Unavailable: ${w.unavailable.join(", ")}`]:[],...w.error?[w.error]:[]]});let R=e.installIndexers??!0,D=R?ix(r,x,t):[];R||N(t,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped by guided setup choice."});let _=ge(r,f),z=await zv({projectRoot:r,paths:i,config:f,readiness:_,configHasErrors:S.length>0,steps:t,onStatus:e.onStatus}),T=z.reindexResult,O=z.freshness,Z=Ce(f),F=Kv({projectRoot:r,cacheDir:i.cacheDir,watchConfig:Z,readiness:_,configHasErrors:S.length>0,reindexResult:T,postReindexFreshness:O,steps:t}),H=ge(r,f),mn=Ke(H),Po=Fe(r,f,i);N(t,{id:"capabilities",label:"Capability matrix",status:dx(mn),message:ux(mn)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let To=e.runHealth===!1?ax(t):await sx(i.dbPath,t),we=H.languages.includes("rust")?Cn(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 ee=null;try{e.noHooks?N(t,{id:"project-hooks",label:"Project agent hooks",status:"skipped",message:"Skipped by --no-hooks."}):(ee=jt(r),N(t,{id:"project-hooks",label:"Project agent hooks",status:ee.skipped.length>0?"warn":"ok",message:`${ee.installed.length} installed, ${ee.updated.length} updated, ${ee.unchanged.length} already configured, ${ee.removed.length} hook config(s) cleaned up, ${ee.skipped.length} skipped.`,details:[...ee.gitExcluded.map(E=>`Checkout-local Git exclude: ${E}`),...ee.removed.map(E=>`Removed ${E}`),...ee.skipped.map(E=>`Skipped ${E.target}: ${E.reason}`),...ee.warnings]}))}catch(E){N(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:At(E)})}let ye=null;try{e.noAgentGuidance?N(t,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(ye=_n(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(E=>`Skipped ${E.target}: ${E.reason}`)}))}catch(E){N(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:At(E)})}let fn=Qv({reindexResult:T,readiness:H,capabilities:mn,freshness:Po,health:To,hooksResult:ee,agentResult:ye,watchConfig:Z,watchService:F,rustSemanticSession:we,steps:t});N(t,{id:"smoke-tests",label:"Setup smoke tests",status:Yv(fn),message:Xv(fn),details:fn.map(E=>`${E.command}: ${E.status} - ${E.evidence}`)});let yf={repository:[...a?.changed?[a.configPath]:[],...p?.changed?[p.configPath]:[],...ye?.written.filter(E=>!E.startsWith(".git/hooks/"))??[]],checkout:[...new Set([...ee?.installed??[],...ee?.updated??[],...ee?.gitExcluded??[],...ye?.written.filter(E=>E.startsWith(".git/hooks/"))??[]])],user:[...h.installed,...w.installed,...D.filter(E=>E.attempted).map(E=>`${E.binaryLabel} installer`)]},Ee={projectRoot:r,dbPath:o,configuredDbPath:i.dbPath,scipCliInstalled:g,languages:H.languages,steps:t,skills:h,astParsers:w,initialReadiness:x,indexerRemediation:D,readiness:H,capabilities:mn,freshness:Po,reindex:T,automaticRefreshConfig:p,watchService:F,rustSemanticSession:we,health:To,smokeTests:fn,healthDossier:null,hooks:ee,setupAgent:ye,changeScopes:yf,filesWritten:ye?.written??[],verdict:Xi(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."}),Ee.verdict=Xi(t,H),Ee;let $e=fu(Ee,{dossierDir:e.dossierDir});return Ee.healthDossier=$e,Ee.changeScopes.repository.push(...$e.written),Ee.filesWritten=[...Ee.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]}),Ee.verdict=Xi(t,H),Ee}async function zv(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 Lt({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=Fe(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:At(i),details:t})}return{reindexResult:n,freshness:r}}function Kv(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=Fn({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:At(n)}),null}}function Ru(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${Ki(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:"),Yi("Repository records (commit)",e.changeScopes.repository),Yi("Checkout preferences (do not commit)",e.changeScopes.checkout),Yi("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 Yi(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function Qv(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:Zv(e.steps),evidence:ex(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?tx(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:bu(e.readiness,e.freshness),evidence:Su(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:bu(e.readiness,e.freshness),evidence:Su(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:nx(e.capabilities),evidence:rx(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 Yv(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function Xv(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 Zv(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function ex(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function tx(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 bu(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function Su(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 nx(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function rx(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 ix(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=cr(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=ox(kn(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 ox(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function sx(e,t){if(!Jv(e)){let n="Skipped because no SQLite index database exists yet.";return N(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Zi(n)}try{let n=await Dn({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).`}),cx(n)}catch(n){let r=At(n);return N(t,{id:"health",label:"Health audit",status:"failed",message:r}),Zi(r)}}function ax(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}),Zi(t)}function cx(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(lx),warnings:e.warnings??[]}}function lx(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 Zi(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function Xi(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 dx(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 ux(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 At(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as px}from"readline";function mx(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function fx(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 ku(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let r=mx(e);px(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
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(`
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
344
  `),n.write(`Use \u2191/\u2193 to move, space to toggle, enter to start. Ctrl-C cancels.
344
345
 
345
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
346
347
  `)}),n.write("\x1B[K")};o(!0);try{return await new Promise((s,a)=>{let c=(d,p)=>{if(p.ctrl&&p.name==="c"){l(),a(new Error("Setup cancelled."));return}if(p.name==="return"||p.name==="enter"){l(),n.write(`
347
- `),s(r.selected);return}let m=p.name==="up"?"up":p.name==="down"?"down":p.name==="space"?"toggle":null;m&&(r=fx(r,m,e),o())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!i),t.pause()}}import{existsSync as wu,mkdirSync as gx,writeFileSync as hx}from"fs";import{dirname as yx,join as $u}from"path";function Cu(e,t={}){let n=$u(e,".github","workflows","scip-query.yml"),r=bx({hasNpmProject:wu($u(e,"package.json"))});return wu(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(gx(yx(n),{recursive:!0}),hx(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function bx(e){let t=`scip-query@${Ne}`;return`name: scip-query
348
+ `),s(r.selected);return}let m=p.name==="up"?"up":p.name==="down"?"down":p.name==="space"?"toggle":null;m&&(r=Vx(r,m,e),o())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!i),t.pause()}}import{existsSync as Ou,mkdirSync as Hx,writeFileSync as Wx}from"fs";import{dirname as Gx,join as Nu}from"path";function Mu(e,t={}){let n=Nu(e,".github","workflows","scip-query.yml"),r=Ux({hasNpmProject:Ou(Nu(e,"package.json"))});return Ou(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(Hx(Gx(n),{recursive:!0}),Wx(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function Ux(e){let t=`scip-query@${Ne}`;return`name: scip-query
348
349
 
349
350
  # Generated by scip-query setup-ci.
350
351
  # Install the language indexers your repository needs before the reindex step
@@ -372,69 +373,70 @@ ${e.hasNpmProject?` - run: npm ci
372
373
  `)+`
373
374
  `} - run: npx ${t} reindex
374
375
  - run: npx ${t} diff-gate --base "origin/\${{ github.base_ref }}"
375
- `}import{existsSync as Sx}from"fs";import{join as br}from"path";function Pu(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=vl({dryRun:e.dryRun,homeDir:e.homeDir})),o&&(s.project=vx(e.projectRoot,{dryRun:e.dryRun})),s}function vx(e,t={}){return{hooks:jt(e,{remove:!0,dryRun:t.dryRun}),agentSetup:Wc(e,{dryRun:t.dryRun}),left:xx(e)}}function xx(e){return[[".scipquery.json",br(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",br(e,".scipquery","suppressions")],[".scipquery/ledger/ (repository records)",br(e,".scipquery","ledger")],["docs/scip-query/",br(e,"docs","scip-query")]].filter(([,t])=>Sx(t)).map(([t])=>t)}import{existsSync as Rx,readFileSync as kx}from"fs";import{createRequire as wx}from"module";import vr from"path";import{performance as Sr}from"perf_hooks";var $x=wx(import.meta.url),sn;function Lu(e){let t=Cx();if(!t)return Tn("typescript is not installed");let n=rs(e);if(n.length===0)return Tn("no tsconfig found");try{return new eo(e.config.projectRoot,t,n.map(r=>Px(t,r)))}catch(r){return Tn(r instanceof Error?r.message:String(r),n[0],n)}}function Au(e,t,n){let r=Sr.now(),i=Tu(t,e),o=Sr.now()-r,s=Sr.now(),a=Tu(n,e),c=Sr.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 x=Iu(y),w=Iu(S),R=ju(y,w),D=ju(S,x);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 eo=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=vr.join(this.projectRoot,t.relativePath),r=this.bundleForFile(n);if(!r)return[];let i=r.service.getProgram()?.getSourceFile(n);if(!i)return[];let o=Ix(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=jx(this.ts,r.service,this.projectRoot,l);d&&(d.file===t.relativePath&&d.line>=t.startLine&&d.line<=t.endLine||a.push(d))}return ts(a)}bundleForFile(t){let n=Ou(t);return this.bundles.find(r=>r.files.has(n))??null}};function Cx(){if(sn!==void 0)return sn;try{sn=$x("typescript")}catch{sn=null}return sn}function Px(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(Eu(e,n.error));let r=e.parseJsonConfigFileContent(n.config,e.sys,vr.dirname(t));if(r.errors.length>0)throw new Error(r.errors.map(s=>Eu(e,s)).join(`
376
- `));let i=new Set(r.fileNames.map(Ou)),o=e.createLanguageService(Tx(e,r),e.createDocumentRegistry());return{tsconfigPath:t,service:o,files:i}}function Tx(e,t){return{getCompilationSettings:()=>t.options,getCurrentDirectory:()=>t.options.configFilePath?vr.dirname(String(t.options.configFilePath)):process.cwd(),getDefaultLibFileName:n=>e.getDefaultLibFilePath(n),getDirectories:e.sys.getDirectories,getScriptFileNames:()=>t.fileNames,getScriptSnapshot:n=>{if(Rx(n))return e.ScriptSnapshot.fromString(kx(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 Ix(e,t,n){let r=t.text.split(`
377
- `),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 jx(e,t,n,r){let i=ns(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 Tu(e,t){return e.referencesForDefinitions?e.referencesForDefinitions(t):new Map(t.map(n=>[n.symbolId,e.referencesFor(n)]))}function Iu(e){return new Set(e.map(Du))}function ju(e,t){return e.filter(n=>!t.has(Du(n)))}function Du(e){return`${e.file}:${e.line}:${e.column}`}function Ou(e){return vr.resolve(e).replace(/\\/g,"/")}function Eu(e,t){return e.flattenDiagnosticMessageText(t.messageText,`
378
- `)}import{readFileSync as Ex}from"fs";function Fu(e){let t=[];for(let[n,r]of Ex(e,"utf8").split(`
379
- `).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 Nu(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 x=he(S.name)??he(S.phase),w=Mx(S.durationMs),R=he(S.runId);x&&w!==null&&(l+=1,s.add(x),R&&o.add(R),Lx(i,S,x,w),Ax(r,S,x,w,R),he(S.subsystemWorkIdentity)&&c.add(x));let D=he(S.workIdentity);if(!D)continue;d+=1,x&&a.add(x);let _=Nx(S.workOutcome);if(!x||w===null||!_){p+=1;continue}let z=R??`unknown-run-${y}`,T=JSON.stringify([x,D]),O=n.get(T)??{spanName:x,workIdentity:D,observations:[]};O.observations.push({runId:z,command:he(S.command)??"unknown",durationMs:w,outcome:_}),n.set(T,O)}let m=[...n.values()].map(Fx).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(Dx).filter(y=>y!==null).sort((y,S)=>S.laterRunMs-y.laterRunMs||S.laterRunEvents-y.laterRunEvents||y.spanName.localeCompare(S.spanName)),g=[...i.values()].map(Ox).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 Mu(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(`
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(`
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,`
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
381
  `)}
381
- `}function Lx(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 Ax(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 Dx(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 Ox(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 Fx(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:xr(e.observations,"cache-hit"),cacheMisses:xr(e.observations,"cache-miss"),reused:xr(e.observations,"reused"),skipped:xr(e.observations,"skipped")}}function Nx(e){switch(e){case"computed":case"cache-hit":case"cache-miss":case"reused":case"skipped":return e;default:return null}}function xr(e,t){return e.filter(n=>n.outcome===t).length}function Mx(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 _u={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 qu(e,t){let n=_x(t);return{...e,warnings:[...e.warnings??[],_u.note,...n],capabilities:t,scoreInterpretation:_u}}function _x(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 Jx=new Set(Da),zx=18e4,Wu=100*1024*1024,Kx=new Set(Eo),Qx=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],Yx=[["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 Xx(e){return e.filter(t=>Jx.has(t))}async function Gu(e){let t=G(e),n=Y(),r=me(n),i=De(n,r),o=b(t,"json");try{let s=Xx(Ct(t,"language")),a=await Lt({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 Uu(){let e=Y(),t=wt(e);try{let n=er({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 Ju(e){let t=G(e),n=Y(),r=wt(n);try{let i=qi({projectRoot:n,dbPath:r,tsconfig:k(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 zu(e){let t=G(e);ce(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=Ys(n,{base:k(t,"base")}),o=Xs(n,r,i.changedFiles,i.changedRanges);console.log(JSON.stringify(o))})}async function Ku(e){let t=G(e);try{let n=await sc({base:k(t,"base")});if(b(t,"json")){I("diff-impact",[],t,n);return}ac(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Qu(e,t){let n=G(t),r=String(e).split(",").filter(i=>i.length>0);ce(i=>{let o=[];for(let c of r)Pa.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:k(n,"scope"),full:b(n,"full")},a=o.length===1?Ta(i,o[0],s):Ia(i,o,s);console.log(JSON.stringify(a))})}async function Yu(e){let t=G(e);if(b(t,"writeBaseline")||b(t,"baseline")){pR(t);return}try{let n=await Dn({scope:k(t,"scope"),full:b(t,"full"),json:b(t,"json")}),{projectRoot:r,config:i,dbPath:o}=Me(),s=Ke(ge(r,i),{hasIndexedGraph:ke(o)}),a=qu(n,s);if(b(t,"json")){I("health",[],t,a);return}oc(a,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function Xu(e){let t=G(e),n=Y(),r=U(t,"timeoutMs")??zx,i=b(t,"progress"),o=b(t,"profile"),s=k(t,"profileOut"),a={projectRoot:n,...cR(n),index:to(ke(wt(n))),commands:[]};b(t,"coldIndex")&&(Ot(i,"cold index started"),a.coldIndex=await Zx(n),Ot(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),Ot(i,"warm index started"),a.warmIndex=await rR(n),Ot(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=to(ke(wt(n))));for(let c of iR(t))a.commands.push(sR(n,c,r,{progress:i,profile:o,profileOut:s}));if(b(t,"json")){I("bench",[],t,a);return}lR(a)}function Zu(e,t){let n=G(t),r=Ux(String(e)),i=Nu(Fu(r),{top:U(n,"top")??20});if(b(n,"json")){I("work-audit",[r],n,{profilePath:r,...i});return}process.stdout.write(Mu(i,r))}function ep(e){let t=G(e);ce(n=>{let r=n.config.projectRoot,i=k(t,"scope")??null,o=b(t,"full"),s=U(t,"limit")??200,a=Math.max(0,U(t,"maxMismatches")??10),c=Fo(n).filter(w=>Ht(w.relativePath)).filter(w=>!n.isIgnored(w.relativePath)).sort(uR),l=i?c.filter(w=>w.relativePath.includes(i)):c,d=o?l:l.slice(0,s),p=et.now(),m=os(n),f=Number((et.now()-p).toFixed(3)),g=et.now(),h=Lu(n),y=Number((et.now()-g).toFixed(3)),S=Au(d,m,h),x={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,x);return}dR(x)})}async function Zx(e){let t=me(e),n=De(e,t),r=Rr(n.dbPath),i=`${r}.bench-backup-${Date.now()}`;eR(r);let o=tR(r,i);try{let s=await tp(()=>Lt({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 Bu(r,i,o,"discard-backup"),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...np(e)}}catch(s){throw Bu(r,i,o,"restore-backup"),s}}var no={existsSync:ke,readFileSync:qx,writeFileSync:Wx,renameSync:Bx,rmSync:Vx,unlinkSync:Hx};function ro(e){return mt(Rr(e),"bench-restore.json")}function eR(e,t=no){let n=ro(e);if(!t.existsSync(n))return!1;let r=nR(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 tR(e,t,n=no){return n.existsSync(e)?(n.writeFileSync(ro(e),JSON.stringify({originalPath:e,backupPath:t})),n.renameSync(e,t),!0):!1}function Bu(e,t,n,r,i=no){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=ro(e);i.existsSync(o)&&i.unlinkSync(o)}function nR(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 rR(e){let t=me(e),n=De(e,t),r=await tp(()=>Lt({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,...np(e)}}async function tp(e){let t=et.now(),n=await e();return{durationMs:Math.round(et.now()-t),value:n}}function np(e){return ke(wt(e))?ce(t=>{let n=vt(t);return{files:n.documents,symbols:n.symbols}}):{}}function iR(e){let t=Ct(e,"command");return t.length>0?t.map(oR).filter(n=>n.length>0):[...Qx.map(n=>[...n]),...b(e,"includeHeavy")?Yx.map(n=>[...n]):[]]}function oR(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function sR(e,t,n,r={}){let i=`scip-query ${t.join(" ")}`;Ot(r.progress,`${i} started`),qt({type:"bench-command-start",command:i,projectRoot:e},r.profileOut);let o=et.now(),s={...r.profile?aR(i,r.profileOut):process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"},a=Hu(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:Wu,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 Ot(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 Ot(e,t){e&&process.stderr.write(`[bench] ${t}
382
- `)}function aR(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function cR(e){let t=Hu("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:Wu});if(t.status!==0)return{repoFiles:null,sourceFiles:null};let n=t.stdout.split(`
383
- `).filter(Boolean);return{repoFiles:n.length,sourceFiles:n.filter(r=>Kx.has(Gx(r).toLowerCase())).length}}function lR(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, ${Je(e.index.indexSizeBytes)}`),e.coldIndex&&Vu("Cold index",e.coldIndex),e.warmIndex&&Vu("Warm index",e.warmIndex),console.log(`
384
- 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 Vu(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function dR(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(`
385
- Mismatch samples:`);for(let t of e.comparison.mismatches)console.log(` ${t.symbol}`),console.log(` missing=${t.missing.length} extra=${t.extra.length}`)}}function uR(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||(e.startChar??0)-(t.startChar??0)||e.symbolId-t.symbolId}function pR(e){let t=k(e,"scope");ce(n=>{if(b(e,"writeBaseline")){let i=sa(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=aa(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 rp(){let e=Xn(),t=e.installed.length+e.alreadyLinked.length;console.log(`
386
- ${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 ip(e){let t=G(e),n=Y(),r=jt(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(`
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}
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
+ `).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
+ 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(`
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(`
387
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(`
388
- No project-local hook config was written.`)}function op(){let e=!1;Xt()?console.log("scip CLI: installed"):(mi(),e=!0);let t=Y(),n=me(t),r=ge(t,n);if(r.languages.length===0){console.log(`
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(`
389
390
  No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
390
391
  Detected languages: ${r.languages.join(", ")}`),console.log(`
391
- 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=kp(r);i.length>0&&console.log(`
392
- Semantic provider readiness:`);for(let o of i){let s=o.available?" OK":o.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${o.language}: ${RR(o)}${wp(o)}`),o.reason&&console.log(` ${o.reason}`)}process.exitCode=e?1:0}function sp(e){cp(e,"capabilities")}function ap(e){b(G(e),"json")||console.error('note: capability-matrix is deprecated; use "scip-query capabilities --matrix".'),cp(e,"capability-matrix")}function cp(e,t){let n=G(e),{projectRoot:r,config:i,paths:o,dbPath:s}=Me(),a=ge(r,i),c=Fe(r,i,o),l=Ke(a,{hasIndexedGraph:ke(s)&&c.state!=="missing"});if(b(n,"json")){I(t,[],n,l);return}io(l)}function lp(){let e=Y(),t=rt(e),n=Oa(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function dp(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 up(e,t){let n=G(t),r=k(n,"reason");if(!r||r.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let i=da(Y(),{id:String(e),check:k(n,"check"),file:k(n,"file"),reason:r,expiresAt:k(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 pp(e){let t=G(e),n=Date.now(),r=k(t,"since"),i;if(r){let y=su(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=Wn(o),a=ou(s,{sinceMs:i,check:k(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(Hn,"*.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(x=>x[S].length))),p=y=>y.map((S,x)=>S.padEnd(d[x])).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(`
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
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(`
394
- ${g} finding(s) disappeared without comparable comparison-base evidence; precision is not available.`)}function mp(e){let t=G(e),{report:n,hasIndexerProblems:r,hasErrors:i}=fp("doctor");b(t,"json")?I("doctor",[],t,n):bR(n,r),process.exitCode=i?1:0}function fp(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=Me(),o=kt(n,{projectRoot:t}),s=ge(t,n),a=Fe(t,n,r),c=ke(i),l=Ke(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=Rc(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 gp(e){let t=G(e),n=Y(),r=_n(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(`
395
- 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 hp(e){let t=G(e);try{let n={gitHook:b(t,"gitHook"),noHooks:b(t,"noHooks")||t.hooks===!1,dossierDir:k(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 mR(n,{json:b(t,"json")})),r||(n.onStatus=s=>console.log(` ${s}`));let o=await xu(n);b(t,"json")?I("setup",[],t,o):Ru(o),process.exitCode=o.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function mR(e,t){let{projectRoot:n,config:r}=Me(),i=ge(n,r),o=vu({files:fR(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=Qi(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 ku([...s,...a]):new Set([...gR(o.actions),...s.map(g=>g.id)]);l&&hR(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 fR(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 gR(e){return new Set([...e.filter(t=>t.recommended).map(t=>t.id),"install-agent-skills","install-ast-parsers"])}function hR(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 yp(e){let t=G(e),n=Y(),r=Cu(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 bp(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=Pu({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 Sp(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=De(n,r),S={projectRoot:n,cacheDir:y.cacheDir,cliVersion:Ne,watchOverrides:g};if(l){let R=vp(zr(S),h.enabled);p?I("watch",[],t,R):xp(R);return}if(d){try{let R=Sc(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=Fn(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 x=xc(mt(Rr(y.dbPath),Yo),n);if(!x.acquired){console.error(x.message),process.exitCode=1;return}let w=new hr({projectRoot:n,config:r,languages:r.languages,onStatus:R=>{process.stdout.write(`\r\x1B[K${Gr(R)}`)},onReindexComplete:R=>{console.log(`
396
- Reindex complete in ${(R/1e3).toFixed(1)}s`)},onError:R=>{console.error(`
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(`
397
+ Reindex complete in ${(R/1e3).toFixed(1)}s`),Pe(n,r,y).state==="fresh"),onRefreshSuppressed:R=>{ed(y.dbPath,R),console.log(`
398
+ Skipped redundant refresh; the completed index already includes the queued changes.`)},onError:R=>{console.error(`
397
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.
398
- `),w.start(),process.on("SIGINT",()=>{w.stop(),x.release(),console.log(`
399
- Stopped.`),process.exit(0)}),process.once("exit",x.release)}function vp(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,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,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};default:return yR(n)}}function xp(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: ${Gr(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}`),"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 yR(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function Rp(e){let t=G(e),{report:n}=fp("status"),r=Ce(me(n.projectRoot)).enabled,i=vp(zr({projectRoot:n.projectRoot,cacheDir:Rr(n.configuredDbPath),cliVersion:Ne}),r),o=Ll(n.dbPath),s=it(n.dbPath,n.freshness.metaPath),a=Cn(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:to(n.exists)});return}SR(n,{affectedSetShadow:o,capabilities:b(t,"capabilities"),sqliteGeneration:s,rustSemanticSession:a,watchService:i})}function bR(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})`:""}`),io(e.capabilities)}function SR(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 kp(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}${wp(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: ${kR(e.freshness.lastRefresh)}`),xp(t.watchService),vR(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"),xR(t.sqliteGeneration),console.log(`Shadow: ${Al(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),wR(e.exists),t.capabilities&&(console.log(""),io(e.capabilities))}function vR(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), ${Je(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${Je(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), ${Je(e.cleanup.deletedBytes??0)} removed`)}function xR(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 kp(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function RR(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function wp(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function kR(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 to(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 wR(e){e&&ce(t=>{let n=vt(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${Je(n.indexSizeBytes)}`),n.lastBuilt){let r=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${r}s ago`)}})}function io(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(`
400
- 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 an(e){return{...e,options:P(e.options)}}function Ie({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,...a}){let c=an(a);return{...c,renderShape:"list",handler:lc({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s})}}function kr({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c,...l}){let d=an(l);return{...d,renderShape:"table",handler:dc({commandName:d.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c})}}function $p({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a,...c}){let l=an(c);return{...l,renderShape:"grouped-by-file",handler:uc({commandName:l.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a})}}function Cp({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=an(a);return{...c,renderShape:"sectioned-report",handler:pc({commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}function wr({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=an(a);return{...c,budget:c.budget??"semantic",renderShape:"sectioned-report",handler:mc(c.id,{commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}import{existsSync as nk,mkdirSync as rk,writeFileSync as ik}from"fs";import{dirname as ok,relative as sk}from"path";import{existsSync as Ge,readdirSync as jR,readFileSync as ft}from"fs";import{basename as ER,dirname as Ap,isAbsolute as Dp,join as LR,relative as AR,resolve as cn,sep as DR}from"path";import{spawnSync as CR}from"child_process";import{dirname as PR}from"path";function Tp(e){let n=(e.spawnSync??CR)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:PR(e.specPath),maxBuffer:1024*1024*32});if(n.status!==0)return null;let r=n.stdout??"";return r.includes("<?xml")?r:null}function Ip(e){let t=IR(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=jp(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 TR=8;function IR(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=oo(s,"uniquename"),c=oo(s,"kind"),l=oo(s,"filename");t.push({uid:r[1],type:r[2],uniquename:a===null?null:Pp(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:Pp(l),block:s})}return t}function jp(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<TR&&!o.has(f.uid)&&f.filename===i){let g=jp(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 oo(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function Pp(e){return e.replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}var Op=["update","insert","delete"],Fp=["select","query","findFirst","findMany"],so=new Set([...Op,...Fp]);function ao(e){let t=e.methods&&e.methods.length>0?e.methods:[...so],n=new Set(Op),r=new Set(Fp);return{write:t.filter(i=>n.has(i)),read:t.filter(i=>r.has(i))}}var OR=/^(.*)@L(\d+)-L(\d+)$/;function co(e){let t=e.match(OR);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 FR=new Set(["auto","sany","tlc","apalache","none"]),Cr=/^[A-Za-z_][A-Za-z0-9_]*$/;function Np(e){return FR.has(e)}function Pr(e,t){let n=[],r=ue(e,t);if(!r)return{errors:[`map path escapes project root: ${t}`]};if(!Ge(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=NR(i,n);return o?{loaded:{contract:o,mapPath:r,mapDir:Ap(r)},errors:n}:{errors:n}}function ue(e,t){if(!t)return null;let n=Dp(t)?cn(t):cn(e,t);return pe(e,n)?n:null}function Mp(e,t,n){if(!n)return null;if(Dp(n)){let s=cn(n);return pe(e,s)?s:null}let r=cn(e,n);if(pe(e,r)&&Ge(r))return r;let i=cn(t,n);if(pe(e,i)&&Ge(i))return i;let o=pe(e,r)?r:i;return pe(e,o)?o:null}function _p(e,t){let n=ue(e,t);if(!n||!Ge(n))return null;let r=ft(n,"utf8");return{path:n,modelParse:"regex-fallback",text:r,variables:YR(r),operators:XR(r),actions:[]}}function qp(e,t,n){let r=ue(e,t);if(!r||!Ge(r))return null;let i=ft(r,"utf8"),o=Ip(n);return{path:r,modelParse:"sany",text:i,variables:o.variables,operators:o.operators,actions:o.actions}}function lo(e,t){let n=ue(e,t);if(!n)return{steps:[],errors:[`trace path escapes project root: ${t}`]};if(!Ge(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 uo(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 NR(e,t){if(!q(e))return t.push("map file must contain a JSON object"),null;let n=HR(e.variables,t);VR(n,t);let r=KR(e.actions,n,t),i=MR(e.init,t);qR(i,r,t);let o={module:Lp(e.module,"module",t),config:Lp(e.config,"config",t),scope:J(e.scope)??[],variables:n,actions:r,...i?{init:i}:{},invariants:J(e.invariants)??[],traces:J(e.traces)??[],unmappedWriteScope:BR(e.unmappedWriteScope,t)};return ek(e.scope,t),t.length===0?o:null}function MR(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=_R(e.waive,t);return{codeRefs:n,...r?{waive:r}:{}}}function _R(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 qR(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 BR(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 VR(e,t){$r(e,t,"alias",n=>n.aliases),$r(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),$r(e,t,"statement pattern",n=>n.statements?n.statements.map(r=>r.pattern):[]),$r(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(r=>{let{write:i,read:o}=ao(r);return[...i,...o].map(s=>`${r.table}:${s}`)}))}function $r(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 HR(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(!Cr.test(r)){t.push(`invalid TLA+ variable name: ${r}`);continue}if(!q(i)){t.push(`variables.${r} must be an object`);continue}let o=Vp(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=GR(i.resource,r,t),c=UR(i.statements,r,t),l=JR(i.ormCalls,r,t),d=zR(i.waive,r,t),p=WR(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 WR(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 GR(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 UR(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 JR(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=>!so.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${o}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...so].join(", ")}`);return}r.push(a.length>0?{table:s,methods:a}:{table:s})}),r.length>0?r:void 0}function zR(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 KR(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(!Cr.test(o)){n.push(`invalid TLA+ action name: ${o}`);continue}if(!q(s)){n.push(`actions.${o} must be an object`);continue}let a=Vp(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=co(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=QR(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 QR(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`),Ep(o,"reads",c,i,s),Ep(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 Ep(e,t,n,r,i){for(let o of n)r.has(o)||i.push(`actions.${e}.waive.${t} references unknown variable: ${o}`)}function YR(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();Cr.test(o)&&t.add(o)}}return[...t].sort()}function XR(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 ZR=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function Bp(e){if(!e||!Ge(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(ZR.has(i)){r=i==="INVARIANT"||i==="INVARIANTS";continue}r&&Cr.test(i)&&n.add(i)}return[...n].sort()}function Lp(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function Vp(e){return typeof e=="string"?[e]:J(e)}function ek(e,t){e!==void 0&&(J(e)||t.push("scope must be an array of strings when present"))}function Tr(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var tk=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function Hp(e,t){if(!Ge(t))return{status:"none"};let r=ft(t,"utf8").match(tk)?.[1],i=AR(e,t).split(DR).join("/"),o=ER(t),s=new Set([r,i,o,o.replace(/\.tla$/i,"")].filter(d=>!!d)),a=Ap(t);if(!Ge(a))return{status:"none"};let c=[];for(let d of jR(a)){if(!d.endsWith(".scip-tla.json"))continue;let p=LR(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 Ir(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 po=20,Wp=K("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:B(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=gs(e,i),s=o.symbols.filter(F=>F.kind==="dead-code"),a=o.symbols.filter(F=>F.kind==="file-internal"),c=o.symbols.filter(F=>F.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((F,H)=>F+H.loc,0),y=f.reduce((F,H)=>F+H.loc,0),S=g.reduce((F,H)=>F+H.loc,0),x=b(n,"full"),w=x?m:m.slice(0,po),R=x?f:f.slice(0,po),D=x?g:g.slice(0,po),_=w.reduce((F,H)=>F+H.loc,0),z=R.reduce((F,H)=>F+H.loc,0),T=D.reduce((F,H)=>F+H.loc,0),O={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:O,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){j.empty("No matching dead-code symbols found.");return}m.length>0&&(Ir(w,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
401
- Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,_,{count:m.length,loc:h}),!x&&m.length>w.length&&console.log(`
402
- Showing top ${w.length} by LOC. Re-run with --full for the remaining ${m.length-w.length}.`)),f.length>0&&(m.length>0&&console.log(""),Ir(R,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
400
+ `),k.start(),process.on("SIGINT",()=>{k.stop(),v.release(),console.log(`
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(`
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
403
405
  single-use helper, an abstraction-in-progress, or a callback registered
404
406
  through a framework path that static analysis cannot trace (signal
405
407
  handlers, event listeners, dependency injection). NOT necessarily dead \u2014
406
- review case by case.`,z,{count:f.length,loc:y}),!x&&f.length>R.length&&console.log(`
407
- Showing top ${R.length} by LOC. Re-run with --full for the remaining ${f.length-R.length}.`)),g.length>0&&((m.length>0||f.length>0)&&console.log(""),Ir(D,"IMPLICIT USAGE",` Traits, macros, attributes, ABI exports, or reflection provide a
408
+ review case by case.`,z,{count:f.length,loc:y}),!v&&f.length>R.length&&console.log(`
409
+ Showing top ${R.length} by LOC. Re-run with --full for the remaining ${f.length-R.length}.`)),g.length>0&&((m.length>0||f.length>0)&&console.log(""),jr(D,"IMPLICIT USAGE",` Traits, macros, attributes, ABI exports, or reflection provide a
408
410
  consumer that the static reference graph cannot trace. Investigation
409
- signals only \u2014 not deletion candidates and not counted as dead code.`,T,{count:g.length,loc:S}),!x&&g.length>D.length&&console.log(`
411
+ signals only \u2014 not deletion candidates and not counted as dead code.`,T,{count:g.length,loc:S}),!v&&g.length>D.length&&console.log(`
410
412
  Showing top ${D.length} by LOC. Re-run with --full for the remaining ${g.length-D.length}.`));let Z=[];l&&Z.push(`${m.length} dead code (${h} LOC)`),d&&Z.push(`${f.length} file-internal (${y} LOC)`),p&&Z.push(`${g.length} implicit usage (${S} LOC)`),console.log(`
411
- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${m.length+f.length+g.length} symbols \u2014 ${Z.join(" + ")}`)}),Gp=de("unused-imports",{query:({db:e,args:t,budget:n})=>Ss(e,L(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
412
- ${e.length} unused import(s)`)}),Up=fc("isolated",{query:({db:e,opts:t,budget:n})=>js(e,{scope:k(t,"scope"),minLoc:C(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ie(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
413
- ${e.length} isolated symbol(s)`)}),Jp=K("extract-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Us(e,{scope:k(n,"scope"),minLoc:C(n,"minLoc",10),minCallees:C(n,"minCallees",6),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(b(n,"json")){I("extract-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return j.empty("No extraction candidates found.");Pe("extraction candidates");for(let o of i){console.log(`
413
+ \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${m.length+f.length+g.length} symbols \u2014 ${Z.join(" + ")}`)}),rm=de("unused-imports",{query:({db:e,args:t,budget:n})=>ws(e,A(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
414
+ ${e.length} unused import(s)`)}),im=Sc("isolated",{query:({db:e,opts:t,budget:n})=>Fs(e,{scope:w(t,"scope"),minLoc:C(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${ie(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
415
+ ${e.length} isolated symbol(s)`)}),om=K("extract-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Ys(e,{scope:w(n,"scope"),minLoc:C(n,"minLoc",10),minCallees:C(n,"minCallees",6),limit:L(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(b(n,"json")){I("extract-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return E.empty("No extraction candidates found.");Te("extraction candidates");for(let o of i){console.log(`
414
416
  ${M(o.relativePath,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC, ${o.totalCallees} callees)`),console.log(` Kind: ${o.extractionKind}; tier: ${o.actionTier}`),console.log(` Recommendation: ${o.recommendation}`);for(let s of o.evidenceReasons)console.log(` - ${s}`);for(let s=0;s<o.clusters.length;s++){let a=o.clusters[s];console.log(` Cluster ${s+1} (${Math.round(a.isolation*100)}% isolated, ${a.callees.length} callees):`);for(let c of a.callees)console.log(` ${c}`)}}console.log(`
415
- ${i.length} extraction candidate(s) found.`)}),zp=K("locality-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Js(e,{target:B(t,0)||void 0,scope:k(n,"scope"),minConsumers:C(n,"minConsumers",1),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(b(n,"json")){I("locality-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return j.empty("No locality candidates found.");Pe("locality candidates");for(let o of i){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?M(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
417
+ ${i.length} extraction candidate(s) found.`)}),sm=K("locality-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Xs(e,{target:V(t,0)||void 0,scope:w(n,"scope"),minConsumers:C(n,"minConsumers",1),limit:L(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(b(n,"json")){I("locality-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return E.empty("No locality candidates found.");Te("locality candidates");for(let o of i){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?M(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
416
418
  ${s} ${o.sourceUnit.shortName}`),console.log(` Current directory: ${o.currentDirectory}; tier: ${o.recommendedTier}; action: ${o.actionTier}`),console.log(` Consumer coverage: ${o.consumerCoverage}; consumers: ${o.consumerFiles.length}`),o.nearestCommonOwner&&console.log(` Nearest common owner: ${o.nearestCommonOwner}`),o.suggestedHome&&console.log(` Suggested home: ${o.suggestedHome}`),o.whyNoSuggestedHome&&console.log(` Suggested home withheld: ${o.whyNoSuggestedHome}`),o.boundaryMarkers.length>0&&console.log(` Boundary markers: ${o.boundaryMarkers.join("; ")}`),console.log(` Recommendation: ${o.recommendation}`),o.consumerFiles.length>0){for(let a of o.consumerFiles.slice(0,8))console.log(` - consumer: ${a}`);o.consumerFiles.length>8&&console.log(` - ... ${o.consumerFiles.length-8} more consumer(s)`)}for(let a of o.counterevidence)console.log(` - counterevidence: ${a}`)}console.log(`
417
- ${i.length} locality candidate(s) found.`)}),Kp=de("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>oa(e,{scope:k(t,"scope"),maxLoc:C(t,"maxLoc",15),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
419
+ ${i.length} locality candidate(s) found.`)}),am=de("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>da(e,{scope:w(t,"scope"),maxLoc:C(t,"maxLoc",15),limit:L(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
418
420
  Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
419
421
  Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
420
- ${e.length} wrapper candidate(s).`)}),Qp=de("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>ra(e,{scope:k(t,"scope"),maxLoc:C(t,"maxLoc",15),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
422
+ ${e.length} wrapper candidate(s).`)}),cm=de("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>ca(e,{scope:w(t,"scope"),maxLoc:C(t,"maxLoc",15),limit:L(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
421
423
  Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
422
424
  Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
423
425
  Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
424
426
  Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
425
- ${e.length} passthrough candidate(s).`)}),Yp=de("stale-abstractions",{query:({db:e,opts:t,budget:n})=>ia(e,{scope:k(t,"scope"),minLoc:C(t,"minLoc",3),limit:A(t,"limit",30),includeLowConfidence:b(t,"includeLowConfidence"),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.consumers===0?"unused":`${e.consumers} consumer`,n=e.barrelConsumers>0?`, +${e.barrelConsumers} barrel`:"";return` [${e.confidence}] ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
427
+ ${e.length} passthrough candidate(s).`)}),lm=de("stale-abstractions",{query:({db:e,opts:t,budget:n})=>la(e,{scope:w(t,"scope"),minLoc:C(t,"minLoc",3),limit:L(t,"limit",30),includeLowConfidence:b(t,"includeLowConfidence"),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.consumers===0?"unused":`${e.consumers} consumer`,n=e.barrelConsumers>0?`, +${e.barrelConsumers} barrel`:"";return` [${e.confidence}] ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
426
428
  ${e.reason}
427
429
  Kind: ${e.stalenessKind}; tier: ${e.actionTier}
428
430
  Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
429
- ${e.length} stale abstraction(s).`)}),Xp=On("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>xa(e,{scope:k(t,"scope"),minLoc:C(t,"minLoc",10),limit:A(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]}),Zp=Se("similar",{query:({db:e,args:t,opts:n,budget:r})=>{if(b(n,"plan")){let o=B(t,0),s=B(t,1);if(!o||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:Fs(e,o,s,{scanLimit:r.scanLimit,semantic:r.semantic})}}let i=B(t,0);return i?{mode:"target",rows:Os(e,i,{minSimilarity:C(n,"minSimilarity",.4),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:Ns(e,{minSimilarity:C(n,"minSimilarity",.4),limit:A(n,"limit",20),scope:k(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: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(`
430
432
  ${Math.round(t.similarity*100)}% ${n}
431
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}
432
434
  `),console.log(` Shared evidence (${t.sharedEvidence.length}):`);for(let r of t.sharedEvidence)console.log(` ${r}`);if(t.uniqueToA.length>0){console.log(`
433
435
  Unique to A (${t.uniqueToA.length}):`);for(let r of t.uniqueToA)console.log(` ${r}`)}if(t.uniqueToB.length>0){console.log(`
434
436
  Unique to B (${t.uniqueToB.length}):`);for(let r of t.uniqueToB)console.log(` ${r}`)}console.log(`
435
- Strategy: ${t.consolidationStrategy}`);return}if(e.mode==="target"){j.list(e.rows,t=>{let n=t.similarityBasis??"callees",r=n==="source-tokens"?"Shared source tokens":"Shared callees",i=n==="source-tokens"?"Only tokens in":"Only in",o=[`
437
+ Strategy: ${t.consolidationStrategy}`);return}if(e.mode==="target"){E.list(e.rows,t=>{let n=t.similarityBasis??"callees",r=n==="source-tokens"?"Shared source tokens":"Shared callees",i=n==="source-tokens"?"Only tokens in":"Only in",o=[`
436
438
  ${Math.round(t.similarity*100)}% similar:`,` A: ${t.shortNameA} (${t.fileA})`,` B: ${t.shortNameB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${r}: ${t.sharedCallees.join(", ")}`];return t.evidenceClassReasons.length&&o.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.uniqueToA.length&&o.push(` ${i} A: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&o.push(` ${i} B: ${t.uniqueToB.join(", ")}`),o.join(`
437
- `)});return}j.list(e.rows,t=>`
439
+ `)});return}E.list(e.rows,t=>`
438
440
  ${Math.round(t.similarity*100)}% similar:
439
441
  A: ${t.shortNameA} (${t.fileA})
440
442
  B: ${t.shortNameB} (${t.fileB})
@@ -442,113 +444,113 @@ ${Math.round(t.similarity*100)}% similar:
442
444
  Recommendation: ${t.recommendation}
443
445
  `+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
444
446
  `:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
445
- ${e.rows.length} similar pair(s) found.`)}}),em=ze({commandName:"similar-files",query:({db:e,args:t,opts:n})=>Ms(e,{minSimilarity:C(n,"minSimilarity",.5),limit:A(n,"limit",20),scope:k(n,"scope"),minDeps:U(n,"minDeps"),filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{j.list(e,t=>{let n=[`
447
+ ${e.rows.length} similar pair(s) found.`)}}),pm=Ke({commandName:"similar-files",query:({db:e,args:t,opts:n})=>Hs(e,{minSimilarity:C(n,"minSimilarity",.5),limit:L(n,"limit",20),scope:w(n,"scope"),minDeps:U(n,"minDeps"),filePattern:V(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{E.list(e,t=>{let n=[`
446
448
  ${Math.round(t.similarity*100)}% similar:`,` ${t.fileA}`,` ${t.fileB}`,` Shared deps (${t.sharedDeps.length}): ${t.sharedDeps.join(", ")}`];return t.uniqueToA.length&&n.push(` Only in first: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&n.push(` Only in second: ${t.uniqueToB.join(", ")}`),n.join(`
447
449
  `)}),console.log(`
448
- ${e.length} similar pair(s) found.`)}}),tm=ze({commandName:"similar-chains",query:({db:e,opts:t})=>Gs(e,{minSimilarity:C(t,"minSimilarity",.5),limit:A(t,"limit",15),scope:k(t,"scope"),minChainLength:C(t,"minLength",3),maxChainLength:C(t,"maxLength",8)}),emptyMessage:e=>e.length===0?"No similar chains found.":void 0,heuristicLabel:"similar chain candidates",render:e=>{for(let t=0;t<e.length;t++){let n=e[t];console.log(`
450
+ ${e.length} similar pair(s) found.`)}}),mm=Ke({commandName:"similar-chains",query:({db:e,opts:t})=>Qs(e,{minSimilarity:C(t,"minSimilarity",.5),limit:L(t,"limit",15),scope:w(t,"scope"),minChainLength:C(t,"minLength",3),maxChainLength:C(t,"maxLength",8)}),emptyMessage:e=>e.length===0?"No similar chains found.":void 0,heuristicLabel:"similar chain candidates",render:e=>{for(let t=0;t<e.length;t++){let n=e[t];console.log(`
449
451
  \u2500\u2500 Chain pair ${t+1} (${Math.round(n.similarity*100)}% similar, ${n.divergencePoints.length} divergence point(s)) \u2500\u2500`),console.log(` Chain A: ${n.chainA.join(" \u2192 ")}`),console.log(` Chain B: ${n.chainB.join(" \u2192 ")}`),n.commonPrefix.length&&console.log(` Common prefix: ${n.commonPrefix.join(" \u2192 ")}`),n.commonSuffix.length&&console.log(` Common suffix: ${n.commonSuffix.join(" \u2192 ")}`),console.log(" Divergence points (consolidation targets):");for(let r of n.divergencePoints)console.log(` [${r.index}] ${r.nodeA} \u2194 ${r.nodeB}`)}console.log(`
450
- ${e.length} similar chain pair(s) found.`)}}),nm=Se("drift",{query:({db:e,args:t,opts:n,budget:r})=>na(e,{scope:B(t,0),minDeviation:C(n,"minDeviation",5),semantic:r.semantic,includePatternDeviations:b(n,"patterns"),includeArchitecture:b(n,"architecture"),limit:A(n,"limit",50)}),emptyMessage:e=>e.results.length===0&&!e.architecture?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{if(console.log(""),j.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="architecture-violation"||t.kind==="layer-violation"?"ARCH":"UNIQUE",r=t.policyBasis?`, policy: ${t.policyBasis}`:"",i=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${r}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&i.push(` ${t.detail}`),i.join(`
452
+ ${e.length} similar chain pair(s) found.`)}}),fm=Se("drift",{query:({db:e,args:t,opts:n,budget:r})=>aa(e,{scope:V(t,0),minDeviation:C(n,"minDeviation",5),semantic:r.semantic,includePatternDeviations:b(n,"patterns"),includeArchitecture:b(n,"architecture"),limit:L(n,"limit",50)}),emptyMessage:e=>e.results.length===0&&!e.architecture?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{if(console.log(""),E.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="architecture-violation"||t.kind==="layer-violation"?"ARCH":"UNIQUE",r=t.policyBasis?`, policy: ${t.policyBasis}`:"",i=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${r}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&i.push(` ${t.detail}`),i.join(`
451
453
  `)},t=>t.file),e.architecture){let t=e.architecture,n=t.edges.filter(r=>r.policyStatus==="undeclared").length;if(console.log(`
452
454
  Architecture context: ${t.coverage.mappedFiles}/${t.coverage.totalFiles} file(s) mapped; ${t.policyCoverage.declaredRows}/${t.policyCoverage.totalBoundaries} dependency row(s) declared; ${n} undeclared boundary edge(s).`),t.reciprocalPairs.length>0){console.log(` Reciprocal pairs (${t.reciprocalPairs.length}):`);for(let r of t.reciprocalPairs)console.log(` ${r.boundaries[0]} <-> ${r.boundaries[1]}`)}if(t.cycles.length>0){console.log(` Connected boundary groups (${t.cycles.length}):`);for(let r of t.cycles){let i=r.violatesPolicy?" [violates requireAcyclic]":" [signal]";console.log(` { ${r.boundaries.join(", ")} }${i}`)}}}console.log(`
453
- ${e.unusedImports} unused import(s), ${e.architectureViolations} declared architecture violation(s), ${e.patternDeviations} pattern deviation(s)${e.totalResults?` \u2014 showing ${e.results.length} of ${e.totalResults} (use -n to change)`:""}`)}}),rm=Se("convergence",{query:({db:e,args:t,budget:n})=>ja(e,L(t,0),L(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols did not resolve, or the pair has no fingerprint evidence (small helpers with few callees fall below the similarity threshold; try --min-callees 1).",render:e=>{if(e){console.log("\nDeprecated: use `similar <symbol1> <symbol2> --plan` for the same weighted similarity basis."),console.log(`
455
+ ${e.unusedImports} unused import(s), ${e.architectureViolations} declared architecture violation(s), ${e.patternDeviations} pattern deviation(s)${e.totalResults?` \u2014 showing ${e.results.length} of ${e.totalResults} (use -n to change)`:""}`)}}),gm=Se("convergence",{query:({db:e,args:t,budget:n})=>Fa(e,A(t,0),A(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols did not resolve, or the pair has no fingerprint evidence (small helpers with few callees fall below the similarity threshold; try --min-callees 1).",render:e=>{if(e){console.log("\nDeprecated: use `similar <symbol1> <symbol2> --plan` for the same weighted similarity basis."),console.log(`
454
456
  ${Math.round(e.similarity*100)}% callee overlap
455
457
  `),console.log(` A: ${e.symbolA.shortName} (${e.symbolA.file}, ${e.symbolA.loc} LOC)`),console.log(` B: ${e.symbolB.shortName} (${e.symbolB.file}, ${e.symbolB.loc} LOC)
456
458
  `),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
457
459
  Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
458
460
  Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
459
- Strategy: ${e.consolidationStrategy}`)}}}),im=de("similar-signatures",{query:({db:e,opts:t,budget:n})=>Aa(e,{scope:k(t,"scope"),minLoc:C(t,"minLoc",3),maxShapeFrequency:C(t,"maxShapeFrequency",12),limit:A(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
461
+ Strategy: ${e.consolidationStrategy}`)}}}),hm=de("similar-signatures",{query:({db:e,opts:t,budget:n})=>Ma(e,{scope:w(t,"scope"),minLoc:C(t,"minLoc",3),maxShapeFrequency:C(t,"maxShapeFrequency",12),limit:L(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
460
462
  Signature: ${e.signature} (${e.functions.length} functions, ${e.locBand} LOC${t})`,r=e.functions.map(i=>` ${M(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
461
463
  `);return`${n}
462
464
  ${r}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
463
- ${e.length} group(s) found.`)}),om=de("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>ea(e,{scope:k(t,"scope"),maxLoc:C(t,"maxLoc",15),minLoc:C(t,"minLoc",3),limit:A(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
465
+ ${e.length} group(s) found.`)}),ym=de("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>oa(e,{scope:w(t,"scope"),maxLoc:C(t,"maxLoc",15),minLoc:C(t,"minLoc",3),limit:L(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
464
466
  Body hash: ${e.hash} (${e.functions.length} functions)`,n=e.functions.map((r,i)=>` ${(i===0?"canonical":"duplicate").padEnd(9)} ${M(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
465
467
  `);return`${t}
466
468
  ${n}`},emptyMessage:()=>"No exact duplicate function bodies found.",heuristicLabel:"duplicate body candidates",after:e=>console.log(`
467
- ${e.length} group(s) found.`)}),sm=de("twin-drift",{query:({db:e,opts:t,budget:n})=>ta(e,{scope:k(t,"scope"),minSimilarity:C(t,"minSimilarity",.3),includeHomonyms:b(t,"includeHomonyms"),limit:A(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
469
+ ${e.length} group(s) found.`)}),bm=de("twin-drift",{query:({db:e,opts:t,budget:n})=>sa(e,{scope:w(t,"scope"),minSimilarity:C(t,"minSimilarity",.3),includeHomonyms:b(t,"includeHomonyms"),limit:L(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
468
470
  ${e.leaf} (${e.relationship}, ${e.members.length} functions, ${Math.round(e.maxDivergence*100)}% divergence)`,n=e.members.map(i=>` ${M(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
469
471
  `),r=e.firstDivergentTokens?`
470
472
  first divergent tokens: ${e.firstDivergentTokens}`:"";return`${t}
471
473
  ${n}${r}`},emptyMessage:()=>"No divergent twin groups found.",heuristicLabel:"twin drift candidates",after:e=>console.log(`
472
- ${e.length} group(s) found.`)}),am=de("not-implemented",{query:({db:e,opts:t,budget:n})=>ma(e,{scope:k(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
474
+ ${e.length} group(s) found.`)}),Sm=de("not-implemented",{query:({db:e,opts:t,budget:n})=>ba(e,{scope:w(t,"scope"),limit:L(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
473
475
  ${e.stubText}`,emptyMessage:()=>"No reachable placeholder stubs found.",heuristicLabel:"reachable placeholder stubs",after:e=>console.log(`
474
- ${e.length} reachable placeholder stub(s).`)}),cm=de("decorative-checkers",{query:({db:e,opts:t,budget:n})=>fa(e,{scope:k(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.nameKind}, resolved: ${e.resolvedVia}${e.delegateTarget?` -> ${e.delegateTarget}`:""})`,emptyMessage:()=>"No decorative checker candidates found.",heuristicLabel:"decorative checker candidates",after:e=>console.log(`
475
- ${e.length} decorative checker candidate(s).`)}),lm=K("test-quality",({db:e,args:t,opts:n,budget:r})=>{let i=ga(e,{scope:k(n,"scope"),limit:A(n,"limit",30),scanLimit:r.scanLimit,rotDays:U(n,"rotDays")});if(b(n,"json")){I("test-quality",t,n,i,{analysisBudget:r.analysisBudget});return}if(Pe("test-quality findings"),i.assertionFree.length+i.skipped.length+i.mockEcho.length===0){j.empty("No test-quality findings.");return}i.assertionFree.length>0&&(console.log(`
476
- ASSERTION-FREE (${i.assertionFree.length})`),j.list(i.assertionFree,s=>` ${M(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),i.skipped.length>0&&(console.log(`
477
- SKIPPED (${i.skipped.length})`),j.list(i.skipped,s=>` ${s.file}:${s.startLine+1} "${s.title}" (${s.blockKind}.${s.skipKind}, age: ${s.ageDays??"unknown"}d, ${s.rot})`)),i.mockEcho.length>0&&(console.log(`
478
- MOCK-ECHO (${i.mockEcho.length})`),j.list(i.mockEcho,s=>` ${M(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
479
- ${i.assertionFree.length} assertion-free, ${i.skipped.length} skipped, ${i.mockEcho.length} mock-echo.`)}),dm=ze({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let r=L(t,0),i=L(t,1),o=k(n,"out")??ua(r,i),s=ue(e.config.projectRoot,o);if(!s)throw new Error(`twin-ab output path escapes the project root: ${o}`);let a=pa(e,r,i,s);if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=sk(e.config.projectRoot,s);if(!b(n,"force")&&nk(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return rk(ok(s),{recursive:!0}),ik(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
476
+ ${e.length} reachable placeholder stub(s).`)}),vm=de("decorative-checkers",{query:({db:e,opts:t,budget:n})=>Sa(e,{scope:w(t,"scope"),limit:L(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.nameKind}, resolved: ${e.resolvedVia}${e.delegateTarget?` -> ${e.delegateTarget}`:""})`,emptyMessage:()=>"No decorative checker candidates found.",heuristicLabel:"decorative checker candidates",after:e=>console.log(`
477
+ ${e.length} decorative checker candidate(s).`)}),xm=K("test-quality",({db:e,args:t,opts:n,budget:r})=>{let i=va(e,{scope:w(n,"scope"),limit:L(n,"limit",30),scanLimit:r.scanLimit,rotDays:U(n,"rotDays")});if(b(n,"json")){I("test-quality",t,n,i,{analysisBudget:r.analysisBudget});return}if(Te("test-quality findings"),i.assertionFree.length+i.skipped.length+i.mockEcho.length===0){E.empty("No test-quality findings.");return}i.assertionFree.length>0&&(console.log(`
478
+ ASSERTION-FREE (${i.assertionFree.length})`),E.list(i.assertionFree,s=>` ${M(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),i.skipped.length>0&&(console.log(`
479
+ SKIPPED (${i.skipped.length})`),E.list(i.skipped,s=>` ${s.file}:${s.startLine+1} "${s.title}" (${s.blockKind}.${s.skipKind}, age: ${s.ageDays??"unknown"}d, ${s.rot})`)),i.mockEcho.length>0&&(console.log(`
480
+ MOCK-ECHO (${i.mockEcho.length})`),E.list(i.mockEcho,s=>` ${M(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
481
+ ${i.assertionFree.length} assertion-free, ${i.skipped.length} skipped, ${i.mockEcho.length} mock-echo.`)}),Rm=Ke({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let r=A(t,0),i=A(t,1),o=w(n,"out")??ha(r,i),s=ue(e.config.projectRoot,o);if(!s)throw new Error(`twin-ab output path escapes the project root: ${o}`);let a=ya(e,r,i,s);if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=Dk(e.config.projectRoot,s);if(!b(n,"force")&&Ek(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return jk(Lk(s),{recursive:!0}),Ak(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
480
482
  Wrote behavioral A/B scaffold: ${e.outPath}`),console.log(` A: ${e.a.shortName} (${M(e.a.file,e.a.startLine,e.a.startLine)})`),console.log(` B: ${e.b.shortName} (${M(e.b.file,e.b.startLine,e.b.startLine)})`);let t=e.signatureCompatible===null?"unknown":e.signatureCompatible?"compatible":"MISMATCH";console.log(` Signature compatibility: ${t}`),console.log(`
481
- Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),um=K("cleanup-plan",({db:e,args:t,opts:n,budget:r})=>{let i=Br(e,{scope:k(n,"scope"),minLoc:C(n,"minLoc",1),maxDepth:C(n,"maxDepth",5),scanLimit:r.scanLimit}),o=Y(),s=b(n,"patch"),a=b(n,"json"),c=b(n,"verify")||s;if(s&&!b(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(i.batches.length===0){if(a){I("cleanup-plan",t,n,i,{analysisBudget:r.analysisBudget});return}return j.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=ti(i),d=c?Xr(o,i):void 0;if(a){I("cleanup-plan",t,n,{result:i,verification:d},{analysisBudget:r.analysisBudget});return}if(s){let p=ni(d,l);if(p.length>0){for(let f of p)console.error(`error: ${f}`);process.exitCode=1;return}let m=Dc(o,l);if(m.trim()===""){console.error("error: verified cleanup plan produced an empty patch."),process.exitCode=1;return}console.error(`cleanup-plan --patch: ${l.length} verified batch(es), ${i.totalLoc} LOC.`),console.log(m);return}console.log(`Cleanup plan: ${i.totalSymbols} symbol(s), ${i.totalLoc} LOC across ${i.batches.length} batch(es).`),console.log(`Apply one batch at a time; run your typecheck between batches.
483
+ Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),km=K("cleanup-plan",({db:e,args:t,opts:n,budget:r})=>{let i=Hr(e,{scope:w(n,"scope"),minLoc:C(n,"minLoc",1),maxDepth:C(n,"maxDepth",5),scanLimit:r.scanLimit}),o=Y(),s=b(n,"patch"),a=b(n,"json"),c=b(n,"verify")||s;if(s&&!b(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(i.batches.length===0){if(a){I("cleanup-plan",t,n,i,{analysisBudget:r.analysisBudget});return}return E.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=ri(i),d=c?ei(o,i):void 0;if(a){I("cleanup-plan",t,n,{result:i,verification:d},{analysisBudget:r.analysisBudget});return}if(s){let p=ii(d,l);if(p.length>0){for(let f of p)console.error(`error: ${f}`);process.exitCode=1;return}let m=_c(o,l);if(m.trim()===""){console.error("error: verified cleanup plan produced an empty patch."),process.exitCode=1;return}console.error(`cleanup-plan --patch: ${l.length} verified batch(es), ${i.totalLoc} LOC.`),console.log(m);return}console.log(`Cleanup plan: ${i.totalSymbols} symbol(s), ${i.totalLoc} LOC across ${i.batches.length} batch(es).`),console.log(`Apply one batch at a time; run your typecheck between batches.
482
484
  `);for(let p of i.batches){let m=p.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${p.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${p.depth}: dead once batch ${p.depth-1} lands (cascade, ${p.loc} LOC) \u2500\u2500`;console.log(m);for(let f of p.entries)console.log(` ${f.file}:${f.startLine+1}-${f.endLine+1} ${f.shortName} (${f.loc} LOC)`);p.filesEmptied.length>0&&console.log(` -> empties: ${p.filesEmptied.join(", ")}`),console.log("")}if(i.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let p of i.blocked)console.log(` ${p.shortName} (${p.file}) blocked by ${p.blockingFiles.join(", ")}`)}if(d){if(console.log(`
483
- Verifying batches against the project checker (throwaway worktree at HEAD)...`),d.checkers.length===0){console.log(" No checker detected (need tsconfig.json, go.mod, Python project markers, Clojure project markers, or Cargo.toml) -- skipped.");return}for(let f of d.checkers)console.log(` Checker: ${f}`);if(d.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${d.uncoveredFiles.join(", ")}`),d.baselineErrors>0&&console.log(` Baseline has ${d.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),d.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${d.dirtyOverlap.join(", ")}`),d.dirtyWorkingTree.length>0){let f=d.dirtyWorkingTree.slice(0,5),g=d.dirtyWorkingTree.length-f.length;console.log(` WARNING: verification ran at HEAD; ${d.dirtyWorkingTree.length} working-tree change(s) were not compiled: ${f.join(", ")}${g>0?`, ... ${g} more`:""}`)}let p=ak(d.checkers),m=ck(d.checkers);for(let f of d.batches)if(f.status==="verified")console.log(` Batch ${f.depth}: VERIFIED (${p})${m}`);else{console.log(` Batch ${f.depth}: FAILED${f.reason?` (${f.reason})`:""} -- the output below names references the static evidence missed or unparsed checker output:`);for(let g of f.errors??[])console.log(` ${g}`)}}}),pm=K("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!b(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let r=b(t,"all"),i=U(t,"batch");if(r===(i!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=Br(e,{scope:k(t,"scope"),minLoc:C(t,"minLoc",1),maxDepth:C(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){j.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=ti(o,{all:r,batch:i});if(s.length===0){console.error(`error: No cleanup batch ${i} exists.`),process.exitCode=1;return}let a=Y(),c=Xr(a,o),l=ni(c,s,{allowDirty:b(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}ei(a,s);let d=s.reduce((m,f)=>m+f.entries.length,0),p=s.reduce((m,f)=>m+f.loc,0);console.log(`Applied ${s.length} verified cleanup batch(es): ${d} symbol(s), ${p} LOC.`)});function ak(e){return e.join(", ")}function ck(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var mm=K("recent-duplicates",({db:e,args:t,opts:n,budget:r})=>{let i=b(n,"full"),o=ha(e,{windowCommits:C(n,"window",100),minSimilarity:U(n,"minSimilarity"),limit:A(n,"limit",30),scope:k(n,"scope"),scanLimit:r.scanLimit,semantic:r.semantic,historyMode:i?"full":"bounded"});if(b(n,"json")){I("recent-duplicates",t,n,o,{analysisBudget:r.analysisBudget});return}if(!o.available)return j.empty("No git history available (not a repository, or git missing).");if(o.findings.length===0)return j.empty(`No recent re-implementations found (window: last ${o.windowCommits} commits).`);Pe("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${o.windowCommits} commits):
485
+ Verifying batches against the project checker (throwaway worktree at HEAD)...`),d.checkers.length===0){console.log(" No checker detected (need tsconfig.json, go.mod, Python project markers, Clojure project markers, or Cargo.toml) -- skipped.");return}for(let f of d.checkers)console.log(` Checker: ${f}`);if(d.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${d.uncoveredFiles.join(", ")}`),d.baselineErrors>0&&console.log(` Baseline has ${d.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),d.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${d.dirtyOverlap.join(", ")}`),d.dirtyWorkingTree.length>0){let f=d.dirtyWorkingTree.slice(0,5),g=d.dirtyWorkingTree.length-f.length;console.log(` WARNING: verification ran at HEAD; ${d.dirtyWorkingTree.length} working-tree change(s) were not compiled: ${f.join(", ")}${g>0?`, ... ${g} more`:""}`)}let p=Fk(d.checkers),m=Ok(d.checkers);for(let f of d.batches)if(f.status==="verified")console.log(` Batch ${f.depth}: VERIFIED (${p})${m}`);else{console.log(` Batch ${f.depth}: FAILED${f.reason?` (${f.reason})`:""} -- the output below names references the static evidence missed or unparsed checker output:`);for(let g of f.errors??[])console.log(` ${g}`)}}}),wm=K("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!b(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let r=b(t,"all"),i=U(t,"batch");if(r===(i!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=Hr(e,{scope:w(t,"scope"),minLoc:C(t,"minLoc",1),maxDepth:C(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){E.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=ri(o,{all:r,batch:i});if(s.length===0){console.error(`error: No cleanup batch ${i} exists.`),process.exitCode=1;return}let a=Y(),c=ei(a,o),l=ii(c,s,{allowDirty:b(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}ni(a,s);let d=s.reduce((m,f)=>m+f.entries.length,0),p=s.reduce((m,f)=>m+f.loc,0);console.log(`Applied ${s.length} verified cleanup batch(es): ${d} symbol(s), ${p} LOC.`)});function Fk(e){return e.join(", ")}function Ok(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var $m=K("recent-duplicates",({db:e,args:t,opts:n,budget:r})=>{let i=b(n,"full"),o=xa(e,{windowCommits:C(n,"window",100),minSimilarity:U(n,"minSimilarity"),limit:L(n,"limit",30),scope:w(n,"scope"),scanLimit:r.scanLimit,semantic:r.semantic,historyMode:i?"full":"bounded"});if(b(n,"json")){I("recent-duplicates",t,n,o,{analysisBudget:r.analysisBudget});return}if(!o.available)return E.empty("No git history available (not a repository, or git missing).");if(o.findings.length===0)return E.empty(`No recent re-implementations found (window: last ${o.windowCommits} commits).`);Te("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${o.windowCommits} commits):
484
486
  `);let s=o.rootCauseGroups?.filter(a=>a.count>1)??[];if(s.length>0){console.log(`Root-cause groups (${s.length}):`);for(let a of s)console.log(` ${a.count} pair(s) ${a.kind.toUpperCase()} ${a.domain} ${Math.round(a.maxSimilarity*100)}% max`),a.establishedFile&&a.establishedSymbol&&console.log(` established: ${a.establishedFile} ${a.establishedSymbol}`),console.log(` files: ${a.relatedFiles.slice(0,6).join(", ")}`),console.log(` -> ${a.recommendation}`);console.log("")}for(let a of o.findings){let c=a.sharedEvidence.slice(0,16).join(", ");a.kind==="echo"?(console.log(` ${Math.round(a.similarity*100)}% ECHO ${a.domain} ${a.echoFile} ${a.echoSymbol} (added ${a.echoAgeCommits} commits ago)`),console.log(` duplicates established ${a.establishedFile} ${a.establishedSymbol}`)):(console.log(` ${Math.round(a.similarity*100)}% TWIN ${a.domain} ${a.echoFile} ${a.echoSymbol}`),console.log(` and ${a.establishedFile} ${a.establishedSymbol} (both new \u2014 consolidate before they diverge)`)),console.log(` basis: ${a.basis}`),c.length>0&&console.log(` shared: ${c}`)}console.log(`
485
- ${o.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),fm=le(({db:e,args:t,opts:n})=>{let r=b(n,"full"),i=Zs(e,{doc:t[0]===void 0?void 0:L(t,0),limit:A(n,"limit",20),minCoupling:C(n,"minCoupling",3),includeSnapshotExcluded:r,historyMode:r?"full":"bounded"});if(b(n,"json")){I("doc-drift",t,n,i);return}if(!i.available)return j.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return j.empty(`No drifting docs found across ${i.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);Pe("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${i.docsScanned} docs scanned, ${i.commitsAnalyzed} commits analyzed):
486
- `);for(let o of i.findings){let s=o.snapshotExcluded?" [snapshot (excluded by policy)]":"",a=o.docLastChangedAtEstimated?" [docLastChangedAt estimated from file mtime]":"";console.log(` staleness ${o.staleness} ${o.doc}${s}${a}`);for(let c of o.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${c} \u2014 that file no longer exists`);for(let c of o.subjects.slice(0,4)){let l=c.evidence==="both"?`referenced by doc + coupled ${c.coChanges}x`:c.evidence==="reference"?"referenced by doc":`coupled ${c.coChanges}x historically`;console.log(` ${c.changesSinceDocUpdate} change(s) since doc update ${c.file} (${l}; ${c.actionTier}/${c.docIntent})`);let d=c.docIntentReasons[0];d&&console.log(` intent: ${d}`);let p=c.citationContexts?.[0];p&&console.log(` cited claim: ${An(p)}`)}}console.log(`
487
- Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),gm=de("unused-params",{query:({db:e,opts:t,budget:n})=>la(e,{scope:k(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName}
487
+ ${o.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),Cm=le(({db:e,args:t,opts:n})=>{let r=b(n,"full"),i=ia(e,{doc:t[0]===void 0?void 0:A(t,0),limit:L(n,"limit",20),minCoupling:C(n,"minCoupling",3),includeSnapshotExcluded:r,historyMode:r?"full":"bounded"});if(b(n,"json")){I("doc-drift",t,n,i);return}if(!i.available)return E.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return E.empty(`No drifting docs found across ${i.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);Te("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${i.docsScanned} docs scanned, ${i.commitsAnalyzed} commits analyzed):
488
+ `);for(let o of i.findings){let s=o.snapshotExcluded?" [snapshot (excluded by policy)]":"",a=o.docLastChangedAtEstimated?" [docLastChangedAt estimated from file mtime]":"";console.log(` staleness ${o.staleness} ${o.doc}${s}${a}`);for(let c of o.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${c} \u2014 that file no longer exists`);for(let c of o.subjects.slice(0,4)){let l=c.evidence==="both"?`referenced by doc + coupled ${c.coChanges}x`:c.evidence==="reference"?"referenced by doc":`coupled ${c.coChanges}x historically`;console.log(` ${c.changesSinceDocUpdate} change(s) since doc update ${c.file} (${l}; ${c.actionTier}/${c.docIntent})`);let d=c.docIntentReasons[0];d&&console.log(` intent: ${d}`);let p=c.citationContexts?.[0];p&&console.log(` cited claim: ${Dn(p)}`)}}console.log(`
489
+ Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),Pm=de("unused-params",{query:({db:e,opts:t,budget:n})=>fa(e,{scope:w(t,"scope"),limit:L(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName}
488
490
  trailing unused: ${e.unusedTrailing.join(", ")} (${e.unusedTrailing.length} of ${e.paramCount} params -- type-safe to remove at the signature; check call sites for side-effectful arguments)`,emptyMessage:()=>"No trailing unused parameters found.",heuristicLabel:"unused trailing parameter candidates",after:e=>console.log(`
489
- ${e.length} function(s) with trailing unused parameters.`)});var hm=Se("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>_s(e,{minSimilarity:C(n,"minSimilarity",.62),minTokens:C(n,"minTokens",8),limit:A(n,"limit",20),scope:k(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{j.list(e,t=>{let n=[`
491
+ ${e.length} function(s) with trailing unused parameters.`)});var Tm=Se("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Ws(e,{minSimilarity:C(n,"minSimilarity",.62),minTokens:C(n,"minTokens",8),limit:L(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:V(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{E.list(e,t=>{let n=[`
490
492
  ${Math.round(t.similarity*100)}% similar React structure:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComponents.length&&n.push(` Shared components: ${t.sharedComponents.join(", ")}`),t.sharedNativeTags.length&&n.push(` Shared native tags: ${t.sharedNativeTags.join(", ")}`),t.sharedProps.length&&n.push(` Shared props: ${t.sharedProps.join(", ")}`),t.sharedEvents.length&&n.push(` Shared events: ${t.sharedEvents.join(", ")}`),t.sharedBindings.length&&n.push(` Shared bindings: ${t.sharedBindings.slice(0,20).join(", ")}`),n.join(`
491
493
  `)}),console.log(`
492
- ${e.length} duplicated React component pair(s) found.`)}}),ym=Se("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:r})=>qs(e,{minSimilarity:C(n,"minSimilarity",.45),minSharedBehaviors:C(n,"minSharedBehaviors",6),limit:A(n,"limit",20),scope:k(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{j.list(e,t=>{let n=[`
494
+ ${e.length} duplicated React component pair(s) found.`)}}),Im=Se("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Gs(e,{minSimilarity:C(n,"minSimilarity",.45),minSharedBehaviors:C(n,"minSharedBehaviors",6),limit:L(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:V(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{E.list(e,t=>{let n=[`
493
495
  ${Math.round(t.similarity*100)}% similar React behavior:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${t.reason}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedHooks.length&&n.push(` Shared hooks: ${t.sharedHooks.join(", ")}`),t.sharedReactHooks.length&&n.push(` Shared React hooks: ${t.sharedReactHooks.join(", ")}`),t.sharedEffects.length&&n.push(` Shared effects: ${t.sharedEffects.join(", ")}`),t.sharedState.length&&n.push(` Shared state: ${t.sharedState.join(", ")}`),t.sharedRequests.length&&n.push(` Shared requests: ${t.sharedRequests.join(", ")}`),t.sharedHandlers.length&&n.push(` Shared handlers: ${t.sharedHandlers.slice(0,12).join(", ")}`),t.sharedHandlerVerbs.length&&n.push(` Shared action verbs: ${t.sharedHandlerVerbs.slice(0,12).join(", ")}`),n.join(`
494
496
  `)}),console.log(`
495
- ${e.length} React hook candidate pair(s) found.`)}}),bm=Se("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Bs(e,{minComponentLines:C(n,"minComponentLines",300),minFileLines:C(n,"minFileLines",800),minJsxTokens:C(n,"minJsxTokens",80),minBehaviorTokens:C(n,"minBehaviorTokens",40),limit:A(n,"limit",20),scope:k(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{j.list(e,t=>[`
497
+ ${e.length} React hook candidate pair(s) found.`)}}),Em=Se("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Us(e,{minComponentLines:C(n,"minComponentLines",300),minFileLines:C(n,"minFileLines",800),minJsxTokens:C(n,"minJsxTokens",80),minBehaviorTokens:C(n,"minBehaviorTokens",40),limit:L(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:V(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{E.list(e,t=>[`
496
498
  ${t.componentLines} component line(s): ${t.component} (${t.file})`,` Dominant pressure: ${t.dominantPressure} (context: ${t.contextKind})`,` Pressure kinds: ${t.pressureKinds.join(", ")}`,` File lines: ${t.fileLines}; JSX tokens: ${t.jsxTokens}; behavior tokens: ${t.behaviorTokens}`,` Recommendation: ${t.recommendationKind} - ${t.recommendation}`,` Reasons: ${t.reasons.join("; ")}`].join(`
497
499
  `)),console.log(`
498
- ${e.length} large React component(s) found.`)}}),Sm=Se("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Vs(e,{minSimilarity:C(n,"minSimilarity",.62),minTokens:C(n,"minTokens",8),limit:A(n,"limit",20),scope:k(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{j.list(e,t=>{let n=[`
500
+ ${e.length} large React component(s) found.`)}}),jm=Se("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Js(e,{minSimilarity:C(n,"minSimilarity",.62),minTokens:C(n,"minTokens",8),limit:L(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:V(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{E.list(e,t=>{let n=[`
499
501
  ${Math.round(t.similarity*100)}% similar Vue structure:`,` ${t.fileA}`,` ${t.fileB}`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComponents.length&&n.push(` Shared components: ${t.sharedComponents.join(", ")}`),t.sharedProps.length&&n.push(` Shared props: ${t.sharedProps.join(", ")}`),t.sharedEvents.length&&n.push(` Shared events: ${t.sharedEvents.join(", ")}`),t.sharedDirectives.length&&n.push(` Shared directives: ${t.sharedDirectives.join(", ")}`),t.sharedSlots.length&&n.push(` Shared slots: ${t.sharedSlots.join(", ")}`),t.sharedIdentifiers.length&&n.push(` Shared identifiers: ${t.sharedIdentifiers.slice(0,20).join(", ")}`),n.join(`
500
502
  `)}),console.log(`
501
- ${e.length} duplicated Vue component pair(s) found.`)}}),vm=Se("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Hs(e,{minSimilarity:C(n,"minSimilarity",.45),minSharedBehaviors:C(n,"minSharedBehaviors",6),limit:A(n,"limit",20),scope:k(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{j.list(e,t=>{let n=[`
503
+ ${e.length} duplicated Vue component pair(s) found.`)}}),Am=Se("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:r})=>zs(e,{minSimilarity:C(n,"minSimilarity",.45),minSharedBehaviors:C(n,"minSharedBehaviors",6),limit:L(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:V(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{E.list(e,t=>{let n=[`
502
504
  ${Math.round(t.similarity*100)}% similar Vue behavior:`,` ${t.fileA}`,` ${t.fileB}`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${t.reason}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComposables.length&&n.push(` Shared composables: ${t.sharedComposables.join(", ")}`),t.sharedStores.length&&n.push(` Shared stores: ${t.sharedStores.join(", ")}`),t.sharedRequests.length&&n.push(` Shared requests: ${t.sharedRequests.join(", ")}`),t.sharedLifecycle.length&&n.push(` Shared lifecycle: ${t.sharedLifecycle.join(", ")}`),t.sharedFunctions.length&&n.push(` Shared functions: ${t.sharedFunctions.slice(0,12).join(", ")}`),t.sharedFunctionVerbs.length&&n.push(` Shared action verbs: ${t.sharedFunctionVerbs.slice(0,12).join(", ")}`),t.sharedBindings.length&&n.push(` Shared bindings: ${t.sharedBindings.slice(0,20).join(", ")}`),t.sharedTemplateEvents.length&&n.push(` Shared template events: ${t.sharedTemplateEvents.slice(0,20).join(", ")}`),n.join(`
503
505
  `)}),console.log(`
504
- ${e.length} Vue composable candidate pair(s) found.`)}}),xm=Se("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Ws(e,{minTotalLines:b(n,"reviewThresholds")&&gc(n,"minTotalLines")==="default"?300:C(n,"minTotalLines",800),minTemplateLines:C(n,"minTemplateLines",300),minScriptLines:C(n,"minScriptLines",300),minStyleLines:C(n,"minStyleLines",500),limit:A(n,"limit",20),scope:k(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{j.list(e,t=>{let n=[`
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=[`
505
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(`
506
508
  `)}),console.log(`
507
- ${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 jr=[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",v,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:gm}),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",v,1),u("--max-depth <n>","Maximum cascade depth",v,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:um}),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",v,1),u("--max-depth <n>","Maximum cascade depth",v,5),u("--verified","Required: verify the selected cleanup batch before applying it"),u("--batch <n>","Apply one batch depth",v),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:pm}),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"',v,100),u("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",fe),u("-n, --limit <n>","Maximum findings",v,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:mm}),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",v,20),u("--min-coupling <n>","Minimum historical co-changes to track a subject",v,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:fm}),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",v,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:Wp}),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:Gp}),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",v,3),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:Up}),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",v,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-callees <n>","Minimum callees to consider",v,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:Zp}),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",v,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-deps <n>","Minimum dependencies to consider",v),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:em}),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",v,8),u("-n, --limit <n>","Number of results",v,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:hm}),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",v,6),u("-n, --limit <n>","Number of results",v,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:ym}),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",v,300),u("--min-file-lines <n>","Minimum file lines",v,800),u("--min-jsx-tokens <n>","Minimum JSX structure tokens",v,80),u("--min-behavior-tokens <n>","Minimum behavior tokens",v,40),u("-n, --limit <n>","Number of results",v,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:bm}),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",v,8),u("-n, --limit <n>","Number of results",v,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:Sm}),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",v,6),u("-n, --limit <n>","Number of results",v,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:vm}),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",v,800),u("--min-template-lines <n>","Minimum template lines",v,300),u("--min-script-lines <n>","Minimum script lines",v,300),u("--min-style-lines <n>","Minimum style lines",v,500),u("--review-thresholds","Use lower review thresholds without changing health scoring"),u("-n, --limit <n>","Number of results",v,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:xm}),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",v,15),u("-s, --scope <path>","Limit to files matching path"),u("--min-length <n>","Minimum chain length",v,3),u("--max-length <n>","Maximum chain length",v,8),u("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:tm}),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",v,10),u("--min-callees <n>","Minimum callees to analyze",v,6),u("-n, --limit <n>","Number of results",v,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Jp}),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",v,1),u("-n, --limit <n>","Number of results",v,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:zp}),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",v,50),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:nm}),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",v,15),u("-n, --limit <n>","Number of results",v,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:Kp}),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",v,15),u("-n, --limit <n>","Number of results",v,30),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:Qp}),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",v,3),u("-n, --limit <n>","Number of results",v,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:Yp}),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",v,10),u("-n, --limit <n>","Number of results",v,20),u("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:Xp}),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:rm}),$p({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",v,30),u("--full","Run unbounded analysis on large indexes")],docs:$("Cleanup"),query:({db:e,opts:t})=>Ea(e,{scope:k(t,"scope"),limit:A(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",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})
508
510
  barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
509
511
  Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
510
512
  Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
511
- ${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",v,15),u("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",v,3),u("-n, --limit <n>","Number of groups",v,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:om}),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",v,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:sm}),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",v,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:am}),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",v,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:cm}),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",v,30),u("--rot-days <n>","Skips older than this many days are reported as rot",v,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:lm}),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:dm}),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",v,3),u("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",v,12),u("-n, --limit <n>","Number of groups",v,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:im})];var lk=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: ${Je(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Rm=[{id:"stats",command:"stats",description:"Show index statistics",options:[cc()],renderShape:"custom",docs:$("Core"),handler:lk}];var dk=On("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Is(e,{limit:A(t,"limit",20),scope:k(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."}),uk=le(({db:e,args:t,opts:n})=>{let r=B(t,0),i=A(n,"limit",30);if(r){let c=xs(e,r);if(b(n,"json")){I("fan-in",t,n,{mode:"symbol",symbol:r,rows:c});return}if(c.length===0)return j.empty(`No fan-in for ${r}.`);j.list(c,l=>` ${String(l.count).padStart(4)} files ${l.name}`);return}let o=ks(e,{limit:i,scope:k(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));j.table(["files","symbol"],o.map(c=>` ${String(c.count).padStart(5)} ${c.name}${a.has(c.name)?` [${c.definedIn}]`:""}`))}),pk=le(({db:e,args:t,opts:n})=>{let r=B(t,0),i=A(n,"limit",30);if(r){let s=Rs(e,r);if(b(n,"json")){I("fan-out",t,n,{mode:"file",file:r,rows:s});return}if(s.length===0)return j.empty(`No fan-out for ${r}.`);j.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=ws(e,{limit:i,scope:k(n,"scope")});if(b(n,"json")){I("fan-out",t,n,{mode:"top",rows:o});return}j.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),mk=le(({db:e,args:t,opts:n})=>{let r=B(t,0),i=B(t,1),o=A(n,"limit",20);if(r&&i){let a=$s(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=Cs(e,{limit:o,scope:k(n,"scope")});if(b(n,"json")){I("coupling",t,n,{mode:"top",rows:s});return}j.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}`))}),fk=ze({commandName:"cycles",query:({db:e,opts:t})=>Ps(e,{scope:k(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}]`:""}`))}),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(`
512
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(`
513
- ${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.)`)}}),gk=ze({commandName:"architecture",query:({db:e,opts:t})=>Ts(e,{scope:k(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(`
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(`
514
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(`
515
517
  No declared boundary violations found.`);if(e.edges.length>0){console.log(`
516
518
  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(`
517
519
  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(`
518
- 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)`)}}}}),hk=ze({commandName:"deep-chains",query:({db:e,opts:t})=>As(e,{limit:A(t,"limit",10),scope:k(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(`
519
- 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("; ")}`)}}}),km=[kr({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[u("-n, --limit <n>","Number of results",v,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})=>hs(e,{limit:A(t,"limit",30),scope:k(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",v,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:uk},{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",v,30),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:pk},{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",v,20),u("-s, --scope <path>","Limit to files matching path"),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:mk},{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",v,10)]),renderShape:"custom",docs:$("Graph"),handler:fk},{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:gk},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:P([u("-n, --limit <n>","Number of results",v,20),u("-s, --scope <path>","Limit to files matching path"),u("--min-fan-in <n>","Minimum fan-in",v,2),u("--min-fan-out <n>","Minimum fan-out",v,2),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:$("Graph"),handler:dk},{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",v,10),u("-s, --scope <path>","Limit to files matching path"),u("--min-depth <n>","Minimum chain depth",v,3),u("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:hk},wr({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}
520
- `))},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 yk=K("complexity",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=ya(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 j.empty(se(e,i,"Symbol not found."));oe(e,i),console.log(`${M(o.relativePath,o.startLine,o.endLine)} ${o.shortName}
521
- `),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}`)}),bk=le(({db:e,args:t,opts:n})=>{let r=La(e,{samples:C(n,"samples",50),scope:k(n,"scope")});if(b(n,"json")){I("self-audit",t,n,r);return}if(!r.available)return j.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)}%.
520
+ 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}
522
+ `))},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
+ `),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)}%.
522
524
  `),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(`
523
- Top disagreements (debugging targets):`);for(let o of r.topDisagreements)console.log(` ${o.symbol} [${o.question}]`),o.cheapOnly.length>0&&console.log(` cheap-only: ${o.cheapOnly.join(", ")}`),o.oracleOnly.length>0&&console.log(` oracle-only: ${o.oracleOnly.join(", ")}`)}}),wm=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",options:P([u("--samples <n>","Number of symbols to sample",v,50),u("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:$("Health",["scip-query self-audit --samples 100"]),handler:bk},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:P([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Health"),handler:yk}];var Sk=le(({db:e,args:t,opts:n})=>{let r=L(t,0),i=zs(e,r,{maxDepth:C(n,"maxDepth",5),scope:k(n,"scope")});if(b(n,"json")){I("affected",t,n,ve(e,r,i,"affected"));return}if(i.length===0)return j.empty(se(e,r,"No affected symbols found."));oe(e,r);let o=-1;for(let s of i)s.depth!==o&&(console.log(`
525
+ Top disagreements (debugging targets):`);for(let o of r.topDisagreements)console.log(` ${o.symbol} [${o.question}]`),o.cheapOnly.length>0&&console.log(` cheap-only: ${o.cheapOnly.join(", ")}`),o.oracleOnly.length>0&&console.log(` oracle-only: ${o.oracleOnly.join(", ")}`)}}),Om=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",options:P([u("--samples <n>","Number of symbols to sample",x,50),u("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:$("Health",["scip-query self-audit --samples 100"]),handler:Uk},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:P([u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Health"),handler:Gk}];var Jk=le(({db:e,args:t,opts:n})=>{let r=A(t,0),i=Zs(e,r,{maxDepth:C(n,"maxDepth",5),scope:w(n,"scope")});if(b(n,"json")){I("affected",t,n,ve(e,r,i,"affected"));return}if(i.length===0)return E.empty(se(e,r,"No affected symbols found."));oe(e,r);let o=-1;for(let s of i)s.depth!==o&&(console.log(`
524
526
  \u2500\u2500 Depth ${s.depth} \u2500\u2500`),o=s.depth),console.log(` ${s.file} ${s.shortName}`);console.log(`
525
- ${i.length} affected symbol(s) across ${new Set(i.map(s=>s.file)).size} files.`)}),vk=K("co-change",({db:e,args:t,opts:n,budget:r})=>{let i=t[0]===void 0?void 0:L(t,0),o=b(n,"full"),s=Qs(e,i,{minTogether:C(n,"minTogether",4),limit:A(n,"limit",30),includeLinked:n.all===!0,scanLimit:r.scanLimit,historyMode:o?"full":"bounded"});if(b(n,"json")){I("co-change",t,n,s,{analysisBudget:r.analysisBudget});return}if(!s.available)return j.empty("No git history available (not a repository, or git missing).");if(s.findings.length===0)return j.empty(i?`No co-change partners found for ${i} in ${s.commitsAnalyzed} commits.`:`No hidden coupling found in ${s.commitsAnalyzed} commits.`);Pe("co-change candidates"),console.log(i?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
527
+ ${i.length} affected symbol(s) across ${new Set(i.map(s=>s.file)).size} files.`)}),zk=K("co-change",({db:e,args:t,opts:n,budget:r})=>{let i=t[0]===void 0?void 0:A(t,0),o=b(n,"full"),s=ta(e,i,{minTogether:C(n,"minTogether",4),limit:L(n,"limit",30),includeLinked:n.all===!0,scanLimit:r.scanLimit,historyMode:o?"full":"bounded"});if(b(n,"json")){I("co-change",t,n,s,{analysisBudget:r.analysisBudget});return}if(!s.available)return E.empty("No git history available (not a repository, or git missing).");if(s.findings.length===0)return E.empty(i?`No co-change partners found for ${i} in ${s.commitsAnalyzed} commits.`:`No hidden coupling found in ${s.commitsAnalyzed} commits.`);Te("co-change candidates"),console.log(i?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
526
528
  `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${s.commitsAnalyzed} commits analyzed):
527
529
  `),i&&s.findings.some(a=>a.structurallyLinked||a.declaredCouplingSuggestion)&&console.log(`note: file mode lists all historical partners; [dep edge]/[declared] pairs are excluded from hidden-coupling findings.
528
- `);for(let a of s.findings){let c=a.structurallyLinked?" [dep edge]":"",l=` [${a.partnerClass}]`,d=` [${a.commitScope}/${a.recency}]`;console.log(` ${a.together}x (${Math.round(a.confidence*100)}%) ${a.fileA} <-> ${a.fileB}${l}${d}${c}`),console.log(` history: ${a.focusedTogether} focused, ${a.broadTogether} broad-sweep (${Math.round(a.broadCommitRatio*100)}% broad), ${a.recentTogether} recent; last ${xk(a.lastTogetherAt)}`),console.log(` subjects: ${Rk(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
529
- ${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function xk(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function Rk(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",r=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(i=>`"${i}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${r}; external issue/PR labels ${e.externalIssueLabelStatus}`}var kk=K("change-surface",({db:e,args:t,opts:n,budget:r})=>{let i=Ks(e,L(t,0),{semantic:r.semantic});if(b(n,"json")){I("change-surface",t,n,i,{analysisBudget:r.analysisBudget});return}if(!i)return j.empty("File not found in index.");console.log(`File: ${i.file}`),console.log(`External consumers: ${i.totalExternalConsumers}
530
- `),j.list(i.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${ie(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),wk=K("incomplete-migration",({db:e,args:t,opts:n,budget:r})=>{let i=ca(e,{base:k(n,"base"),minContainment:C(n,"minContainment",.7),maxHelpers:U(n,"maxHelpers"),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(b(n,"json")){I("incomplete-migration",t,n,i,{analysisBudget:r.analysisBudget}),i.available&&i.findings.length>0&&(process.exitCode=1);return}if(!i.available)return j.empty("No git history available (not a repository, or git missing).");if(i.changedFiles.length===0)return j.empty(`No changes vs ${i.base}.`);console.log(`Incomplete migrations vs ${i.base}: ${i.changedFiles.length} changed file(s), ${i.helpersChecked} new helper(s) scored.`),i.note&&console.log(` note: ${i.note}`);for(let o of i.skipped)console.log(` skipped ${o.helperShortName} (${o.helperFile}): ${o.reason}`);if(i.findings.length===0){console.log(`
531
- No incomplete migrations detected.`);return}Pe("incomplete migration candidates");for(let o of i.findings){console.log(`
530
+ `);for(let a of s.findings){let c=a.structurallyLinked?" [dep edge]":"",l=` [${a.partnerClass}]`,d=` [${a.commitScope}/${a.recency}]`;console.log(` ${a.together}x (${Math.round(a.confidence*100)}%) ${a.fileA} <-> ${a.fileB}${l}${d}${c}`),console.log(` history: ${a.focusedTogether} focused, ${a.broadTogether} broad-sweep (${Math.round(a.broadCommitRatio*100)}% broad), ${a.recentTogether} recent; last ${Kk(a.lastTogetherAt)}`),console.log(` subjects: ${Qk(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
531
+ ${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function Kk(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function Qk(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",r=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(i=>`"${i}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${r}; external issue/PR labels ${e.externalIssueLabelStatus}`}var Yk=K("change-surface",({db:e,args:t,opts:n,budget:r})=>{let i=ea(e,A(t,0),{semantic:r.semantic});if(b(n,"json")){I("change-surface",t,n,i,{analysisBudget:r.analysisBudget});return}if(!i)return E.empty("File not found in index.");console.log(`File: ${i.file}`),console.log(`External consumers: ${i.totalExternalConsumers}
532
+ `),E.list(i.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${ie(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),Xk=K("incomplete-migration",({db:e,args:t,opts:n,budget:r})=>{let i=ma(e,{base:w(n,"base"),minContainment:C(n,"minContainment",.7),maxHelpers:U(n,"maxHelpers"),limit:L(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(b(n,"json")){I("incomplete-migration",t,n,i,{analysisBudget:r.analysisBudget}),i.available&&i.findings.length>0&&(process.exitCode=1);return}if(!i.available)return E.empty("No git history available (not a repository, or git missing).");if(i.changedFiles.length===0)return E.empty(`No changes vs ${i.base}.`);console.log(`Incomplete migrations vs ${i.base}: ${i.changedFiles.length} changed file(s), ${i.helpersChecked} new helper(s) scored.`),i.note&&console.log(` note: ${i.note}`);for(let o of i.skipped)console.log(` skipped ${o.helperShortName} (${o.helperFile}): ${o.reason}`);if(i.findings.length===0){console.log(`
533
+ No incomplete migrations detected.`);return}Te("incomplete migration candidates");for(let o of i.findings){console.log(`
532
534
  ${o.helperShortName} (${o.helperFile})`),console.log(` helper shape: ${o.helperShape} (${o.specificHelperCalleeCount}/${o.helperCalleeCount} specific callees)`),console.log(` wired into: ${o.migratedFiles.join(", ")}`);for(let s of o.leftovers)console.log(` un-migrated: ${Math.round(s.containment*100)}% helper / ${Math.round(s.siteCoverage*100)}% site [${s.migrationScope}] ${s.shortName} (${s.file})`),console.log(` scope: ${s.migrationScopeReasons.join("; ")}`),s.uniqueSiteCalleeCount>0&&console.log(` extra site callees: ${s.uniqueSiteCalleeCount}`),console.log(` shared: ${s.sharedCallees.join(", ")}`)}console.log(`
533
- ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function $k(e){let t=Array.isArray(e)?e:[],n=t.filter(r=>!Vr.includes(r));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${Vr.join(", ")}`),process.exit(1)),t}var Ck=le(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&Mn(Jt()))return;let r=b(t,"full"),i=rc(e,"diff-gate",r,{quiet:n||b(t,"json")}),o={base:k(t,"base"),minTogether:C(t,"minTogether",6),maxEchoChecks:U(t,"maxEchoChecks"),maxHelpers:U(t,"maxHelpers"),includeBaseline:b(t,"baseline"),scanLimit:i.scanLimit,semantic:i.semantic,historyMode:r?"full":"bounded",skip:$k(t.skip)},s=xt(e,o),a=jn(s.findings),c=In(s),l=Gn(e,s,{replayGate:f=>xt(e,{...o,base:f})});if(l.warning&&console.error(`note: ${l.warning}`),!n&&b(t,"json")){I("diff-gate",[],t,{exitCode:a.length>0||c?1:0,...c?{gateError:"git diff unavailable - zero checks ran; the gate fails closed"}:{},advisoryFindingCount:s.findings.length-a.length,...i.analysisBudget?{analysisBudget:i.analysisBudget}:{},...s}),(a.length>0||c)&&(process.exitCode=1);return}if(n){let{ledger:f,observed:g,now:h}=l;if(c){console.error("diff gate FAILED CLOSED: could not compute the git diff (diff too large, bad --base, or git error) - zero checks ran. Investigate with: scip-query diff-gate"),process.exitCode=2;return}if(a.length===0)return;let y=ka(f,g,h),S=wa(f,s.checksRun),x=ic(i.analysisBudget),w=[...y?[y]:[],zt(s),...S,...x?[x]:[]];console.error(w.join(`
534
- `)),process.exitCode=2;return}if(c){console.error("FAIL (gate error): could not compute the git diff - zero checks ran; the gate fails closed. Check --base and repository state."),process.exitCode=1;return}if(s.changedFiles.length===0)return j.empty(s.note??`No changes vs ${s.base}.`);console.log(`Diff gate vs ${s.base}: ${s.changedFiles.length} file(s), ${s.changedSymbols} symbol(s) changed.`);let d=s.attributionNotes.filter(f=>f.method==="unattributed");if(d.length>0)for(let f of[...new Set(d.map(g=>g.file))]){let g=d.filter(h=>h.file===f).length;console.log(`note: ${g} changed line-range(s) in ${f} belong to no indexed symbol`)}console.log(`Checks: ${s.checksRun.join(", ")}
535
- `);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}Pe("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: ${An(g)}`);f.declaredCouplingSuggestion&&console.log(` declare coupling: ${f.declaredCouplingSuggestion.name} (${f.declaredCouplingSuggestion.reason})`),console.log(` -> ${f.remediation}`)}if(a.length===0){console.log(`
535
+ ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function Zk(e){let t=Array.isArray(e)?e:[],n=t.filter(r=>!Wr.includes(r));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${Wr.join(", ")}`),process.exit(1)),t}var ew=le(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&_n(Jt()))return;let r=b(t,"full"),i=cc(e,"diff-gate",r,{quiet:n||b(t,"json")}),o={base:w(t,"base"),minTogether:C(t,"minTogether",6),maxEchoChecks:U(t,"maxEchoChecks"),maxHelpers:U(t,"maxHelpers"),includeBaseline:b(t,"baseline"),scanLimit:i.scanLimit,semantic:i.semantic,historyMode:r?"full":"bounded",skip:Zk(t.skip)},s=xt(e,o),a=jn(s.findings),c=En(s),l=Un(e,s,{replayGate:f=>xt(e,{...o,base:f})});if(l.warning&&console.error(`note: ${l.warning}`),!n&&b(t,"json")){I("diff-gate",[],t,{exitCode:a.length>0||c?1:0,...c?{gateError:"git diff unavailable - zero checks ran; the gate fails closed"}:{},advisoryFindingCount:s.findings.length-a.length,...i.analysisBudget?{analysisBudget:i.analysisBudget}:{},...s}),(a.length>0||c)&&(process.exitCode=1);return}if(n){let{ledger:f,observed:g,now:h}=l;if(c){console.error("diff gate FAILED CLOSED: could not compute the git diff (diff too large, bad --base, or git error) - zero checks ran. Investigate with: scip-query diff-gate"),process.exitCode=2;return}if(a.length===0)return;let y=Ta(f,g,h),S=Ia(f,s.checksRun),v=lc(i.analysisBudget),k=[...y?[y]:[],zt(s),...S,...v?[v]:[]];console.error(k.join(`
536
+ `)),process.exitCode=2;return}if(c){console.error("FAIL (gate error): could not compute the git diff - zero checks ran; the gate fails closed. Check --base and repository state."),process.exitCode=1;return}if(s.changedFiles.length===0)return E.empty(s.note??`No changes vs ${s.base}.`);console.log(`Diff gate vs ${s.base}: ${s.changedFiles.length} file(s), ${s.changedSymbols} symbol(s) changed.`);let d=s.attributionNotes.filter(f=>f.method==="unattributed");if(d.length>0)for(let f of[...new Set(d.map(g=>g.file))]){let g=d.filter(h=>h.file===f).length;console.log(`note: ${g} changed line-range(s) in ${f} belong to no indexed symbol`)}console.log(`Checks: ${s.checksRun.join(", ")}
537
+ `);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(`
536
538
  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(`
537
- 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}),$m=[{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",v,5),u("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:$("Impact"),handler:Sk},{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:kk},{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",v,6),u("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",v),u("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",v),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:Ck},{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)",v),u("-n, --limit <n>","Maximum findings to report",v,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:wk},{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",v,4),u("-n, --limit <n>","Maximum pairs to report",v,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:vk}];function Pk(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(`
538
- `).map((s,a)=>` ${_e(i.startLine+a)} ${s}`).join(`
539
- `))}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 ${_e(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var Tk=de("imports",{query:({db:e,args:t,budget:n})=>ys(e,L(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)."}),Ik=K("dataflow",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=ba(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 j.empty(se(e,i,"No dataflow found."));if(oe(e,i),console.log(`${o.shortName} (${o.relativePath})
540
- `),o.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of o.definitionSites)console.log(` ${s.file}:${_e(s.line)}`)}if(o.usageSites.length>0){console.log(`
541
- \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of o.usageSites)console.log(` ${s.file}:${_e(s.line)} in ${s.enclosingShort}`)}if(o.producers.length>0){console.log(`
539
+ 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(`
542
544
  \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(`
543
- \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of o.consumers)console.log(` ${s.file} ${s.shortName}`)}}),jk=K("slice",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=b(n,"forward")?"forward":"backward",s=Sa(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 j.empty(se(e,i,"No slice found."));if(oe(e,i),console.log(`${s.direction} slice of ${s.shortName}
544
- `),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}j.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
545
+ \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
+ `),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}E.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
545
547
  ${a.relationship}`),console.log(`
546
- ${s.connectedSymbols.length} connected symbol(s).`)}),Cm=[...yc,Ie({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:$("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>cs(e,L(t,0)),format:e=>e.relativePath}),Ie({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:$("Navigation"),query:({db:e,args:t})=>ls(e,L(t,0)),format:e=>` ${ie(e.startLine,e.endLine)} ${e.name}`}),wr({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})=>ds(e,L(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?se(t,L(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>oe(t,L(n,0)),toJson:(e,{db:t,args:n})=>({...Ut(t,L(n,0)),...e}),sections:Pk}),Ie({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:$("Navigation"),query:({db:e,args:t})=>us(e,L(t,0)),format:e=>e.relativePath}),Ie({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:$("Navigation"),query:({db:e,args:t})=>ps(e,L(t,0)),format:e=>e.relativePath}),Cp({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})=>ms(e,L(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}`)}]}),Ie({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:$("Navigation"),query:({db:e,args:t})=>fs(e,L(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:Tk},Ie({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:$("Navigation"),query:({db:e,args:t})=>bs(e,L(t,0)),format:e=>` ${e.fromFile}`}),Ie({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:$("Navigation"),query:({db:e,args:t})=>vs(e,L(t,0)),format:e=>` ${ie(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>oe(t,L(n,0)),emptyMessage:({db:e,args:t})=>se(e,L(t,0),"No child symbols found."),toJson:(e,{db:t,args:n})=>ve(t,L(n,0),e,"members")}),Ie({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",v,100),u("--full","Run unbounded analysis on large indexes")],docs:$("Navigation"),query:({db:e,args:t,opts:n})=>Es(e,L(t,0),{scope:k(n,"scope"),limit:A(n,"limit",100)}),format:e=>` ${M(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${L(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
547
- ${e.length} symbol(s)`)}),kr({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})=>Ls(e,{scope:k(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),Ie({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:$("Navigation"),query:({db:e,args:t})=>Ds(e,L(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>oe(t,L(n,0)),emptyMessage:({db:e,args:t})=>se(e,L(t,0),"Symbol not found."),toJson:(e,{db:t,args:n})=>ve(t,L(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:Ik},{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",v,3),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Navigation"),handler:jk}];var Ek=K("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=A(n,"limit",20),o=Me(e.config.projectRoot).gitContext?.headCommit,s=va(e,L(t,0),{semantic:r.semantic,impactDepth:C(n,"impactDepth",3),sliceDepth:C(n,"sliceDepth",3),scope:k(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,L(t,0)),...s},{analysisBudget:r.analysisBudget});return}return j.empty(se(e,L(t,0)))}if(b(n,"json")){I("plan-context",t,n,s.matched.symbol?{...Ut(e,L(t,0)),...s}:s,{analysisBudget:r.analysisBudget});return}s.matched.symbol&&oe(e,L(t,0));let a=[{title:"TARGET",rows:Lk(s)},{title:"DEFINITIONS",rows:Ak(s,i),skipIfEmpty:!0},{title:"REFERENCES",rows:Dk(s,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:Ok(s,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:Fk(s,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:Nk(s,i),skipIfEmpty:!0},{title:"SURFACE",rows:Mk(s,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:_k(s,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:qk(s,i),skipIfEmpty:!0},{title:"HISTORY",rows:Bk(s),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:Vk(s),skipIfEmpty:!0}];j.sectionedReport(a)}),Pm=[{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",v,3),u("--slice-depth <n>","Maximum backward slice depth",v,3),u("-s, --scope <path>","Limit downstream impact to files matching path"),u("-n, --limit <n>","Rows per section",v,20),u("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Planning",["scip-query plan-context parseSymbol"]),handler:Ek}];function Lk(e){return[`Target: ${e.target}`,`Matched: symbol=${mo(e.matched.symbol)} file=${mo(e.matched.file)} module=${mo(e.matched.module)}`]}function Ak(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(`
548
- `).map((o,s)=>` ${String(_e(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 Dk(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${_e(r.line)} in ${r.enclosingShort}`);return gt(tt(n,t))}function Ok(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 Fk(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}:${_e(o.line)} in ${o.enclosingShort}`);return gt(tt([...n,...r,...i],t))}function Nk(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 Mk(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 _k(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 qk(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 Bk(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 Vk(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 mo(e){return e?"yes":"no"}import{existsSync as pn}from"fs";import{existsSync as Yk,mkdtempSync as Xk,rmSync as Zk}from"fs";import{tmpdir as ew}from"os";import{dirname as go,join as ho}from"path";import{performance as Em}from"perf_hooks";import{spawnSync as tw}from"child_process";import{createHash as Hk}from"crypto";import{existsSync as Wk,mkdirSync as Gk,readFileSync as Uk,renameSync as Jk,writeFileSync as zk}from"fs";import{homedir as Kk}from"os";import{dirname as Qk,join as fo}from"path";function Tm(e){return Hk("sha256").update(e).digest("hex")}function Im(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?fo(t.XDG_CACHE_HOME,"scip-query"):fo(Kk(),".cache","scip-query"));return fo(n,e)}async function jm(e){let{cachePath:t,url:n,expectedSha256:r}=e;if(Wk(t)){let l=Tm(Uk(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=Tm(s);if(a!==r)throw new Error(`downloaded ${n} checksum mismatch: expected ${r}, got ${a}`);Gk(Qk(t),{recursive:!0});let c=`${t}.tmp-${process.pid}`;return zk(c,s),Jk(c,t),{status:"downloaded",path:t,sha256:a}}var nw=12e4,Dm="v1.8.0",rw=`https://github.com/tlaplus/tlaplus/releases/download/${Dm}/tla2tools.jar`,iw="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function Lr(e){let t=e.spawn??tw,n=ow(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??nw,i=Em.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??[])Zk(l,{recursive:!0,force:!0})}let s=Math.round(Em.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:sw(c,o.stdout??"",o.stderr??""),stdout:o.stdout??"",stderr:o.stderr??""}}function ow(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"&&Ae(Lm(e),t)){let o=Lm(e);return Ae(o,t)?{checker:"apalache",command:[o,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:go(e.specPath)}:Er("apalache",`Apalache binary is not available: ${o}`)}let r=yo(e),i=Ae("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!r)return Er(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!i)return Er(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:go(e.specPath)};let s=e.metaDir??Xk(ho(ew(),"scip-tla-tlc-"));return{checker:o,command:["java","-cp",r,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:go(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Er("none",`unknown checker mode: ${n}`)}function Lm(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function yo(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,Om(t),ho(e.projectRoot,"tla2tools.jar"),ho(e.projectRoot,"tools","tla2tools.jar")].filter(r=>typeof r=="string"&&r.length>0).find(r=>Yk(r))??null}function Om(e=process.env){return Im("tla2tools.jar",e)}async function Fm(e={}){let t=e.cachePath??Om(e.env),n=e.expectedSha256??iw,r=e.version??Dm,i=e.url??rw;return{...await jm({cachePath:t,url:i,expectedSha256:n,fetchImpl:e.fetchImpl}),version:r,url:i}}function sw(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=[...Am(n),...Am(t)].slice(0,20);return r.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:r.map(i=>({severity:"error",message:i}))}function Am(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Er(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as aw}from"crypto";import{readFileSync as Mm}from"fs";import{join as _m}from"path";var qm=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),Bm=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),Vm=new Set(["readFileSync","existsSync","statSync"]),cw=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,lw=/^\s*SELECT\b/i;function Hm(e){return cw.test(e)?"write":lw.test(e)?"read":null}var dw=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function uw(e,t){let n=e.match(dw);if(!n)return!1;let r=e.slice(n[0].length);return new RegExp(`^${Le(t)}\\b`).test(r)}function Wm(e,t,n,r=[],i=[]){let o=[],s=fw(e,t,o),a=s.aliases,c=gw(t),l=hw(t),d=yw(t),p=vw(e,t,o),m=Rw(e,t,o);n&&kw(t,n,i,o);let f=new Map((n?.actions??[]).map(x=>[x.name,x])),g=new Set(p.flatMap(x=>x.referents.map(w=>w.match?.symbol).filter(Boolean))),h=new Set((m?.referents??[]).map(x=>x.match?.symbol).filter(Boolean)),y=ww(e,t,p,a,c,l,d,g,h,o,f),S=Pw(e,p,a,c,l,d,o,f);return Iw(e,p,o),jw(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:So(p.flatMap(x=>x.referents))+So(s.referents)+So(m?.referents??[]),staticWrites:y,staticReads:S,waivers:Qw(t),checkedInvariants:[...i],traceStepsChecked:r.length,findings:o,findingGroups:pw(o)}}function pw(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=mw(i.severity,n.severity)}return[...t.values()].sort((n,r)=>r.count-n.count||Ar(r.severity)-Ar(n.severity)||n.groupKey.localeCompare(r.groupKey))}function mw(e,t){return Ar(t)>Ar(e)?t:e}function Ar(e){return e==="error"?2:e==="warning"?1:0}function fw(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=Fr(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}Ww(e,o,l,p,n,c),s.aliases.length===0&&a.add(Oo(p.symbol))}for(let l of a)r.push({variable:o,alias:l})}return{aliases:Kw(r),referents:i}}function gw(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 hw(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 yw(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.ormCalls??[]){let{write:o,read:s}=ao(i);t.push({variable:n,table:i.table,writeMethods:new Set(o),readMethods:new Set(s)})}return t}function bw(e,t,n,r,i,o){return Gm(e,t,(s,a,c)=>ht(e,s,a,c,n,r,i,o))}function Sw(e,t,n,r,i,o){return Gm(e,t,(s,a,c)=>Or(e,s,a,c,n,r,i,o))}function Gm(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=vn(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 vw(e,t,n){return Object.entries(t.actions).map(([r,i])=>{let o=i.code.map(s=>{let a=co(s),c="error"in a?s:a.ref,d=Fr(e,c,n,r).match;return d?(Gw(e,r,s,d,n),"error"in a||!a.window?{ref:s,match:d}:xw(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 xw(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function Rw(e,t,n){let r=t.init;if(!r)return;let i=!!r.waive,o=r.codeRefs.map(s=>{let a=Fr(e,s,n,"Init"),c=a.match;return c?Uw(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 kw(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&&(Nm({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)}),Nm({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 Nm(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 ww(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 x=new Set(f.mapping.writes),w=bw(e,h.match.symbol,r,i,o,s).filter(R=>x.has(R.variable));g.push(...w),p.push(...w)}Cw(f,g,l,d.get(f.name))}let m=t.unmappedWriteScope==="actions"?[]:Bw(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),$w(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 Ro(p)}function $w(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function Cw(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)&&!dn(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}${Dr(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)&&!dn(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}${Dr(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)&&!dn(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 Pw(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=Or(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=Sw(e,p.match.symbol,n,r,i,o).filter(y=>g.has(y.variable));d.push(...h),c.push(...h)}Tw(l,d,s,a.get(l.name))}return ko(c)}function Tw(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}${Dr(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)&&!dn(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}${Dr(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)&&!dn(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 Iw(e,t,n){for(let r of t){if(r.mapping.calls.length===0)continue;let i=r.mapping.calls.map(s=>Fr(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 jw(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=zw(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=Ew(e,t,n,r,i,o,s,a);return c||_w(e,t,n,r,i,o,s,a)}function Or(e,t,n,r,i,o=[],s=[],a=[]){let c=Lw(e,t,n,r,i,o,s,a);return c||qw(e,t,n,r,i,o,s,a)}function Ew(e,t,n,r,i,o=[],s=[],a=[]){let c=_r(e,t);if(!c)return null;let l=[],d=p=>{if(!(p.startPosition.row>r||p.endPosition.row<n)){Aw(e,t,p,i,l),Um(e,t,p,o,"write",l),Jm(e,t,p,s,"write",l),zm(e,t,p,a,"write",l);for(let m of p.children)d(m)}};return d(c.rootNode),Ro(l)}function Lw(e,t,n,r,i,o=[],s=[],a=[]){let c=_r(e,t);if(!c)return null;let l=[],d=p=>{if(!(p.startPosition.row>r||p.endPosition.row<n)){Fw(e,t,p,i,l),Um(e,t,p,o,"read",l),Jm(e,t,p,s,"read",l),zm(e,t,p,a,"read",l);for(let m of p.children)d(m)}};return d(c.rootNode),ko(l)}function Aw(e,t,n,r,i){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let o=n.childForFieldName("left")??n.namedChild(0);o&&ln(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&&ln(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&&ln(e,t,o,"update",r,i);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let o=n.namedChild(0);o&&ln(e,t,o,"delete",r,i);return}if(n.type==="call_expression"){let o=n.childForFieldName("function")??n.namedChild(0);if(!o||!Qm(o))return;ln(e,t,o,"mutation-call",r,i)}}}function Um(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?vo(s):null;if(!a||!(i==="write"?Bm:Vm).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 vo(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 Jm(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=Dw(a);if(c!==null&&Hm(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&&vo(p))??"call";o.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${m}(${Ow(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?Q(d.symbol):void 0})}}}function Dw(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function Ow(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function zm(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?vo(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(!Km(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 Km(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 Fw(e,t,n,r,i){if(!(!Nw(n)||Mw(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 Nw(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function Mw(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&&bo(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&&bo(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&Qm(n)&&bo(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 bo(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function Qm(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&qm.has(t.text))}function ln(e,t,n,r,i,o){for(let s of i){if(!Jw(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 _w(e,t,n,r,i,o=[],s=[],a=[]){let l=Mm(_m(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(uw(f,g.alias))continue;let h=Le(g.alias);if(!new RegExp(`(?:\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${h}\\b\\s*\\.\\s*(?:${[...qm].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})}Ym(e,t,m,f,o,Bm,d),Xm(e,t,m,f,s,"write",d),Zm(e,t,m,f,a,"write",d)}return Ro(d)}function qw(e,t,n,r,i,o=[],s=[],a=[]){let l=Mm(_m(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})}Ym(e,t,m,f,o,Vm,d),Xm(e,t,m,f,s,"read",d),Zm(e,t,m,f,a,"read",d)}return ko(d)}function Ym(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 Xm(e,t,n,r,i,o,s){if(i.length!==0&&Hm(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 Zm(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(!Km(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 Bw(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 Fr(e,t,n,r){let i=vn(e,t),o=i.match??(t.includes("#")?vn(e,t.replace("#","/")).match:null);return i.match&&i.total>1&&!Vw(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.`,Hw(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 Vw(e){return/[/#:]/.test(e)}function Hw(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function Ww(e,t,n,r,i,o=!1){let s=xo(e,r);if(s===null||Yw.has(s)||o)return;let a=wo.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 Gw(e,t,n,r,i){let o=xo(e,r);o===null||ef.has(o)||wo.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 Uw(e,t,n,r,i){let o=xo(e,n);o===null||ef.has(o)||i||wo.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 xo(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function je(e,t,n){return Sn(e,t).filter(i=>i.startLine<=n&&i.endLine>=n).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine))[0]??null}function Jw(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${Le(e)}([^A-Za-z0-9_$]|$)`).test(t)}function zw(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 Ro(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 ko(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 Kw(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 So(e){return e.filter(t=>t.match).length}function Dr(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function dn(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function Qw(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 wo=new Set(_o()),ef=new Set(Mo()),Yw=new Set(qo());function W(e,t,n,r){let i=JSON.stringify({category:e,evidence:n,...r});return{id:`TLA${aw("sha1").update(i).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...r}}import{readFileSync as Xw}from"fs";import{basename as Zw,join as tf}from"path";var $o=/^[A-Za-z_][A-Za-z0-9_]*$/;function nf(e,t,n={}){let r=[],i=Sn(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=Xw(tf(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&&$o.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:n$(s,T)),f=null,g;if(m.length>0)g=i.filter(T=>a(T)&&T.parentTypeName===null);else{if(f=e$(e,t,i,a),!f){let T=i.some(O=>!a(O)&&!O.isTypeLike&&O.parentTypeName!==null&&$o.test(O.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=>r$(T,s,t,r,f?.className)),y=h.map(T=>({variable:T.name,alias:T.leaf})),S=[],x=new Set;for(let T of g){let O=ht(e,t,T.startLine,T.endLine,y);if(O.length===0)continue;let Z=Or(e,t,T.startLine,T.endLine,y),F=a$(rf(T.leaf),x);S.push({name:F,leaf:T.leaf,codeRef:t$(t,T,f?.className),startLine:T.startLine,writes:[...new Set(O.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 w=n.moduleName??c$(t),R=n.specDir??tf("specs",w),D=l$(w,h,S,t),_=d$(),z=u$(w,R,t,h,S);return{moduleName:w,file:t,variables:h,actions:S,warnings:r,spec:D,cfg:_,map:z}}function e$(e,t,n,r){let i=new Map;for(let s of n){if(r(s)||s.isTypeLike||s.parentTypeName===null||!$o.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 t$(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function n$(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function r$(e,t,n,r,i){let o=i$(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=o$(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 i$(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function o$(e,t){let r=t.match(new RegExp(`\\b${p$(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,o=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(r){let l=s$(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 s$(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 rf(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function a$(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}${r++}`;return t.add(n),n}function c$(e){let n=Zw(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return rf(n||"Model")}function l$(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(`
549
- `)}function d$(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
550
- `)}function u$(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)}
551
- `}function p$(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function of(e,t){let n=Object.keys(t.variables),r=Object.entries(t.actions).map(([i,o])=>{let s=o.code[0]??"",a=s?No(e,s):null;return{action:i,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:o.writes}});return{recorderSource:m$(n),wiring:r,variables:n}}function m$(e){return`/**
548
+ ${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
+ ${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(`
551
+ `)}function M$(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
552
+ `)}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`/**
552
554
  * Generated by 'scip-query tla instrument'. Dependency-free trace recorder.
553
555
  *
554
556
  * Usage inside a mapped action (record the model-visible slice around the
@@ -591,15 +593,15 @@ export function tlaRecord(action: string, before: Record<string, unknown>, after
591
593
  steps.push({ action, before, after });
592
594
  writeFileSync(tracePath, JSON.stringify(steps, null, 2));
593
595
  }
594
- `}import{copyFileSync as f$,mkdtempSync as g$,readdirSync as h$,rmSync as y$,writeFileSync as sf}from"fs";import{tmpdir as b$}from"os";import{basename as S$,dirname as v$,join as un}from"path";function Nr(e,t){let n=new Map;for(let r of t)n.set(r.action,(n.get(r.action)??0)+1);return e.map(r=>({action:r,stepsObserved:n.get(r)??0}))}function x$(e,t,n,r="Next"){if(n.length===0)return{error:"trace has no steps"};let i=[],o=n[0];if(!o.before)return{error:"trace step 0 must include a full `before` state"};let s=[],a={...o.before},c=h=>{let y={};for(let[S,x]of Object.entries(h)){if(!t.includes(S))continue;let w=k$(x);w!==void 0&&(y[S]=w)}return y};s.push(c(a));for(let h of n){if(h.before)for(let[y,S]of Object.entries(h.before))y in a||(a[y]=S);Object.assign(a,h.after??{}),s.push(c(a))}let l=t.filter(h=>s.every(y=>h in y)),d=t.filter(h=>!l.includes(h));if(l.length===0)return{error:"no mapped variable had a scalar-encodable value in every trace state"};d.length>0&&i.push(`variables not pinned by the trace (missing or non-scalar values): ${d.join(", ")} \u2014 divergence in these variables is NOT checked.`);let p=`${e}Trace`,m=s.map(h=>` [${l.map(y=>`${y} |-> ${cf(h[y])}`).join(", ")}]`).join(`,
596
+ `}import{copyFileSync as V$,mkdtempSync as H$,readdirSync as W$,rmSync as G$,writeFileSync as bf}from"fs";import{tmpdir as U$}from"os";import{basename as J$,dirname as z$,join as pn}from"path";function _r(e,t){let n=new Map;for(let r of t)n.set(r.action,(n.get(r.action)??0)+1);return e.map(r=>({action:r,stepsObserved:n.get(r)??0}))}function K$(e,t,n,r="Next"){if(n.length===0)return{error:"trace has no steps"};let i=[],o=n[0];if(!o.before)return{error:"trace step 0 must include a full `before` state"};let s=[],a={...o.before},c=h=>{let y={};for(let[S,v]of Object.entries(h)){if(!t.includes(S))continue;let k=Y$(v);k!==void 0&&(y[S]=k)}return y};s.push(c(a));for(let h of n){if(h.before)for(let[y,S]of Object.entries(h.before))y in a||(a[y]=S);Object.assign(a,h.after??{}),s.push(c(a))}let l=t.filter(h=>s.every(y=>h in y)),d=t.filter(h=>!l.includes(h));if(l.length===0)return{error:"no mapped variable had a scalar-encodable value in every trace state"};d.length>0&&i.push(`variables not pinned by the trace (missing or non-scalar values): ${d.join(", ")} \u2014 divergence in these variables is NOT checked.`);let p=`${e}Trace`,m=s.map(h=>` [${l.map(y=>`${y} |-> ${vf(h[y])}`).join(", ")}]`).join(`,
595
597
  `),f=[`---- MODULE ${p} ----`,"\\* Generated trace-validation harness. Checks that the recorded execution",`\\* is a behavior of ${e}!${r}. TLC deadlocks at the first`,"\\* divergent step; a clean run means the model accepts the trace.",`EXTENDS ${e}, Naturals, Sequences`,"","VARIABLE traceIdx","","TraceStates ==","<<",m,">>","","TraceInit =="," /\\ traceIdx = 1",...l.map(h=>` /\\ ${h} = TraceStates[1].${h}`),"","TraceStep =="," /\\ traceIdx < Len(TraceStates)"," /\\ traceIdx' = traceIdx + 1",` /\\ ${r}`,...l.map(h=>` /\\ ${h}' = TraceStates[traceIdx + 1].${h}`),"","TraceDone =="," /\\ traceIdx = Len(TraceStates)"," /\\ UNCHANGED <<vars, traceIdx>>","","TraceNext == TraceStep \\/ TraceDone","","TraceSpec == TraceInit /\\ [][TraceNext]_<<vars, traceIdx>>","","\\* Reaching the last pinned state means the model accepted every step.","TraceProgress == traceIdx \\in 1..Len(TraceStates)","====",""].join(`
596
598
  `),g=["SPECIFICATION TraceSpec","INVARIANT TraceProgress",""].join(`
597
- `);return{moduleName:p,moduleText:f,cfgText:g,variables:l,skippedVariables:d,states:s.length,warnings:i}}function af(e){let t=e.mappedActions??[],n=x$(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:Nr(t,[])};let r=g$(un(b$(),"scip-tla-trace-"));try{let i=v$(e.specPath);for(let d of h$(i))d.endsWith(".tla")&&f$(un(i,d),un(r,d));let o=un(r,`${n.moduleName}.tla`),s=un(r,`${n.moduleName}.cfg`);sf(o,n.moduleText),sf(s,n.cfgText);let a=Lr({...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:Nr(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:Nr(t,e.steps)};let c=R$(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:Nr(t,l)}}finally{y$(r,{recursive:!0,force:!0})}}function R$(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 k$(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 cf(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>cf(t)).join(", ")}>>`}function lf(e){return S$(e).replace(/\.tla$/i,"")}import{mkdirSync as uf,writeFileSync as pf}from"fs";import{dirname as w$,join as Ft}from"path";var $$=async(...e)=>{let{args:t,opts:n}=hc(e),r=L(t,0);if(r==="fetch-tools"){let o=await Fm();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=B(t,1);if(!o)throw new Error("tla scaffold requires a target source file");ce(s=>C$(s,t,n,o));return}if(r==="instrument"){let o=B(t,1);ce(s=>P$(s,t,n,o));return}if(r==="trace-check"){let o=B(t,1);if(!o)throw new Error("tla trace-check requires a spec path");ce(s=>T$(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=B(t,1);if(!i)throw new Error("tla verify requires a spec path");ce(o=>E$(o,t,n,i))};function C$(e,t,n,r){let i=e.config.projectRoot,o=nf(e,r,{moduleName:k(n,"moduleName"),specDir:k(n,"out")}),s=k(n,"out")??Ft("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:Ft(a,`${o.moduleName}.tla`),body:o.spec},{path:Ft(a,`${o.moduleName}.cfg`),body:o.cfg},{path:Ft(a,`${o.moduleName}.scip-tla.json`),body:o.map}];for(let d of l)if(!c&&pn(d.path))throw new Error(`refusing to overwrite ${d.path} (pass --force to replace scaffold output)`);uf(a,{recursive:!0});for(let d of l)pf(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 ${Ft(s,`${o.moduleName}.tla`)}'.`)}function P$(e,t,n,r){let i=e.config.projectRoot,o=k(n,"map")??(r?Tr(r):void 0);if(!o)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=Pr(i,o);if(!s.loaded)throw new Error(s.errors.join(`
598
- `));let{contract:a,mapDir:c}=s.loaded,l=of(e,a),d=k(n,"out")??Ft(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")&&pn(p))throw new Error(`refusing to overwrite ${p} (pass --force to replace the recorder)`);if(uf(w$(p),{recursive:!0}),pf(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 T$(e,t,n,r){let i=e.config.projectRoot,o=ue(i,r);if(!o||!pn(o))throw new Error(`TLA+ spec not found: ${r}`);let s=k(n,"map")??Tr(r),a=Pr(i,s);if(!a.loaded)throw new Error(a.errors.join(`
599
- `));let{contract:c}=a.loaded,l=Ct(n,"trace"),p=uo(i,[...c.traces,...l]).flatMap(g=>lo(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=af({specPath:o,baseModuleName:lf(o),mappedVariables:Object.keys(c.variables),mappedActions:Object.keys(c.actions),steps:p,nextOperator:k(n,"next"),toolOptions:{projectRoot:i,tlaToolsJar:k(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")&&I$(m.actionCoverage),process.exitCode=f}function I$(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 j$(e,t,n,r){let i=k(r,"map");if(i)return{mapArg:i};let o=Tr(t),s=ue(e,o);if(s&&pn(s))return{mapArg:o};let a=Hp(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 E$(e,t,n,r){let i=e.config.projectRoot,o=ue(i,r);if(!o||!pn(o))throw new Error(`TLA+ spec not found: ${r}`);let{mapArg:s,mappingDiscoveredBy:a}=j$(i,r,o,n),c=Pr(i,s);if(!c.loaded)throw new Error(c.errors.join(`
600
- `));let{contract:l,mapPath:d,mapDir:p}=c.loaded,m=k(n,"config")??l.config,f=Mp(i,p,m),g=A$(k(n,"checker")??"auto"),h=k(n,"tlaTools"),y=L$(i,r,o,h)??_p(i,r),S=Bp(f),x=Ct(n,"trace"),R=uo(i,[...l.traces,...x]).map(F=>({tracePath:F,...lo(i,F)})),D=R.flatMap(F=>F.steps),_=new Set(x),z=R.filter(F=>_.has(F.tracePath)).flatMap(F=>F.errors),T=Wm(e,l,y,D,S);for(let F of[...c.errors,...z])T.findings.push({id:`TLA-CONTRACT-${T.findings.length+1}`,severity:"error",evidence:"contract",category:"contract",message:F,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 O=Lr({projectRoot:i,specPath:o,configPath:f??void 0,checker:g,tlaToolsJar:h,apalacheBin:k(n,"apalache"),length:C(n,"length",10),timeoutMs:U(n,"timeoutMs")});O.status==="skipped"&&g!=="none"&&T.findings.push({id:"TLA-MODEL-CHECKER-UNAVAILABLE",severity:"warning",evidence:"unknown",category:"contract",message:O.diagnostics.map(F=>F.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:O,conformance:T,exitCode:D$(O,T,b(n,"allowUnknown"))};if(b(n,"json")){I("tla",t,n,Z),process.exitCode=Z.exitCode;return}O$(Z,b(n,"full")),process.exitCode=Z.exitCode}function L$(e,t,n,r){let i=yo({projectRoot:e,specPath:n,tlaToolsJar:r,checker:"sany"});if(!i)return null;let o=Tp({specPath:n,jarPath:i});return o?qp(e,t,o):null}var mf=[{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",v,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:$$}];function A$(e){if(!Np(e))throw new Error(`unknown checker mode: ${e}`);return e}function D$(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 df=3;function O$(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=N$(e);console.log(`
601
- 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 M$(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)ff(o);return}F$(e.conformance)}function F$(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
599
+ `);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
+ `));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
+ `));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(`
603
+ 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(`
602
604
  Finding groups (${e.findingGroups.length}) \u2014 pass --full for every finding ungrouped:`);for(let n of e.findingGroups){console.log(`
603
- [${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let i of n.findingIds.slice(0,df)){let o=t.get(i);o&&ff(o)}let r=n.count-df;r>0&&console.log(` ... and ${r} more in this group (use --full to show all)`)}}function N$(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 M$(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 ff(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(`
604
- [${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 gf=["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"],_$=[Rm,Cm,km,jr,$m,Pm,mf,wm],hf=_$.flat(),q$=new Map(hf.map(e=>[e.id,e]));for(let e of hf)if(!gf.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Nt=gf.map(e=>B$(e));function B$(e){let t=q$.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var V$=Nt.slice(0,Co("plan-context")),H$=Nt.slice(Mr("drift"),Co("self-audit")),W$=Nt.slice(Mr("convergence"),Co("slice")),G$=Nt.slice(Mr("redundant-reexports")),vD=[{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:Gu},{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:Uu},{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:Ju},...V$,{id:Jr,command:Jr,description:"Internal diff-impact batch worker",hidden:!0,options:[u("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:zu},{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:Ku},...H$,{id:Ur,command:Ur,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:Qu},{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:Yu},{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:Xu},{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:Zu},{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:ep},...W$,{id:"install-skills",command:"install-skills",description:`Install skills (${Yn.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:$("Maintenance"),handler:rp},{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:ip},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:ll},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:dl},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:$("Maintenance"),handler:op},{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:sp},{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:ap},...G$,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:$("Maintenance"),handler:lp},{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:dp},{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:up},{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:pp},{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:mp},{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:hp},{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:gp},{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:yp},{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:bp},{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:Sp},{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:Rp}];function Mr(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 Co(e){return Mr(e)+1}export{vD as commandDescriptors};
605
- //# sourceMappingURL=command-descriptors-SWFWGIFK.js.map
605
+ [${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