scip-query 0.19.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/dist/augment-vue-worker.js +1 -1
  2. package/dist/{chunk-YHYTDWFT.js → chunk-24ET4VLC.js} +2 -2
  3. package/dist/{chunk-IXORBCMR.js → chunk-2NA6TYP4.js} +2 -2
  4. package/dist/{chunk-XKWEMFHP.js → chunk-2WCXKANA.js} +2 -2
  5. package/dist/{chunk-GJ3FR5WG.js → chunk-34MLC6UI.js} +2 -2
  6. package/dist/{chunk-PAZFJMXB.js → chunk-3WLRW5TC.js} +2 -2
  7. package/dist/{chunk-EZHARAL4.js → chunk-4BU54UJG.js} +2 -2
  8. package/dist/{chunk-XTSVYYAL.js → chunk-4CZJ4YJB.js} +2 -2
  9. package/dist/{chunk-TCVRJ56J.js → chunk-4FMT4HPC.js} +2 -2
  10. package/dist/{chunk-7FG5M53V.js → chunk-53SUJOJA.js} +2 -2
  11. package/dist/{chunk-YBAC3RON.js → chunk-5GOBZI34.js} +2 -2
  12. package/dist/{chunk-X36LKKVG.js → chunk-5OZCNAVM.js} +2 -2
  13. package/dist/{chunk-FMC3BI4I.js → chunk-5TEUKVSM.js} +2 -2
  14. package/dist/{chunk-WT7TOU2C.js → chunk-5W2VAEVR.js} +2 -2
  15. package/dist/{chunk-AWSRND4W.js → chunk-63P42UR6.js} +2 -2
  16. package/dist/{chunk-GNJHHPZE.js → chunk-64QITTX7.js} +2 -2
  17. package/dist/{chunk-XPYXEEDO.js → chunk-6O5JOS7T.js} +2 -2
  18. package/dist/{chunk-X65VYV2S.js → chunk-6PKO2TNZ.js} +2 -2
  19. package/dist/{chunk-X3OOU7CF.js → chunk-7SGOWD2Y.js} +2 -2
  20. package/dist/{chunk-ZXWFN7CK.js → chunk-7TJJY2C3.js} +2 -2
  21. package/dist/{chunk-OGHGTD6Z.js → chunk-AEM24WSF.js} +2 -2
  22. package/dist/{chunk-IWK562KR.js → chunk-AGTATREV.js} +2 -2
  23. package/dist/{chunk-SATRCB5O.js → chunk-AOSFSYEA.js} +2 -2
  24. package/dist/{chunk-3OSRXJKK.js → chunk-APLNTJPJ.js} +2 -2
  25. package/dist/{chunk-TDGCALH6.js → chunk-AYRHVJXW.js} +2 -2
  26. package/dist/{chunk-AM2LGOEX.js → chunk-B2WQKQKP.js} +2 -2
  27. package/dist/{chunk-F5L7WEZF.js → chunk-BBBKPOIT.js} +2 -2
  28. package/dist/{chunk-2FAJTZSX.js → chunk-BCMOTIB6.js} +2 -2
  29. package/dist/{chunk-RJLU7IMR.js → chunk-BMTBVMA3.js} +2 -2
  30. package/dist/{chunk-JFGUBZWE.js → chunk-C3KCSAQ4.js} +2 -2
  31. package/dist/{chunk-FLIF3JWA.js → chunk-CAKPEQZB.js} +2 -2
  32. package/dist/{chunk-PKAPOFF5.js → chunk-CIYUFF24.js} +2 -2
  33. package/dist/{chunk-7EI4MU5A.js → chunk-CKFMZE77.js} +2 -2
  34. package/dist/{chunk-A45K6VUK.js → chunk-DCDOGW32.js} +2 -2
  35. package/dist/{chunk-4ZCNFENR.js → chunk-DFQNE73Y.js} +2 -2
  36. package/dist/{chunk-J3U47L4Q.js → chunk-DO775SYA.js} +2 -2
  37. package/dist/{chunk-NEG77KKH.js → chunk-DRH3AD7W.js} +2 -2
  38. package/dist/{chunk-UVMME4FI.js → chunk-DZXFZAZO.js} +2 -2
  39. package/dist/{chunk-GMZYT44R.js → chunk-E3KWOHH7.js} +2 -2
  40. package/dist/{chunk-F334Z5UA.js → chunk-EMIIOOTM.js} +2 -2
  41. package/dist/{chunk-GBB2RUDN.js → chunk-ESNRT7QN.js} +130 -130
  42. package/dist/{chunk-RIGY5DDE.js → chunk-FB6IKAKZ.js} +2 -2
  43. package/dist/{chunk-BGUYAA3Q.js → chunk-FBUNGRKI.js} +2 -2
  44. package/dist/{chunk-M2TRDR25.js → chunk-FC5K7T35.js} +1 -1
  45. package/dist/{chunk-4ZHJAHLE.js → chunk-FHLYJVXF.js} +2 -2
  46. package/dist/{chunk-KWBA6FDD.js → chunk-FRXB74RQ.js} +2 -2
  47. package/dist/{chunk-BYPVNKJT.js → chunk-FTRNGQGR.js} +2 -2
  48. package/dist/{chunk-54UYBTZW.js → chunk-FUFNRZFJ.js} +2 -2
  49. package/dist/{chunk-QNMOZ3CJ.js → chunk-GAE7WCBK.js} +2 -2
  50. package/dist/{chunk-547VY366.js → chunk-GIHVWNKQ.js} +2 -2
  51. package/dist/{chunk-AEDB4WXE.js → chunk-HCS5LB6U.js} +2 -2
  52. package/dist/{chunk-UXOVHGT6.js → chunk-HFBNIIZX.js} +2 -2
  53. package/dist/{chunk-JHK2DMUQ.js → chunk-HGFDYOVB.js} +1 -1
  54. package/dist/{chunk-6SHX42QQ.js → chunk-IOOCKVUA.js} +2 -2
  55. package/dist/{chunk-XDVT7QPG.js → chunk-J4MYRIYT.js} +2 -2
  56. package/dist/{chunk-TAB7AWKO.js → chunk-J5XJWCB3.js} +2 -2
  57. package/dist/{chunk-PXJIEMND.js → chunk-JBZXJXIS.js} +2 -2
  58. package/dist/{chunk-UJL3N6TC.js → chunk-JJZRS2OP.js} +2 -2
  59. package/dist/chunk-KC2IFAAU.js +3 -0
  60. package/dist/{chunk-4XTPZ5CR.js → chunk-KMOMNTB4.js} +2 -2
  61. package/dist/{chunk-YYR7ADNB.js → chunk-KMUFGAIK.js} +2 -2
  62. package/dist/{chunk-DWN7QDTV.js → chunk-LF5CIKWZ.js} +2 -2
  63. package/dist/{chunk-ZL5Y23AJ.js → chunk-LM72NQ7T.js} +1 -1
  64. package/dist/{chunk-3KQOIXLO.js → chunk-LQUDSHLB.js} +2 -2
  65. package/dist/{chunk-VV5WJLRO.js → chunk-MP43RX4O.js} +1 -1
  66. package/dist/{chunk-D5OXYOJP.js → chunk-MQ2B33LQ.js} +1 -1
  67. package/dist/{chunk-EZGT3NJX.js → chunk-NTOBQK5H.js} +2 -2
  68. package/dist/{chunk-TOYQTO44.js → chunk-OLG2YPLS.js} +2 -2
  69. package/dist/{chunk-J65FQLDL.js → chunk-OOUJBAKJ.js} +2 -2
  70. package/dist/{chunk-PBADFBRR.js → chunk-OQ6TCHBB.js} +2 -2
  71. package/dist/{chunk-BOXAKNN6.js → chunk-PNESKY2Z.js} +2 -2
  72. package/dist/{chunk-TDZXQAH7.js → chunk-PYMZU5EG.js} +2 -2
  73. package/dist/{chunk-HOXI4F5I.js → chunk-Q2WEWIKX.js} +2 -2
  74. package/dist/{chunk-DQIJMKNE.js → chunk-QHKXGMOI.js} +2 -2
  75. package/dist/{chunk-MTFHE7ZO.js → chunk-RPEA7P5Z.js} +2 -2
  76. package/dist/{chunk-DV6B262O.js → chunk-SJ6XSCG7.js} +2 -2
  77. package/dist/{chunk-LJD7V7UO.js → chunk-SSXEYWN3.js} +2 -2
  78. package/dist/{chunk-XESK6725.js → chunk-SYGAA54M.js} +2 -2
  79. package/dist/{chunk-TC3X33N6.js → chunk-TYEGFDOP.js} +2 -2
  80. package/dist/chunk-UJKZQLDB.js +2 -0
  81. package/dist/{chunk-QB5WSOTY.js → chunk-US44MEVU.js} +2 -2
  82. package/dist/{chunk-2ZNZSNVW.js → chunk-V5WBVF6K.js} +2 -2
  83. package/dist/{chunk-S65OEY2G.js → chunk-V7J4A3AH.js} +2 -2
  84. package/dist/{chunk-J6BR4MD6.js → chunk-VIKEPD4D.js} +2 -2
  85. package/dist/{chunk-XDSB47KO.js → chunk-WAU7HVDI.js} +2 -2
  86. package/dist/{chunk-T5CSWYAZ.js → chunk-WCZAABYF.js} +2 -2
  87. package/dist/{chunk-KD6TPIXM.js → chunk-WFRET75Z.js} +2 -2
  88. package/dist/chunk-WWCZCH7W.js +3 -0
  89. package/dist/{chunk-G6RQVDTI.js → chunk-XCPE3G75.js} +2 -2
  90. package/dist/{chunk-QN67MWDU.js → chunk-XYBNOILR.js} +2 -2
  91. package/dist/{chunk-MFBXBLHA.js → chunk-XZXUMGAA.js} +2 -2
  92. package/dist/{chunk-QHOUNTDZ.js → chunk-YCSTKIYU.js} +2 -2
  93. package/dist/{chunk-ZNSLF5AC.js → chunk-YGQBJUS6.js} +2 -2
  94. package/dist/{chunk-6DHPQS72.js → chunk-YILKXTIY.js} +2 -2
  95. package/dist/{chunk-G6QQCX45.js → chunk-ZJGZCBYT.js} +2 -2
  96. package/dist/{chunk-MDDF67O2.js → chunk-ZNK6K3LB.js} +2 -2
  97. package/dist/cli.js +1 -1
  98. package/dist/{command-descriptors-SWFWGIFK.js → command-descriptors-3EJHQLQZ.js} +55 -55
  99. package/dist/direct-navigation-C2A44KFT.js +3 -0
  100. package/dist/index.js +1 -1
  101. package/dist/queries/affected.js +1 -1
  102. package/dist/queries/architecture.js +1 -1
  103. package/dist/queries/bottlenecks.js +1 -1
  104. package/dist/queries/by-kind.js +1 -1
  105. package/dist/queries/call-graph.js +1 -1
  106. package/dist/queries/change-surface.js +1 -1
  107. package/dist/queries/cleanup-plan.js +1 -1
  108. package/dist/queries/co-change.js +1 -1
  109. package/dist/queries/code.js +1 -1
  110. package/dist/queries/complexity-hotspots.js +1 -1
  111. package/dist/queries/complexity.js +1 -1
  112. package/dist/queries/convergence.js +1 -1
  113. package/dist/queries/coupling.js +1 -1
  114. package/dist/queries/cycles.js +1 -1
  115. package/dist/queries/dataflow.js +1 -1
  116. package/dist/queries/dead.js +1 -1
  117. package/dist/queries/decorative-checkers.js +1 -1
  118. package/dist/queries/deep-chains.js +1 -1
  119. package/dist/queries/deps.js +1 -1
  120. package/dist/queries/diff-gate.js +1 -1
  121. package/dist/queries/diff-impact.js +1 -1
  122. package/dist/queries/doc-drift.js +1 -1
  123. package/dist/queries/drift.js +1 -1
  124. package/dist/queries/duplicate-bodies.js +1 -1
  125. package/dist/queries/extract-candidates.js +1 -1
  126. package/dist/queries/fan.js +1 -1
  127. package/dist/queries/health.js +1 -1
  128. package/dist/queries/hierarchy.js +1 -1
  129. package/dist/queries/hotspots.js +1 -1
  130. package/dist/queries/imports.js +1 -1
  131. package/dist/queries/incomplete-migration.js +1 -1
  132. package/dist/queries/index.js +1 -1
  133. package/dist/queries/isolated.js +1 -1
  134. package/dist/queries/locality-candidates.js +1 -1
  135. package/dist/queries/members.js +1 -1
  136. package/dist/queries/methods.js +1 -1
  137. package/dist/queries/not-implemented.js +1 -1
  138. package/dist/queries/outline.js +1 -1
  139. package/dist/queries/passthrough-candidates.js +1 -1
  140. package/dist/queries/plan-context.js +1 -1
  141. package/dist/queries/react-component-duplicates.js +1 -1
  142. package/dist/queries/react-hook-candidates.js +1 -1
  143. package/dist/queries/react-large-component-pressure.js +1 -1
  144. package/dist/queries/recent-duplicates.js +1 -1
  145. package/dist/queries/redundant-reexports.js +1 -1
  146. package/dist/queries/refs.js +1 -1
  147. package/dist/queries/self-audit.js +1 -1
  148. package/dist/queries/similar-chains.js +1 -1
  149. package/dist/queries/similar-files.js +1 -1
  150. package/dist/queries/similar-signatures.js +1 -1
  151. package/dist/queries/similar.js +1 -1
  152. package/dist/queries/slice.js +1 -1
  153. package/dist/queries/stale-abstractions.js +1 -1
  154. package/dist/queries/surface.js +1 -1
  155. package/dist/queries/symbols.js +1 -1
  156. package/dist/queries/system.js +1 -1
  157. package/dist/queries/test-quality.js +1 -1
  158. package/dist/queries/trace.js +1 -1
  159. package/dist/queries/twin-ab.js +1 -1
  160. package/dist/queries/twin-drift.js +1 -1
  161. package/dist/queries/unused-imports.js +1 -1
  162. package/dist/queries/unused-params.js +1 -1
  163. package/dist/queries/vue-component-duplicates.js +1 -1
  164. package/dist/queries/vue-composable-candidates.js +1 -1
  165. package/dist/queries/vue-large-view-pressure.js +1 -1
  166. package/dist/queries/wrapper-candidates.js +1 -1
  167. package/dist/reindex-worker.js +5 -5
  168. package/dist/reindex.js +15 -15
  169. package/dist/runtime.js +1 -1
  170. package/dist/rust-semantic-session-server.js +1 -1
  171. package/dist/rust-semantic-session-worker.js +1 -1
  172. package/dist/rust-semantic-worker.js +1 -1
  173. package/dist/watch-server.js +1 -1
  174. package/package.json +1 -1
  175. package/dist/chunk-42QYU6FD.js +0 -3
  176. package/dist/chunk-AERYQJ52.js +0 -3
  177. package/dist/chunk-OYYZLJVT.js +0 -2
  178. package/dist/direct-navigation-RKMPBXMI.js +0 -3
@@ -1,5 +1,5 @@
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(`
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-DRH3AD7W.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-RPEA7P5Z.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-ESNRT7QN.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
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
4
  `),i=(n.rust===!0?Hf(e):Io(e)).split(`
5
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(`
@@ -41,7 +41,7 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
41
41
  `),console.log("Or download manually:")):Yt()==="win32"?(console.log("On Windows the scip binary ships via the npm sidecar package scip-query-scip-windows,"),console.log("installed automatically with scip-query. If it is missing:"),console.log(" npm install -g scip-query-scip-windows"),console.log(`Or set ${hl} to a local scip.exe path.
42
42
  `),console.log("Upstream release page:")):console.log("Download from:"),console.log(e?` ${e.url}
43
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)
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 _x,renameSync as qx,rmSync as Bx,unlinkSync as Vx,writeFileSync as Hx}from"fs";import{dirname as Rr,extname as Wx,join as mt,resolve as Gx}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
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
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(`
47
47
  SELECT relative_path, language, position_encoding, text
@@ -273,7 +273,7 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
273
273
  ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,p]of Object.entries({documents:i,chunks:o,definitions:s,mentions:a}))for(let m of p){let f=JSON.stringify([d,m]),g=c.get(m.relative_path)??[];g.push(f),c.set(m.relative_path,g)}let l=new Map;for(let[d,p]of[...c].sort(([m],[f])=>m.localeCompare(f))){let m=Jh("sha256");for(let f of p.sort())m.update(f).update(`
274
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
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(`
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 KP,relative as QP,resolve as YP,sep as XP}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
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(`
278
278
  DELETE FROM mentions
279
279
  WHERE chunk_id IN (
@@ -330,21 +330,21 @@ ${r.message}`:""}var nl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
330
330
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
331
331
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
332
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.
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",()=>Ko(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
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
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(`
336
336
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
337
337
  `+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
338
  `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
339
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
+ `),()=>{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 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"?fv(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&gv(n),...o,clojureConfigPath:s,files:$n(e,{language:r,markerFiles:i})}]}))}function fv(e){return e?.trim()||void 0}function gv(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=hv(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?yv(S):null})}return{totalEvents:r.length,windowStart:t.sinceMs??null,checks:c.sort((l,d)=>l.check.localeCompare(d.check))}}function hv(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 yv(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 bv}from"child_process";import{statSync as Sv}from"fs";import{isAbsolute as vv,join as xv,relative as Rv}from"path";import{watch as kv}from"chokidar";import wv 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=wv(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let t=kv(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=vv(t)?t:xv(this.projectRoot,t);return Rv(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=bv(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:a.indexPath,SCIP_REINDEX_OUTPUT_DB:a.dbPath,SCIP_REINDEX_LANGUAGES:(s.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(s.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:t.kind,SCIP_REINDEX_TRIGGER_DETAIL:t.detail??""},stdio:"pipe"});d.on("exit",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=Sv(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 Uv}from"fs";import{existsSync as lu,mkdirSync as du,readFileSync as uu,writeFileSync as pu}from"fs";import{homedir as $v}from"os";import{dirname as mu,isAbsolute as Cv,join as Ji,relative as cu,resolve as Pv}from"path";function fu(e,t={}){let n=t.dossierDir?Pv(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=Fv({...e,generatedAt:new Date().toISOString(),healthDossier:r},e.projectRoot);try{return Av(r.markdownPath,Tv(i),r),Dv(r.jsonPath,i,r),r}catch(o){return{...r,status:"failed",error:o instanceof Error?o.message:String(o)}}}function Tv(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${Ki(e.health)}`,"","## Items That Need Attention","",...Iv(e),"","## Blocked Or Unavailable Checks","",...jv(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","",...Ev(e),"","## JSON","",`Machine-readable report: \`${Lv(e)}\``,""].join(`
341
+ `)}`}function Iv(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 jv(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 Ev(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 Lv(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function Av(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 Dv(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&&Ov(i,r)){n.unchanged.push(e);return}pu(e,r),n.written.push(e)}function Ov(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 Fv(e,t){return zi(e,t)}function zi(e,t){return typeof e=="string"?Nv(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 Nv(e,t){if(e===t)return".";if(!Cv(e))return e;let n=cu(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let r=cu($v(),e).replace(/\\/g,"/");return r&&!r.startsWith("..")?`~/${r}`:e}return n}import{spawnSync as Mv}from"child_process";import{readFileSync as hu}from"fs";import{dirname as gu,join as _v,resolve as qv}from"path";import{fileURLToPath as Bv}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 Vv(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??Gv,r=t.packageRoot??Hv(),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=Wv(r),c=Vv(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 Hv(){let e=gu(Bv(import.meta.url));for(;;){let t=_v(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 Wv(e){return JSON.parse(hu(qv(e,"package.json"),"utf8")).optionalDependencies??{}}var Gv={probe:e=>yn(e)==="ast",resetProbe:jo,install:(e,t)=>{let n=Mv(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?rx(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 Jv({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=zv({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:lx(mn),message:dx(mn)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let To=e.runHealth===!1?sx(t):await ox(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=Kv({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:Qv(fn),message:Yv(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 Jv(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 zv(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 Kv(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:Xv(e.steps),evidence:Zv(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?ex(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:tx(e.capabilities),evidence:nx(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 Qv(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function Yv(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 Xv(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function Zv(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function ex(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 tx(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function nx(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 rx(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=ix(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 ix(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function ox(e,t){if(!Uv(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).`}),ax(n)}catch(n){let r=At(n);return N(t,{id:"health",label:"Health audit",status:"failed",message:r}),Zi(r)}}function sx(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 ax(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(cx),warnings:e.warnings??[]}}function cx(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 lx(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 dx(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 ux}from"readline";function px(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function mx(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=px(e);ux(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
343
  `),n.write(`Use \u2191/\u2193 to move, space to toggle, enter to start. Ctrl-C cancels.
344
344
 
345
345
  `),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
346
  `)}),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
347
+ `),s(r.selected);return}let m=p.name==="up"?"up":p.name==="down"?"down":p.name==="space"?"toggle":null;m&&(r=mx(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 fx,writeFileSync as gx}from"fs";import{dirname as hx,join as $u}from"path";function Cu(e,t={}){let n=$u(e,".github","workflows","scip-query.yml"),r=yx({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||(fx(hx(n),{recursive:!0}),gx(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function yx(e){let t=`scip-query@${Ne}`;return`name: scip-query
348
348
 
349
349
  # Generated by scip-query setup-ci.
350
350
  # Install the language indexers your repository needs before the reindex step
@@ -372,32 +372,32 @@ ${e.hasNpmProject?` - run: npm ci
372
372
  `)+`
373
373
  `} - run: npx ${t} reindex
374
374
  - 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(`
375
+ `}import{existsSync as bx}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=Sx(e.projectRoot,{dryRun:e.dryRun})),s}function Sx(e,t={}){return{hooks:jt(e,{remove:!0,dryRun:t.dryRun}),agentSetup:Wc(e,{dryRun:t.dryRun}),left:vx(e)}}function vx(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])=>bx(t)).map(([t])=>t)}import{existsSync as xx,readFileSync as Rx}from"fs";import{createRequire as kx}from"module";import vr from"path";import{performance as Sr}from"perf_hooks";var wx=kx(import.meta.url),sn;function Lu(e){let t=$x();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=>Cx(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=Tx(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=Ix(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 $x(){if(sn!==void 0)return sn;try{sn=wx("typescript")}catch{sn=null}return sn}function Cx(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(Px(e,r),e.createDocumentRegistry());return{tsconfigPath:t,service:o,files:i}}function Px(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(xx(n))return e.ScriptSnapshot.fromString(Rx(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 Tx(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 Ix(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 jx}from"fs";function Fu(e){let t=[];for(let[n,r]of jx(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=Nx(S.durationMs),R=he(S.runId);x&&w!==null&&(l+=1,s.add(x),R&&o.add(R),Ex(i,S,x,w),Lx(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 _=Fx(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(Ox).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(Ax).filter(y=>y!==null).sort((y,S)=>S.laterRunMs-y.laterRunMs||S.laterRunEvents-y.laterRunEvents||y.spanName.localeCompare(S.spanName)),g=[...i.values()].map(Dx).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(`
380
380
  `)}
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(`
381
+ `}function Ex(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 Lx(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 Ax(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 Dx(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 Ox(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 Fx(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 Nx(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=Mx(t);return{...e,warnings:[...e.warnings??[],_u.note,...n],capabilities:t,scoreInterpretation:_u}}function Mx(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 Ux=new Set(Da),Jx=18e4,Wu=100*1024*1024,zx=new Set(Eo),Kx=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],Qx=[["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 Yx(e){return e.filter(t=>Ux.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=Yx(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")){uR(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")??Jx,i=b(t,"progress"),o=b(t,"profile"),s=k(t,"profileOut"),a={projectRoot:n,...aR(n),index:to(ke(wt(n))),commands:[]};b(t,"coldIndex")&&(Ot(i,"cold index started"),a.coldIndex=await Xx(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 nR(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 rR(t))a.commands.push(oR(n,c,r,{progress:i,profile:o,profileOut:s}));if(b(t,"json")){I("bench",[],t,a);return}cR(a)}function Zu(e,t){let n=G(t),r=Gx(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(dR),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}lR(x)})}async function Xx(e){let t=me(e),n=De(e,t),r=Rr(n.dbPath),i=`${r}.bench-backup-${Date.now()}`;Zx(r);let o=eR(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:_x,writeFileSync:Hx,renameSync:qx,rmSync:Bx,unlinkSync:Vx};function ro(e){return mt(Rr(e),"bench-restore.json")}function Zx(e,t=no){let n=ro(e);if(!t.existsSync(n))return!1;let r=tR(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 eR(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 tR(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 nR(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 rR(e){let t=Ct(e,"command");return t.length>0?t.map(iR).filter(n=>n.length>0):[...Kx.map(n=>[...n]),...b(e,"includeHeavy")?Qx.map(n=>[...n]):[]]}function iR(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function oR(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?sR(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 sR(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function aR(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=>zx.has(Wx(r).toLowerCase())).length}}function cR(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 lR(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 dR(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||(e.startChar??0)-(t.startChar??0)||e.symbolId-t.symbolId}function uR(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
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(`
387
387
  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
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
389
  No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
390
390
  Detected languages: ${r.languages.join(", ")}`),console.log(`
391
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
+ Semantic provider readiness:`);for(let o of i){let s=o.available?" OK":o.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${o.language}: ${xR(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(`
393
393
  ${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(`
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):yR(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 pR(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 pR(e,t){let{projectRoot:n,config:r}=Me(),i=ge(n,r),o=vu({files:mR(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([...fR(o.actions),...s.map(g=>g.id)]);l&&gR(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 mR(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 fR(e){return new Set([...e.filter(t=>t.recommended).map(t=>t.id),"install-agent-skills","install-ast-parsers"])}function gR(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
396
  Reindex complete in ${(R/1e3).toFixed(1)}s`)},onError:R=>{console.error(`
397
397
  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
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.
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 hR(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 hR(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}bR(n,{affectedSetShadow:o,capabilities:b(t,"capabilities"),sqliteGeneration:s,rustSemanticSession:a,watchService:i})}function yR(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 bR(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: ${RR(e.freshness.lastRefresh)}`),xp(t.watchService),SR(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"),vR(t.sqliteGeneration),console.log(`Shadow: ${Al(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),kR(e.exists),t.capabilities&&(console.log(""),io(e.capabilities))}function SR(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 vR(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 xR(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 RR(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 kR(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 tk,mkdirSync as nk,writeFileSync as rk}from"fs";import{dirname as ik,relative as ok}from"path";import{existsSync as Ge,readdirSync as IR,readFileSync as ft}from"fs";import{basename as jR,dirname as Ap,isAbsolute as Dp,join as ER,relative as LR,resolve as cn,sep as AR}from"path";import{spawnSync as $R}from"child_process";import{dirname as CR}from"path";function Tp(e){let n=(e.spawnSync??$R)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:CR(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=TR(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 PR=8;function TR(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<PR&&!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 DR=/^(.*)@L(\d+)-L(\d+)$/;function co(e){let t=e.match(DR);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 OR=new Set(["auto","sany","tlc","apalache","none"]),Cr=/^[A-Za-z_][A-Za-z0-9_]*$/;function Np(e){return OR.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=FR(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:QR(r),operators:YR(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 FR(e,t){if(!q(e))return t.push("map file must contain a JSON object"),null;let n=VR(e.variables,t);BR(n,t);let r=zR(e.actions,n,t),i=NR(e.init,t);_R(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:qR(e.unmappedWriteScope,t)};return ZR(e.scope,t),t.length===0?o:null}function NR(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=MR(e.waive,t);return{codeRefs:n,...r?{waive:r}:{}}}function MR(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 _R(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 qR(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 BR(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 VR(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=WR(i.resource,r,t),c=GR(i.statements,r,t),l=UR(i.ormCalls,r,t),d=JR(i.waive,r,t),p=HR(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 HR(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 WR(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 GR(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 UR(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 JR(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 zR(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=KR(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 KR(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 QR(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 YR(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 XR=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(XR.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 ZR(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 ek=/^-{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(ek)?.[1],i=LR(e,t).split(AR).join("/"),o=jR(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 IR(a)){if(!d.endsWith(".scip-tla.json"))continue;let p=ER(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
401
  Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,_,{count:m.length,loc:h}),!x&&m.length>w.length&&console.log(`
402
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
403
403
  single-use helper, an abstraction-in-progress, or a callback registered
@@ -476,11 +476,11 @@ ${e.length} decorative checker candidate(s).`)}),lm=K("test-quality",({db:e,args
476
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
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
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(`
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=ok(e.config.projectRoot,s);if(!b(n,"force")&&tk(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return nk(ik(s),{recursive:!0}),rk(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
480
480
  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
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.
482
482
  `);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):
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=sk(d.checkers),m=ak(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 sk(e){return e.join(", ")}function ak(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):
484
484
  `);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
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
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(`
@@ -508,47 +508,47 @@ ${e.length} large Vue view pressure file(s) found.`)}});function re(e){return{do
508
508
  barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
509
509
  Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
510
510
  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(`
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 ck=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:ck}];var lk=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."}),dk=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}]`:""}`))}),uk=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}`))}),pk=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}`))}),mk=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(`
512
512
  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(`
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.)`)}}),fk=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(`
514
514
  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
515
  No declared boundary violations found.`);if(e.edges.length>0){console.log(`
516
516
  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
517
  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)}%.
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)`)}}}}),gk=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:dk},{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:uk},{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:pk},{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:mk},{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:fk},{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:lk},{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:gk},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 hk=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}`)}),yk=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)}%.
522
522
  `),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(`
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:yk},{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:hk}];var bk=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(`
524
524
  \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):
525
+ ${i.length} affected symbol(s) across ${new Set(i.map(s=>s.file)).size} files.`)}),Sk=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):
526
526
  `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${s.commitsAnalyzed} commits analyzed):
527
527
  `),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(`
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 ${vk(a.lastTogetherAt)}`),console.log(` subjects: ${xk(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 vk(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function xk(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 Rk=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}`})}),kk=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
531
  No incomplete migrations detected.`);return}Pe("incomplete migration candidates");for(let o of i.findings){console.log(`
532
532
  ${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(`
533
+ ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function wk(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 $k=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:wk(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
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
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(`
536
536
  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(`
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:bk},{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:Rk},{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:$k},{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:kk},{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:Sk}];function Ck(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
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})
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 Pk=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)."}),Tk=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
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
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(`
542
542
  \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}
543
+ \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of o.consumers)console.log(` ${s.file} ${s.shortName}`)}}),Ik=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
544
  `),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}j.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
545
545
  ${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`/**
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:Ck}),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:Pk},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:Tk},{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:Ik}];var jk=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:Ek(s)},{title:"DEFINITIONS",rows:Lk(s,i),skipIfEmpty:!0},{title:"REFERENCES",rows:Ak(s,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:Dk(s,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:Ok(s,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:Fk(s,i),skipIfEmpty:!0},{title:"SURFACE",rows:Nk(s,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:Mk(s,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:_k(s,i),skipIfEmpty:!0},{title:"HISTORY",rows:qk(s),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:Bk(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:jk}];function Ek(e){return[`Target: ${e.target}`,`Matched: symbol=${mo(e.matched.symbol)} file=${mo(e.matched.file)} module=${mo(e.matched.module)}`]}function Lk(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 Ak(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${_e(r.line)} in ${r.enclosingShort}`);return gt(tt(n,t))}function Dk(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 Ok(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 Fk(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 Nk(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 Mk(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 _k(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 qk(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 Bk(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 Qk,mkdtempSync as Yk,rmSync as Xk}from"fs";import{tmpdir as Zk}from"os";import{dirname as go,join as ho}from"path";import{performance as Em}from"perf_hooks";import{spawnSync as ew}from"child_process";import{createHash as Vk}from"crypto";import{existsSync as Hk,mkdirSync as Wk,readFileSync as Gk,renameSync as Uk,writeFileSync as Jk}from"fs";import{homedir as zk}from"os";import{dirname as Kk,join as fo}from"path";function Tm(e){return Vk("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(zk(),".cache","scip-query"));return fo(n,e)}async function jm(e){let{cachePath:t,url:n,expectedSha256:r}=e;if(Hk(t)){let l=Tm(Gk(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}`);Wk(Kk(t),{recursive:!0});let c=`${t}.tmp-${process.pid}`;return Jk(c,s),Uk(c,t),{status:"downloaded",path:t,sha256:a}}var tw=12e4,Dm="v1.8.0",nw=`https://github.com/tlaplus/tlaplus/releases/download/${Dm}/tla2tools.jar`,rw="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function Lr(e){let t=e.spawn??ew,n=iw(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??tw,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??[])Xk(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:ow(c,o.stdout??"",o.stderr??""),stdout:o.stdout??"",stderr:o.stderr??""}}function iw(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??Yk(ho(Zk(),"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=>Qk(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??rw,r=e.version??Dm,i=e.url??nw;return{...await jm({cachePath:t,url:i,expectedSha256:n,fetchImpl:e.fetchImpl}),version:r,url:i}}function ow(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 sw}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"]),aw=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,cw=/^\s*SELECT\b/i;function Hm(e){return aw.test(e)?"write":cw.test(e)?"read":null}var lw=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function dw(e,t){let n=e.match(lw);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=mw(e,t,o),a=s.aliases,c=fw(t),l=gw(t),d=hw(t),p=Sw(e,t,o),m=xw(e,t,o);n&&Rw(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=kw(e,t,p,a,c,l,d,g,h,o,f),S=Cw(e,p,a,c,l,d,o,f);return Tw(e,p,o),Iw(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:Kw(t),checkedInvariants:[...i],traceStepsChecked:r.length,findings:o,findingGroups:uw(o)}}function uw(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=pw(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 pw(e,t){return Ar(t)>Ar(e)?t:e}function Ar(e){return e==="error"?2:e==="warning"?1:0}function mw(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}Hw(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:zw(r),referents:i}}function fw(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 gw(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 hw(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 yw(e,t,n,r,i,o){return Gm(e,t,(s,a,c)=>ht(e,s,a,c,n,r,i,o))}function bw(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 Sw(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?(Ww(e,r,s,d,n),"error"in a||!a.window?{ref:s,match:d}:vw(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 vw(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function xw(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?Gw(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 Rw(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 kw(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=yw(e,h.match.symbol,r,i,o,s).filter(R=>x.has(R.variable));g.push(...w),p.push(...w)}$w(f,g,l,d.get(f.name))}let m=t.unmappedWriteScope==="actions"?[]:qw(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),ww(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 ww(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function $w(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 Cw(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=bw(e,p.match.symbol,n,r,i,o).filter(y=>g.has(y.variable));d.push(...h),c.push(...h)}Pw(l,d,s,a.get(l.name))}return ko(c)}function Pw(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 Tw(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 Iw(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=Jw(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=jw(e,t,n,r,i,o,s,a);return c||Mw(e,t,n,r,i,o,s,a)}function Or(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 jw(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)){Lw(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 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)){Ow(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 Lw(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=Aw(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}(${Dw(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?Q(d.symbol):void 0})}}}function Aw(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function Dw(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 Ow(e,t,n,r,i){if(!(!Fw(n)||Nw(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 Fw(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function Nw(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(!Uw(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 Mw(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(dw(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 _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){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 qw(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&&!Bw(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.`,Vw(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 Bw(e){return/[/#:]/.test(e)}function Vw(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function Hw(e,t,n,r,i,o=!1){let s=xo(e,r);if(s===null||Qw.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 Ww(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 Gw(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 Uw(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${Le(e)}([^A-Za-z0-9_$]|$)`).test(t)}function Jw(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 zw(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 Kw(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()),Qw=new Set(qo());function W(e,t,n,r){let i=JSON.stringify({category:e,evidence:n,...r});return{id:`TLA${sw("sha1").update(i).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...r}}import{readFileSync as Yw}from"fs";import{basename as Xw,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=Yw(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:t$(s,T)),f=null,g;if(m.length>0)g=i.filter(T=>a(T)&&T.parentTypeName===null);else{if(f=Zw(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=>n$(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=s$(rf(T.leaf),x);S.push({name:F,leaf:T.leaf,codeRef:e$(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??a$(t),R=n.specDir??tf("specs",w),D=c$(w,h,S,t),_=l$(),z=d$(w,R,t,h,S);return{moduleName:w,file:t,variables:h,actions:S,warnings:r,spec:D,cfg:_,map:z}}function Zw(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 e$(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function t$(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function n$(e,t,n,r,i){let o=r$(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=i$(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 r$(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function i$(e,t){let r=t.match(new RegExp(`\\b${u$(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,o=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(r){let l=o$(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 o$(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 s$(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}${r++}`;return t.add(n),n}function a$(e){let n=Xw(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return rf(n||"Model")}function c$(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 l$(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
550
+ `)}function d$(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 u$(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:p$(n),wiring:r,variables:n}}function p$(e){return`/**
552
552
  * Generated by 'scip-query tla instrument'. Dependency-free trace recorder.
553
553
  *
554
554
  * Usage inside a mapped action (record the model-visible slice around the
@@ -591,15 +591,15 @@ export function tlaRecord(action: string, before: Record<string, unknown>, after
591
591
  steps.push({ action, before, after });
592
592
  writeFileSync(tracePath, JSON.stringify(steps, null, 2));
593
593
  }
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(`,
594
+ `}import{copyFileSync as m$,mkdtempSync as f$,readdirSync as g$,rmSync as h$,writeFileSync as sf}from"fs";import{tmpdir as y$}from"os";import{basename as b$,dirname as S$,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 v$(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=R$(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(`,
595
595
  `),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
596
  `),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(`
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=v$(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=f$(un(y$(),"scip-tla-trace-"));try{let i=S$(e.specPath);for(let d of g$(i))d.endsWith(".tla")&&m$(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=x$(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{h$(r,{recursive:!0,force:!0})}}function x$(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 R$(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 b$(e).replace(/\.tla$/i,"")}import{mkdirSync as uf,writeFileSync as pf}from"fs";import{dirname as k$,join as Ft}from"path";var w$=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=>$$(s,t,n,o));return}if(r==="instrument"){let o=B(t,1);ce(s=>C$(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=>P$(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=>j$(o,t,n,i))};function $$(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 C$(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(k$(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 P$(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")&&T$(m.actionCoverage),process.exitCode=f}function T$(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 I$(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 j$(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}=I$(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=L$(k(n,"checker")??"auto"),h=k(n,"tlaTools"),y=E$(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:A$(O,T,b(n,"allowUnknown"))};if(b(n,"json")){I("tla",t,n,Z),process.exitCode=Z.exitCode;return}D$(Z,b(n,"full")),process.exitCode=Z.exitCode}function E$(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:w$}];function L$(e){if(!Np(e))throw new Error(`unknown checker mode: ${e}`);return e}function A$(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 D$(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=F$(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 N$(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}O$(e.conformance)}function O$(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
602
602
  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
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 F$(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 N$(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"],M$=[Rm,Cm,km,jr,$m,Pm,mf,wm],hf=M$.flat(),_$=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=>q$(e));function q$(e){let t=_$.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var B$=Nt.slice(0,Co("plan-context")),V$=Nt.slice(Mr("drift"),Co("self-audit")),H$=Nt.slice(Mr("convergence"),Co("slice")),W$=Nt.slice(Mr("redundant-reexports")),SD=[{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},...B$,{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},...V$,{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},...H$,{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},...W$,{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{SD as commandDescriptors};
605
+ //# sourceMappingURL=command-descriptors-3EJHQLQZ.js.map