scip-query 0.17.2 → 0.18.0

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 (121) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +2 -1
  3. package/dist/{chunk-KSD6IWF4.js → chunk-2GX3TNOW.js} +2 -2
  4. package/dist/{chunk-Q4GKL4CC.js → chunk-35TZERMO.js} +2 -2
  5. package/dist/{chunk-P6FOIU7O.js → chunk-43QUXX3E.js} +2 -2
  6. package/dist/{chunk-U4G4UYLB.js → chunk-45XOH33S.js} +2 -2
  7. package/dist/{chunk-LEKXKHIQ.js → chunk-4MFMTEJ4.js} +5 -5
  8. package/dist/{chunk-FVLZB54V.js → chunk-ABDXTPCT.js} +2 -2
  9. package/dist/{chunk-N3JH45WR.js → chunk-AV54WZUK.js} +2 -2
  10. package/dist/{chunk-S22ICAWV.js → chunk-BAMVG4WQ.js} +2 -2
  11. package/dist/{chunk-7VR5TNOI.js → chunk-BECOMXAL.js} +2 -2
  12. package/dist/{chunk-K53GNKY3.js → chunk-BJJHBKEC.js} +2 -2
  13. package/dist/{chunk-ROMKXEUM.js → chunk-D5F3IQYP.js} +2 -2
  14. package/dist/{chunk-LFPQFRCX.js → chunk-DDGO34I2.js} +2 -2
  15. package/dist/{chunk-IS7DZ7TB.js → chunk-DUKRAHV2.js} +2 -2
  16. package/dist/{chunk-W7FNZKX5.js → chunk-EJ65IVPV.js} +2 -2
  17. package/dist/{chunk-SON6DQNK.js → chunk-EMEXMHOP.js} +2 -2
  18. package/dist/{chunk-BPMBOZAN.js → chunk-FMD46HAG.js} +2 -2
  19. package/dist/{chunk-4H7T7FIM.js → chunk-GTANVH72.js} +2 -2
  20. package/dist/{chunk-O7NA5FCA.js → chunk-GWCW25ON.js} +2 -2
  21. package/dist/chunk-GWNE2WJN.js +3 -0
  22. package/dist/{chunk-ELLPMCWA.js → chunk-H4JNB7RT.js} +2 -2
  23. package/dist/{chunk-G6DDSHMD.js → chunk-HOZ3IXZ5.js} +2 -2
  24. package/dist/{chunk-RUV4KHWA.js → chunk-L2RE5P3X.js} +2 -2
  25. package/dist/{chunk-7LERNHDG.js → chunk-L2TSLMPT.js} +2 -2
  26. package/dist/{chunk-KA7RMBVU.js → chunk-LADYDOS5.js} +2 -2
  27. package/dist/{chunk-AY44MGWS.js → chunk-MN54AGZ3.js} +2 -2
  28. package/dist/{chunk-DJI446FQ.js → chunk-MNRKD3WP.js} +2 -2
  29. package/dist/{chunk-SXDXR5FH.js → chunk-MPBN5DO4.js} +2 -2
  30. package/dist/{chunk-KJOKTZUE.js → chunk-NQBMGFFD.js} +2 -2
  31. package/dist/{chunk-K4XL4HOK.js → chunk-O5Y3ISO3.js} +2 -2
  32. package/dist/{chunk-BEGHYHOQ.js → chunk-ODH4FT3P.js} +2 -2
  33. package/dist/{chunk-MBVHEPHQ.js → chunk-OM6JHEW3.js} +2 -2
  34. package/dist/{chunk-C7MBQSIC.js → chunk-OSBLECSI.js} +2 -2
  35. package/dist/{chunk-ATC4MEVA.js → chunk-OTTHMUMV.js} +2 -2
  36. package/dist/{chunk-SSGACGAD.js → chunk-OUXPJ4H5.js} +2 -2
  37. package/dist/{chunk-CVWX24IY.js → chunk-OWXNDSG3.js} +2 -2
  38. package/dist/{chunk-OQFA2SUQ.js → chunk-P4L5QQT5.js} +2 -2
  39. package/dist/{chunk-APCXCRED.js → chunk-POGZSZPX.js} +2 -2
  40. package/dist/{chunk-4QBRVI7D.js → chunk-PV3GKBO5.js} +2 -2
  41. package/dist/{chunk-NJD4C5G5.js → chunk-PZV2PGBR.js} +2 -2
  42. package/dist/{chunk-CHJ3QROR.js → chunk-Q4UM4JJP.js} +2 -2
  43. package/dist/{chunk-PQD7P6WB.js → chunk-QPF7CS5W.js} +2 -2
  44. package/dist/{chunk-WD3PAQJT.js → chunk-R4VPIS4D.js} +2 -2
  45. package/dist/{chunk-XLJORP6N.js → chunk-RDX6WWHN.js} +2 -2
  46. package/dist/{chunk-YYYERNQL.js → chunk-S43DIBME.js} +2 -2
  47. package/dist/{chunk-MFIA6EIT.js → chunk-SW7LKHRU.js} +2 -2
  48. package/dist/{chunk-2A7LUMZP.js → chunk-SWJEREML.js} +2 -2
  49. package/dist/{chunk-6AITNECC.js → chunk-VQWDZ34M.js} +127 -127
  50. package/dist/{chunk-A2GX3PYV.js → chunk-VXDMXZKC.js} +2 -2
  51. package/dist/{chunk-XTF6ELXT.js → chunk-W3557RPL.js} +2 -2
  52. package/dist/chunk-W3SKYOTF.js +2 -0
  53. package/dist/{chunk-NJTIAQY7.js → chunk-XEEQX5X3.js} +2 -2
  54. package/dist/cli.js +1 -1
  55. package/dist/{command-descriptors-7UUURHWT.js → command-descriptors-AQWWJNTT.js} +143 -143
  56. package/dist/direct-navigation-K3CTVVBU.js +3 -0
  57. package/dist/index.js +1 -1
  58. package/dist/postinstall.js +1 -1
  59. package/dist/queries/affected.js +1 -1
  60. package/dist/queries/bottlenecks.js +1 -1
  61. package/dist/queries/call-graph.js +1 -1
  62. package/dist/queries/change-surface.js +1 -1
  63. package/dist/queries/cleanup-plan.js +1 -1
  64. package/dist/queries/complexity-hotspots.js +1 -1
  65. package/dist/queries/complexity.js +1 -1
  66. package/dist/queries/convergence.js +1 -1
  67. package/dist/queries/dataflow.js +1 -1
  68. package/dist/queries/dead.js +1 -1
  69. package/dist/queries/decorative-checkers.js +1 -1
  70. package/dist/queries/diff-gate.js +1 -1
  71. package/dist/queries/diff-impact.js +1 -1
  72. package/dist/queries/drift.js +1 -1
  73. package/dist/queries/extract-candidates.js +1 -1
  74. package/dist/queries/health.js +1 -1
  75. package/dist/queries/hotspots.js +1 -1
  76. package/dist/queries/imports.js +1 -1
  77. package/dist/queries/incomplete-migration.js +1 -1
  78. package/dist/queries/index.js +1 -1
  79. package/dist/queries/isolated.js +1 -1
  80. package/dist/queries/locality-candidates.js +1 -1
  81. package/dist/queries/members.js +1 -1
  82. package/dist/queries/methods.js +1 -1
  83. package/dist/queries/not-implemented.js +1 -1
  84. package/dist/queries/passthrough-candidates.js +1 -1
  85. package/dist/queries/plan-context.js +1 -1
  86. package/dist/queries/recent-duplicates.js +1 -1
  87. package/dist/queries/redundant-reexports.js +1 -1
  88. package/dist/queries/refs.js +1 -1
  89. package/dist/queries/self-audit.js +1 -1
  90. package/dist/queries/similar-signatures.js +1 -1
  91. package/dist/queries/similar.js +1 -1
  92. package/dist/queries/slice.js +1 -1
  93. package/dist/queries/stale-abstractions.js +1 -1
  94. package/dist/queries/surface.js +1 -1
  95. package/dist/queries/trace.js +1 -1
  96. package/dist/queries/twin-ab.js +1 -1
  97. package/dist/queries/unused-imports.js +1 -1
  98. package/dist/queries/unused-params.js +1 -1
  99. package/dist/queries/wrapper-candidates.js +1 -1
  100. package/dist/reindex-worker.js +24 -24
  101. package/dist/reindex.js +36 -36
  102. package/dist/runtime.js +1 -1
  103. package/docs/COMMAND_REFERENCE.md +1 -1
  104. package/package.json +1 -1
  105. package/skills/_shared/SKILL.md +1 -1
  106. package/skills/scip-api-impact/SKILL.md +5 -1
  107. package/skills/scip-claim-audit/SKILL.md +1 -0
  108. package/skills/scip-cleanup-audit/SKILL.md +4 -0
  109. package/skills/scip-concrete-plan/SKILL.md +129 -48
  110. package/skills/scip-debug/SKILL.md +6 -1
  111. package/skills/scip-explore/SKILL.md +2 -1
  112. package/skills/scip-integrity-audit/SKILL.md +17 -0
  113. package/skills/scip-maintainability/SKILL.md +6 -1
  114. package/skills/scip-query/SKILL.md +3 -0
  115. package/skills/scip-root-cause/SKILL.md +150 -0
  116. package/skills/scip-root-cause/agents/openai.yaml +4 -0
  117. package/skills/scip-tla-model-system/SKILL.md +7 -9
  118. package/skills/scip-verify/SKILL.md +19 -2
  119. package/dist/chunk-TFWDJDGO.js +0 -2
  120. package/dist/chunk-Z4MCFCGX.js +0 -3
  121. package/dist/direct-navigation-CVCFER5G.js +0 -3
@@ -1,49 +1,49 @@
1
1
  #!/usr/bin/env node
2
- import{b as Sc}from"./chunk-XTF6ELXT.js";import{a as rt,b as v,c as _e,d as ge,e as kt,f as p,g as lc,h as C,i as $,j as se,k as ae,l as ve,m as Vt,n as bc}from"./chunk-A2GX3PYV.js";import{$ as Go,$a as js,$b as wa,$c as Y,A as Lo,Aa as qt,Ab as ta,Ac as _a,Ad as dc,B as hn,Ba as cs,Bb as na,Bc as qa,Bd as uc,C as Ao,Ca as ls,Cb as ra,Cc as nt,Cd as pc,D as Do,Da as ds,Db as ia,Dc as Oe,Dd as it,E as yn,Ea as bt,Eb as oa,Ec as Ne,Ed as mc,Fa as us,Fb as sa,Fd as Se,G as et,Ga as ps,Gb as aa,Gc as Ba,Gd as fc,H as gt,Hb as ca,Hc as Va,Hd as ue,I as Oo,Ia as ms,Ib as la,Ic as Ha,Id as Dn,J as No,Ja as fs,Jb as da,Jc as Wa,Jd as gc,K as Fo,Ka as gs,Kb as ua,Kc as Ga,Kd as L,L as Mo,La as hs,Lb as pa,Lc as Ua,Ld as B,M as _o,Ma as ys,Mb as Br,Mc as Ja,Md as w,N as bn,Na as bs,Nb as St,Nc as za,Nd as U,O as Sn,Oa as Ss,Ob as Tn,Oc as Ka,Od as b,P as qo,Pa as vs,Pb as In,Pc as Qa,Pd as wt,Q as ht,Qa as xs,Qb as ma,Qc as Ya,Qd as P,R as yt,Ra as Rs,Rb as fa,Rc as Xa,Rd as A,S as Bo,Sb as ga,Sc as En,Sd as hc,T as Vo,Ta as ks,Tb as ha,Tc as Za,Td as I,U as vn,Ua as ws,Ub as ya,Uc as ec,Ud as yc,V as Ho,Va as $s,Vb as ba,Vc as jn,Vd as G,W as xn,Wa as Ps,Wb as Sa,Wc as tc,X as Wo,Xa as Cs,Xb as va,Xc as Vr,Y as Rn,Ya as Ts,Yb as xa,Yc as nc,Za as Is,Zb as Ra,Zc as Hr,_ as Nr,_a as Es,_b as ka,aa as Uo,ab as Ls,ac as $a,ba as Jo,bb as As,bc as re,bd as Fe,c as pn,ca as zo,cb as Ds,cc as Pa,cd as Rt,d as me,db as Os,dc as Ca,dd as rc,e as mn,eb as Ns,ec as Ta,f as q,fa as Ko,fb as Bt,fc as Ia,fd as le,g as J,ga as kn,gb as Fs,gc as Ea,ha as Fr,hb as Ms,hc as ja,hd as Ue,ia as wn,ib as _s,id as Wr,ja as Qo,jb as qs,jc as La,jd as Me,ka as Mr,kb as Bs,kc as Aa,kd as oe,la as Yo,lb as Vs,lc as Da,ld as M,m as Nt,ma as Xo,mb as Hs,mc as Ae,md as Ln,n as Ft,na as Zo,nb as Ws,nc as vt,nd as E,o as Mt,oa as es,ob as Gs,oc as Oa,od as Gr,p as Le,pa as _t,pb as Us,pc as fe,pd as Ur,q as Po,qa as ts,qb as Js,qc as xt,qd as Ce,r as fn,ra as ns,rb as zs,rc as Pe,rd as ic,s as Co,sa as $n,sb as Ks,sd as oc,t as Or,ta as rs,tb as Qs,td as An,u as To,ua as is,ub as Ys,ud as sc,v as Io,va as Pn,vb as _r,vc as De,vd as ac,w as Eo,wa as os,wb as qr,wc as Na,wd as cc,x as jo,xa as Cn,xb as Xs,xc as Fa,y as gn,ya as ss,yb as Zs,yc as Ma,yd as de,z as Q,za as as,zb as ea,zc as tt,zd as K}from"./chunk-6AITNECC.js";import{execFileSync as nl,spawn as Pg}from"child_process";import{existsSync as ct,mkdirSync as ai,readFileSync as rl,rmSync as Cg,writeFileSync as Wn}from"fs";import{homedir as Tg}from"os";import{dirname as Gn,isAbsolute as Ig,join as Jt,resolve as Eg}from"path";import{execFileSync as Qf}from"child_process";import{createRequire as gf}from"module";var hf=gf(import.meta.url);function vc(e,t=[]){let n=yf(),r=ns(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 yf(){try{return hf.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as $t,spawnSync as Sf}from"child_process";import{existsSync as xe,mkdtempSync as wc,readFileSync as vf,readdirSync as xf,rmSync as $c,symlinkSync as Rf,writeFileSync as kf}from"fs";import{tmpdir as Pc}from"os";import{join as ce}from"path";import{spawnSync as bf}from"child_process";function qe(e,t=bf){try{return t(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}var wf=3e5,$f=12;function Kr(e,t,n={}){let r=Qr(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],dirtyWorkingTree:Jr(e),batches:[]};let i=If(t,r),o=n.timeoutMs??wf,s=Df(e,t),a=Jr(e),c=wc(ce(Pc(),"scip-cleanup-verify-")),l=[],d=new Map;try{$t("git",["-C",e,"worktree","add","--detach","--force",c,"HEAD"],{stdio:"ignore"}),Of(e,c);for(let u of r)d.set(u.label,Rc(u,c,o).rawErrors);for(let u of t.batches){Tc(c,u);let m=null;for(let f of r){let g=Rc(f,c,o),h=Pf(g,d.get(f.label)??[],g.rawErrors);if(h.status==="failed"){let y=h.errors.length>0?h.errors:g.outputTail;m={depth:u.depth,status:"failed",reason:`${f.label}: ${h.reason}`,errors:y.slice(0,$f)};break}}if(!m)l.push({depth:u.depth,status:"verified"});else{l.push(m);break}}}finally{try{$t("git",["-C",e,"worktree","remove","--force",c],{stdio:"ignore"})}catch{$c(c,{recursive:!0,force:!0})}}return{checkers:r.map(u=>u.label),uncoveredFiles:i,baselineErrors:[...d.values()].reduce((u,m)=>u+m.length,0),dirtyOverlap:s,dirtyWorkingTree:a,batches:l}}function Pf(e,t,n){let r=Cf(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 Cf(e,t){let n=Tf(e),r=new Map,i=[];for(let o of t){let s=Cc(o),a=(r.get(s)??0)+1;r.set(s,a),a>(n.get(s)??0)&&i.push(o)}return i}function Tf(e){let t=new Map;for(let n of e){let r=Cc(n);t.set(r,(t.get(r)??0)+1)}return t}function If(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 Cc(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var xc=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],Ef=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function Qr(e){let t=[];if(xe(ce(e,"tsconfig.json"))){let n=ce(e,"node_modules",".bin","tsc");t.push(xe(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:xc,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:xc,strength:"reference-aware"})}if(xe(ce(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(ce(e,n)))){let n=jf();n&&t.push(n)}if(Ef.some(n=>xe(ce(e,n)))){let n=Lf(e);n&&t.push(n)}for(let n of Af(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:ce(e,n,"..","target")}});return t}function jf(){return qe("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"}:qe("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function Lf(e){let t=ce(e,"node_modules",".bin","clj-kondo");return xe(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...mn],strength:"reference-aware"}:qe("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...mn],strength:"reference-aware"}:qe("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...mn],strength:"reference-aware"}:null}function Af(e){let t=[];if(xe(ce(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=xf(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||xe(ce(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function Df(e,t){let n=new Set(Jr(e));return[...new Set(t.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>n.has(i)).sort()}function Jr(e){let t;try{t=$t("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}return t.split(`
3
- `).map(n=>n.slice(3).trim()).filter(n=>n!=="").sort()}function Of(e,t){for(let n of["node_modules"]){let r=ce(e,n),i=ce(t,n);if(xe(r)&&!xe(i))try{Rf(r,i,"junction")}catch{}}}function Tc(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=ce(e,r);xe(o)&&kf(o,Nf(vf(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function Yr(e,t){for(let n of t)Tc(e,n)}function Ic(e,t){let n=wc(ce(Pc(),"scip-cleanup-patch-"));try{return $t("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),Yr(n,t),$t("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{$t("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{$c(n,{recursive:!0,force:!0})}}}function Xr(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 Zr(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 Nf(e,t,n={}){let r=e.split(`
4
- `),i=(n.rust===!0?Ff(e):Po(e)).split(`
5
- `),o=new Set;for(let s of t){let a=Mf(r,s.start),c=qf(i,a,Math.min(s.end,r.length-1));for(let l=a;l<=c&&l<r.length;l++)o.add(l)}return r.filter((s,a)=>!o.has(a)).join(`
6
- `)}function Ff(e){return e.replace(/\/\/.*$/gm,t=>t.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\r\n]/g," ")).replace(/"(?:\\.|[^"\\\r\n])*"/g,t=>t.replace(/[^\r\n]/g," "))}function Mf(e,t){let n=t;for(;n>0;){let r=(e[n-1]??"").trim();if(/^(?:\/\/\/|\/\/!|#\[|#!\[|\/\*\*|\*|\*\/|@\w)/.test(r))n-=1;else break}return n}var _f=200;function qf(e,t,n){let r=0;for(let i=t;i<e.length;i++){for(let o of e[i]??"")o==="("||o==="["||o==="{"?r+=1:(o===")"||o==="]"||o==="}")&&(r-=1);if(i>=n&&r<=0)return i;if(i-n>_f)break}return n}function Rc(e,t,n){let r=Sf(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,env:e.env??process.env,maxBuffer:33554432}),i=`${r.stdout??""}
7
- ${r.stderr??""}`;if(r.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostics:[],parseBasis:"heuristic",outputTail:kc(i)};let o=Bf(e.label,i),s=o.diagnostics.length>0?o.diagnostics:r.error?[{file:"",message:String(r.error),parseBasis:"heuristic"}]:[];return{ok:!1,exitCode:r.status,rawErrors:s.map(Kf),diagnostics:s,parseBasis:o.parseBasis,outputTail:kc(i)}}function Bf(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:Vf(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:Hf(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=Wf(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:Gf(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:Uf(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:Jf(t),parseBasis:"clj-kondo-json"}:{diagnostics:zf(t),parseBasis:"heuristic"}}function Vf(e){let t=[],n=/^(.+?)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),code:r[4],message:r[5]??"",parseBasis:"tsc"});return t}function Hf(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),message:r[4]??"",parseBasis:"go"});return t}function Wf(e){let t=Ec(e);if(!Array.isArray(t))return[];let n=[];for(let r of t){if(!r||typeof r!="object")continue;let i=r,o=i.location,s=o&&typeof o=="object"?o:{},a=typeof i.filename=="string"?i.filename:"",c=typeof i.message=="string"?i.message:"";!a&&!c||n.push({file:a,line:typeof s.row=="number"?s.row:void 0,column:typeof s.column=="number"?s.column:void 0,code:typeof i.code=="string"?i.code:void 0,message:c,parseBasis:"ruff-json"})}return n}function Gf(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+([A-Z]\d{3})\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),code:r[4],message:r[5]??"",parseBasis:"ruff-text"});return t}function Uf(e){let t=[];for(let n of e.split(`
8
- `)){if(!n.trim().startsWith("{"))continue;let r=zr(n);if(!r||typeof r!="object")continue;let i=r;if(i.reason!=="compiler-message")continue;let o=i.message;if(!o||typeof o!="object")continue;let s=o;if(s.level!=="error")continue;let l=(Array.isArray(s.spans)?s.spans:[]).find(u=>!!u&&typeof u=="object"&&u.is_primary===!0),d=s.code;t.push({file:typeof l?.file_name=="string"?l.file_name:"",line:typeof l?.line_start=="number"?l.line_start:void 0,column:typeof l?.column_start=="number"?l.column_start:void 0,code:d&&typeof d=="object"&&typeof d.code=="string"?String(d.code):void 0,message:typeof s.message=="string"?s.message:"",parseBasis:"cargo-json"})}return t}function Jf(e){let t=Ec(e);if(!t||typeof t!="object")return[];let n=t.findings;if(!Array.isArray(n))return[];let r=[];for(let i of n){if(!i||typeof i!="object")continue;let o=i;o.level==="error"&&r.push({file:typeof o.filename=="string"?o.filename:"",line:typeof o.row=="number"?o.row:void 0,column:typeof o.col=="number"?o.col:void 0,code:typeof o.type=="string"?o.type:void 0,message:typeof o.message=="string"?o.message:"",parseBasis:"clj-kondo-json"})}return r}function zf(e){return e.split(`
9
- `).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function Kf(e){let t=e.file.length>0?`${e.file}${e.line?`:${e.line}`:""}${e.column?`:${e.column}`:""}: `:"",n=e.code?`${e.code} `:"";return`${t}${n}${e.message}`.trim()}function Ec(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return zr(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(r=>r>=0));return Number.isFinite(n)?zr(t.slice(n)):null}function zr(e){try{return JSON.parse(e)}catch{return null}}function kc(e,t=10){return e.split(`
10
- `).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var Ac={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".vue"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"],clojure:[".clj",".cljs",".cljc"]},Yf={typescript:"typescript",javascript:"javascript",java:"java",scala:"scala",kotlin:"kotlin",rust:"rust",python:"python",ruby:"ruby",cpp:"cpp",c:"c",csharp:"csharp",vb:"vb",php:"php",clojure:"clojure"},Xf={typescript:"javascript",javascript:"javascript",java:"jvm",scala:"jvm",kotlin:"jvm",rust:"rust",python:"python",ruby:"ruby",cpp:"c/cpp",c:"c/cpp",csharp:"dotnet",vb:"dotnet",dart:"dart",php:"php",clojure:"clojure"};function he(e,t){let n=t.languages??tt(e),r=n.map(a=>{let c=bn(et(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),i=sg(e,n,t),o=ei({semantics:i},"typescript"),s=Qr(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:r,semantics:i,semantic:o,checkers:s,gitAvailable:lg(e)}}function Je(e,t={}){let n=e.indexers.filter(c=>c.runnable).length,r=e.languages.length===0||n===0&&!t.hasIndexedGraph?"unavailable":n===e.indexers.length&&e.indexers.length>0?"available":"partial",i=r!=="unavailable",o=e.languages.map(c=>rg(e,c,{hasIndexedGraph:ig(c,t),runtimeProbe:t.runtimeProbe})),s=o.map(c=>c.cleanupVerification.status),a=s.length===0||s.every(c=>c==="unavailable")?"unavailable":s.every(c=>c==="available")?"available":"partial";return{languages:e.languages,matrix:o,capabilities:[{id:"indexing",label:"SCIP indexing",status:r,evidence:"graph-fact",reason:r==="available"?"All detected/configured language indexers are runnable.":t.hasIndexedGraph?`An indexed graph is present; ${n}/${e.indexers.length} detected/configured language indexers are runnable for refresh.`:`${n}/${e.indexers.length} detected/configured language indexers are runnable.`},...Zf(e),{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:i?"available":"unavailable",evidence:"heuristic",reason:i?"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index.":"Heuristic detectors need an indexed code graph."},{id:"cleanup-verification",label:"Project cleanup verification",status:a,evidence:"checker",reason:a!=="unavailable"?o.map(c=>`${c.language}: ${c.cleanupVerification.status} (${c.cleanupVerification.reason})`).join("; "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-gate",label:"Git diff gate",status:e.gitAvailable&&i?"available":"unavailable",evidence:"git",reason:e.gitAvailable?"Git diff data is available for changed-file gates.":"Git is unavailable or the project root is not a git worktree."}]}}function Zf(e){return eg(e).map(t=>{let n=ei(e,t),r=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${tg(t)} semantic provider`,status:r,evidence:"semantic",reason:ng(t,n)}})}function eg(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of Oc(e))t.add(n.language);return[...t].sort((n,r)=>jc(n)-jc(r))}function jc(e){return e==="typescript"?0:1}function tg(e){return e==="typescript"?"TypeScript":"Rust"}function ng(e,t){return t?.available?e==="typescript"?"ts-morph can load the configured TypeScript project.":"rust-analyzer semantic queries are available.":t?t.reason??(e==="typescript"?"TypeScript semantic checks will fall back to SCIP/source evidence.":"Rust semantic checks will fall back to SCIP/source evidence."):e==="typescript"?"TypeScript is not detected/configured for this project.":"Rust is not detected/configured for this project."}function rg(e,t,n){let r=e.indexers.find(d=>d.language===t),i=r?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=i!=="unavailable",s=og(t,n.runtimeProbe),a=ag(e,t),c=cg(e,t),l=c.length===0?"unavailable":c.every(d=>d.strength!=="syntax-only")?"available":"partial";return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:i==="available"?`${r?.binaryLabel??t} is runnable${r?.resolvedBinary?` at ${r.resolvedBinary}`:""}.`:i==="partial"?`An indexed ${t} graph is present, but ${r?.binaryLabel??t} is not currently runnable for refresh.`:r?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:o?s.status:"unavailable",evidence:"heuristic",reason:o?s.reason:"Source fallback needs indexed documents before it can attach evidence."},semantic:a,detectors:{id:"detectors",label:"Cleanup detectors",status:o?"available":"unavailable",evidence:"heuristic",reason:o?"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above.":"Cleanup detectors need an indexed graph for this language."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:l,evidence:"checker",reason:c.length>0?c.map(d=>d.label).join(", "):`No detected checker covers ${Ac[t].join(", ")} files.`}}}function ig(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function og(e,t){if(e==="go")return{status:"unavailable",reason:"No Go source-fallback adapter is registered; Go relies on SCIP graph facts."};if(e==="clojure")return(t?.(e)??Lc(e))==="unavailable"?{status:"unavailable",reason:"Clojure built-in reader is not available in this environment; no source-fallback evidence can be produced."}:{status:"available",reason:"Clojure source fallback uses the built-in reader for namespace imports plus callable, callsite, and protocol/record member evidence for .clj, .cljs, and .cljc files."};let n=Dc(e);if(n==="regex-only")return{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`};if(!n)return{status:"unavailable",reason:`No source-fallback adapter is registered for ${e}.`};let r=t?.(e)??Lc(e);return r==="unavailable"?{status:"partial",reason:"tree-sitter native module not loadable \u2014 regex/import-only evidence remains available where registered."}:r==="regex"?{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`}:r==="reader"?{status:"available",reason:`${e} source fallback is reader-backed.`}:{status:"available",reason:n==="ast-dispatch-with-regex-fallback"?`AST-dispatched source fallback covers ${e} imports.`:`AST/source fallback covers ${e} imports and source-backed evidence.`}}function Lc(e){let t=Yf[e];return t?fn(t):Dc(e)==="regex-only"?"regex":"unavailable"}function Dc(e){let t=Xf[e],n=t?jo(t):null;return n?.imports??n?.exports??n?.reExports??null}function sg(e,t,n){let r=[];return t.includes("typescript")&&r.push({language:"typescript",...vc(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")&&r.push({language:"rust",...qo(e)}),r}function Oc(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function ei(e,t){return Oc(e).find(n=>n.language===t)}function ag(e,t){if(t!=="typescript"&&t!=="rust")return{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:`No semantic provider is registered for ${t}; commands use graph and source evidence instead.`};let n=ei(e,t);return n?{id:"semantic",label:"Semantic provider",status:n.available?"available":n.dependencyAvailable?"partial":"unavailable",evidence:"semantic",reason:n.available?t==="typescript"?"ts-morph can load the configured TypeScript project.":"rust-analyzer semantic queries are available.":n.reason??`${t} semantic checks fall back to SCIP/source evidence.`}:{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:t==="typescript"?"TypeScript is not detected/configured for this project.":"Rust is not detected/configured for this project."}}function cg(e,t){let n=new Set(Ac[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function lg(e){try{return Qf("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as dg,existsSync as Pt,readFileSync as Ct,rmSync as Mc,writeFileSync as ni}from"fs";import{join as st}from"path";var ot="<!-- scip-query:agent-setup:begin -->",On="<!-- scip-query:agent-setup:end -->",ti="# scip-query:agent-setup";function Ht(){if(process.stdin.isTTY)return"";try{return Ct(0,"utf-8")}catch{return""}}function Nn(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function Wt(e){let t=In(e.findings),n=e.findings.length-t.length,r=e.rootCauseGroups?.length??e.findings.length,i=[`scip-query diff-gate found ${t.length} issue(s) in ${r} root-cause group(s) in this diff`+(n>0?` (+${n} advisory, non-blocking)`:"")+" \u2014 fix or knowingly accept them before finishing:"],o=e.rootCauseGroups?.filter(s=>s.count>1)??[];for(let s of o)i.push(`- group [${s.check}] ${s.count} finding(s): ${s.message}`),i.push(` -> ${s.remediation}`);for(let s of e.findings)i.push(`- [${s.check}]${s.advisory?" (advisory)":""} ${s.message}`),i.push(` -> ${s.remediation}`);return i.join(`
11
- `)}function Fn(e,t={}){let n={written:[],unchanged:[],skipped:[]};return ug(e,n),t.gitHook&&pg(e,n),n}function _c(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Fc(e,"AGENTS.md",t,n),Fc(e,"CLAUDE.md",t,n),mg(e,t,n),n}function ug(e,t){let n=[ot,"## scip-query","","This repo is indexed by scip-query (compiler-resolved code intelligence).","","- Unsure how to explore, plan, verify, or clean up here: invoke the `scip-query` skill \u2014 it routes to the right specialist skill.","- Each specialist skill carries its own command shortlist \u2014 prefer it over the full `_shared` catalog.","- For non-trivial implementation requests: plan first (`scip-concrete-plan` skill, anchored by `scip-query plan-context <target>`), then implement.","- After the change, run the check matching what you did: extracted a helper -> `scip-query incomplete-migration`; new helper -> `scip-query recent-duplicates`; new params -> `scip-query unused-params`; new wrapper -> `scip-query wrapper-candidates`; schema/config change -> `scip-query co-change <file>`; deleted code -> `scip-query cleanup-plan --verify`.","- Before declaring the work done: `scip-query reindex && scip-query diff-gate` \u2014 fix findings or state why each is accepted.","- Repository records: commit `.scipquery/suppressions/*.json` and `.scipquery/events/*.json` with the code or docs change that produced them; do not ignore or drop these shared records.","- Checkout preferences: `.codex/hooks.json` and `.claude/settings.local.json` are local agent-tool settings and must not be committed.",On].join(`
12
- `);Nc(e,"AGENTS.md",n,t);let r=Pt(st(e,"CLAUDE.md"))?Ct(st(e,"CLAUDE.md"),"utf-8"):"";if(r.includes("@AGENTS.md")&&!r.includes(ot)){t.unchanged.push("CLAUDE.md");return}let i=[ot,"@AGENTS.md",On].join(`
13
- `);Nc(e,"CLAUDE.md",i,t)}function Nc(e,t,n,r){let i=st(e,t),o=Pt(i)?Ct(i,"utf-8"):"",s;if(o.includes(ot)){let a=new RegExp(`${ot}[\\s\\S]*?${On}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
2
+ import{b as vc}from"./chunk-W3557RPL.js";import{a as rt,b as v,c as _e,d as ge,e as kt,f as p,g as dc,h as C,i as $,j as se,k as ae,l as ve,m as Vt,n as Sc}from"./chunk-VXDMXZKC.js";import{$ as Nr,$a as js,$b as wa,A as Lo,Aa as cs,Ab as ta,Ac as tt,Ad as K,B as hn,Ba as qt,Bb as na,Bc as qa,Bd as uc,C as Ao,Ca as ls,Cb as ra,Cc as Ba,Cd as pc,D as Do,Da as ds,Db as ia,Dc as nt,Dd as mc,E as yn,Ea as us,Eb as oa,Ec as Oe,Ed as it,Fa as bt,Fb as sa,Fc as Ne,Fd as fc,G as et,Ga as ps,Gb as aa,Gd as Se,H as gt,Ha as ms,Hb as ca,Hc as Va,Hd as gc,I as Oo,Ib as la,Ic as Ha,Id as ue,J as No,Ja as fs,Jb as da,Jc as Wa,Jd as Dn,K as Fo,Ka as gs,Kb as ua,Kc as Ga,Kd as hc,L as Mo,La as hs,Lb as pa,Lc as Ua,Ld as L,M as _o,Ma as ys,Mb as ma,Mc as Ja,Md as B,N as qo,Na as bs,Nb as Br,Nc as za,Nd as w,O as bn,Oa as Ss,Ob as St,Oc as Ka,Od as U,P as Sn,Pa as vs,Pb as Tn,Pc as Qa,Pd as b,Q as Bo,Qa as xs,Qb as In,Qc as Ya,Qd as wt,R as ht,Ra as Rs,Rb as fa,Rc as Xa,Rd as P,S as yt,Sa as ks,Sb as ga,Sc as Za,Sd as A,T as Vo,Tb as ha,Tc as En,Td as yc,U as Ho,Ua as ws,Ub as ya,Uc as ec,Ud as I,V as vn,Va as $s,Vb as ba,Vc as tc,Vd as bc,W as Wo,Wa as Ps,Wb as Sa,Wc as jn,Wd as G,X as xn,Xa as Cs,Xb as va,Xc as nc,Y as Go,Ya as Ts,Yb as xa,Yc as Vr,Z as Rn,Za as Is,Zb as Ra,Zc as rc,_a as Es,_b as ka,_c as Hr,aa as Uo,ab as Ls,ac as $a,ad as Y,ba as Jo,bb as As,bc as Pa,c as pn,ca as zo,cb as Ds,cc as re,cd as Fe,d as me,da as Ko,db as Os,dc as Ca,dd as Rt,e as mn,eb as Ns,ec as Ta,ed as ic,f as q,fb as Fs,fc as Ia,g as J,ga as Qo,gb as Bt,gc as Ea,gd as le,ha as kn,hb as Ms,hc as ja,ia as Fr,ib as _s,ic as La,id as Ue,ja as wn,jb as qs,jd as Wr,ka as Yo,kb as Bs,kc as Aa,kd as Me,la as Mr,lb as Vs,lc as Da,ld as oe,m as Nt,ma as Xo,mb as Hs,mc as Oa,md as M,n as Ft,na as Zo,nb as Ws,nc as Ae,nd as Ln,o as Mt,oa as es,ob as Gs,oc as vt,od as E,p as Le,pa as ts,pb as Us,pc as Na,pd as Gr,q as Po,qa as _t,qb as Js,qc as fe,qd as Ur,r as fn,ra as ns,rb as zs,rc as xt,rd as Ce,s as Co,sa as rs,sb as Ks,sc as Pe,sd as oc,t as Or,ta as $n,tb as Qs,td as sc,u as To,ua as is,ub as Ys,ud as An,v as Io,va as os,vb as Xs,vd as ac,w as Eo,wa as Pn,wb as _r,wc as De,wd as cc,x as jo,xa as ss,xb as qr,xc as Fa,xd as lc,y as gn,ya as Cn,yb as Zs,yc as Ma,z as Q,za as as,zb as ea,zc as _a,zd as de}from"./chunk-VQWDZ34M.js";import{execFileSync as rl,spawn as Cg}from"child_process";import{existsSync as ct,mkdirSync as ai,readFileSync as il,rmSync as Tg,writeFileSync as Wn}from"fs";import{homedir as Ig}from"os";import{dirname as Gn,isAbsolute as Eg,join as Jt,resolve as jg}from"path";import{execFileSync as Yf}from"child_process";import{createRequire as hf}from"module";var yf=hf(import.meta.url);function xc(e,t=[]){let n=bf(),r=rs(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 bf(){try{return yf.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as $t,spawnSync as vf}from"child_process";import{existsSync as xe,mkdtempSync as $c,readFileSync as xf,readdirSync as Rf,rmSync as Pc,symlinkSync as kf,writeFileSync as wf}from"fs";import{tmpdir as Cc}from"os";import{join as ce}from"path";import{spawnSync as Sf}from"child_process";function qe(e,t=Sf){try{return t(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}var $f=3e5,Pf=12;function Kr(e,t,n={}){let r=Qr(e);if(r.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],dirtyWorkingTree:Jr(e),batches:[]};let i=Ef(t,r),o=n.timeoutMs??$f,s=Of(e,t),a=Jr(e),c=$c(ce(Cc(),"scip-cleanup-verify-")),l=[],d=new Map;try{$t("git",["-C",e,"worktree","add","--detach","--force",c,"HEAD"],{stdio:"ignore"}),Nf(e,c);for(let u of r)d.set(u.label,kc(u,c,o).rawErrors);for(let u of t.batches){Ic(c,u);let m=null;for(let f of r){let g=kc(f,c,o),h=Cf(g,d.get(f.label)??[],g.rawErrors);if(h.status==="failed"){let y=h.errors.length>0?h.errors:g.outputTail;m={depth:u.depth,status:"failed",reason:`${f.label}: ${h.reason}`,errors:y.slice(0,Pf)};break}}if(!m)l.push({depth:u.depth,status:"verified"});else{l.push(m);break}}}finally{try{$t("git",["-C",e,"worktree","remove","--force",c],{stdio:"ignore"})}catch{Pc(c,{recursive:!0,force:!0})}}return{checkers:r.map(u=>u.label),uncoveredFiles:i,baselineErrors:[...d.values()].reduce((u,m)=>u+m.length,0),dirtyOverlap:s,dirtyWorkingTree:a,batches:l}}function Cf(e,t,n){let r=Tf(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 Tf(e,t){let n=If(e),r=new Map,i=[];for(let o of t){let s=Tc(o),a=(r.get(s)??0)+1;r.set(s,a),a>(n.get(s)??0)&&i.push(o)}return i}function If(e){let t=new Map;for(let n of e){let r=Tc(n);t.set(r,(t.get(r)??0)+1)}return t}function Ef(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 Tc(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var Rc=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],jf=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function Qr(e){let t=[];if(xe(ce(e,"tsconfig.json"))){let n=ce(e,"node_modules",".bin","tsc");t.push(xe(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:Rc,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:Rc,strength:"reference-aware"})}if(xe(ce(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(ce(e,n)))){let n=Lf();n&&t.push(n)}if(jf.some(n=>xe(ce(e,n)))){let n=Af(e);n&&t.push(n)}for(let n of Df(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:ce(e,n,"..","target")}});return t}function Lf(){return qe("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"}:qe("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function Af(e){let t=ce(e,"node_modules",".bin","clj-kondo");return xe(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...mn],strength:"reference-aware"}:qe("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...mn],strength:"reference-aware"}:qe("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...mn],strength:"reference-aware"}:null}function Df(e){let t=[];if(xe(ce(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=Rf(e)}catch{return t}for(let r of n)r==="node_modules"||r.startsWith(".")||xe(ce(e,r,"Cargo.toml"))&&t.push(`${r}/Cargo.toml`);return t}function Of(e,t){let n=new Set(Jr(e));return[...new Set(t.batches.flatMap(i=>i.entries.map(o=>o.file)))].filter(i=>n.has(i)).sort()}function Jr(e){let t;try{t=$t("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}return t.split(`
3
+ `).map(n=>n.slice(3).trim()).filter(n=>n!=="").sort()}function Nf(e,t){for(let n of["node_modules"]){let r=ce(e,n),i=ce(t,n);if(xe(r)&&!xe(i))try{kf(r,i,"junction")}catch{}}}function Ic(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=ce(e,r);xe(o)&&wf(o,Ff(xf(o,"utf-8"),i,{rust:r.endsWith(".rs")}))}}function Yr(e,t){for(let n of t)Ic(e,n)}function Ec(e,t){let n=$c(ce(Cc(),"scip-cleanup-patch-"));try{return $t("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),Yr(n,t),$t("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{$t("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{Pc(n,{recursive:!0,force:!0})}}}function Xr(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 Zr(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 Ff(e,t,n={}){let r=e.split(`
4
+ `),i=(n.rust===!0?Mf(e):Po(e)).split(`
5
+ `),o=new Set;for(let s of t){let a=_f(r,s.start),c=Bf(i,a,Math.min(s.end,r.length-1));for(let l=a;l<=c&&l<r.length;l++)o.add(l)}return r.filter((s,a)=>!o.has(a)).join(`
6
+ `)}function Mf(e){return e.replace(/\/\/.*$/gm,t=>t.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,t=>t.replace(/[^\r\n]/g," ")).replace(/"(?:\\.|[^"\\\r\n])*"/g,t=>t.replace(/[^\r\n]/g," "))}function _f(e,t){let n=t;for(;n>0;){let r=(e[n-1]??"").trim();if(/^(?:\/\/\/|\/\/!|#\[|#!\[|\/\*\*|\*|\*\/|@\w)/.test(r))n-=1;else break}return n}var qf=200;function Bf(e,t,n){let r=0;for(let i=t;i<e.length;i++){for(let o of e[i]??"")o==="("||o==="["||o==="{"?r+=1:(o===")"||o==="]"||o==="}")&&(r-=1);if(i>=n&&r<=0)return i;if(i-n>qf)break}return n}function kc(e,t,n){let r=vf(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,env:e.env??process.env,maxBuffer:33554432}),i=`${r.stdout??""}
7
+ ${r.stderr??""}`;if(r.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostics:[],parseBasis:"heuristic",outputTail:wc(i)};let o=Vf(e.label,i),s=o.diagnostics.length>0?o.diagnostics:r.error?[{file:"",message:String(r.error),parseBasis:"heuristic"}]:[];return{ok:!1,exitCode:r.status,rawErrors:s.map(Qf),diagnostics:s,parseBasis:o.parseBasis,outputTail:wc(i)}}function Vf(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:Hf(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:Wf(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=Gf(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:Uf(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:Jf(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:zf(t),parseBasis:"clj-kondo-json"}:{diagnostics:Kf(t),parseBasis:"heuristic"}}function Hf(e){let t=[],n=/^(.+?)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),code:r[4],message:r[5]??"",parseBasis:"tsc"});return t}function Wf(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),message:r[4]??"",parseBasis:"go"});return t}function Gf(e){let t=jc(e);if(!Array.isArray(t))return[];let n=[];for(let r of t){if(!r||typeof r!="object")continue;let i=r,o=i.location,s=o&&typeof o=="object"?o:{},a=typeof i.filename=="string"?i.filename:"",c=typeof i.message=="string"?i.message:"";!a&&!c||n.push({file:a,line:typeof s.row=="number"?s.row:void 0,column:typeof s.column=="number"?s.column:void 0,code:typeof i.code=="string"?i.code:void 0,message:c,parseBasis:"ruff-json"})}return n}function Uf(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+([A-Z]\d{3})\s+(.+)$/gm;for(let r of e.matchAll(n))t.push({file:r[1]??"",line:Number(r[2]),column:Number(r[3]),code:r[4],message:r[5]??"",parseBasis:"ruff-text"});return t}function Jf(e){let t=[];for(let n of e.split(`
8
+ `)){if(!n.trim().startsWith("{"))continue;let r=zr(n);if(!r||typeof r!="object")continue;let i=r;if(i.reason!=="compiler-message")continue;let o=i.message;if(!o||typeof o!="object")continue;let s=o;if(s.level!=="error")continue;let l=(Array.isArray(s.spans)?s.spans:[]).find(u=>!!u&&typeof u=="object"&&u.is_primary===!0),d=s.code;t.push({file:typeof l?.file_name=="string"?l.file_name:"",line:typeof l?.line_start=="number"?l.line_start:void 0,column:typeof l?.column_start=="number"?l.column_start:void 0,code:d&&typeof d=="object"&&typeof d.code=="string"?String(d.code):void 0,message:typeof s.message=="string"?s.message:"",parseBasis:"cargo-json"})}return t}function zf(e){let t=jc(e);if(!t||typeof t!="object")return[];let n=t.findings;if(!Array.isArray(n))return[];let r=[];for(let i of n){if(!i||typeof i!="object")continue;let o=i;o.level==="error"&&r.push({file:typeof o.filename=="string"?o.filename:"",line:typeof o.row=="number"?o.row:void 0,column:typeof o.col=="number"?o.col:void 0,code:typeof o.type=="string"?o.type:void 0,message:typeof o.message=="string"?o.message:"",parseBasis:"clj-kondo-json"})}return r}function Kf(e){return e.split(`
9
+ `).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function Qf(e){let t=e.file.length>0?`${e.file}${e.line?`:${e.line}`:""}${e.column?`:${e.column}`:""}: `:"",n=e.code?`${e.code} `:"";return`${t}${n}${e.message}`.trim()}function jc(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return zr(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(r=>r>=0));return Number.isFinite(n)?zr(t.slice(n)):null}function zr(e){try{return JSON.parse(e)}catch{return null}}function wc(e,t=10){return e.split(`
10
+ `).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var Dc={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".vue"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"],clojure:[".clj",".cljs",".cljc"]},Xf={typescript:"typescript",javascript:"javascript",java:"java",scala:"scala",kotlin:"kotlin",rust:"rust",python:"python",ruby:"ruby",cpp:"cpp",c:"c",csharp:"csharp",vb:"vb",php:"php",clojure:"clojure"},Zf={typescript:"javascript",javascript:"javascript",java:"jvm",scala:"jvm",kotlin:"jvm",rust:"rust",python:"python",ruby:"ruby",cpp:"c/cpp",c:"c/cpp",csharp:"dotnet",vb:"dotnet",dart:"dart",php:"php",clojure:"clojure"};function he(e,t){let n=t.languages??tt(e),r=n.map(a=>{let c=bn(et(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),i=ag(e,n,t),o=ei({semantics:i},"typescript"),s=Qr(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:r,semantics:i,semantic:o,checkers:s,gitAvailable:dg(e)}}function Je(e,t={}){let n=e.indexers.filter(c=>c.runnable).length,r=e.languages.length===0||n===0&&!t.hasIndexedGraph?"unavailable":n===e.indexers.length&&e.indexers.length>0?"available":"partial",i=r!=="unavailable",o=e.languages.map(c=>ig(e,c,{hasIndexedGraph:og(c,t),runtimeProbe:t.runtimeProbe})),s=o.map(c=>c.cleanupVerification.status),a=s.length===0||s.every(c=>c==="unavailable")?"unavailable":s.every(c=>c==="available")?"available":"partial";return{languages:e.languages,matrix:o,capabilities:[{id:"indexing",label:"SCIP indexing",status:r,evidence:"graph-fact",reason:r==="available"?"All detected/configured language indexers are runnable.":t.hasIndexedGraph?`An indexed graph is present; ${n}/${e.indexers.length} detected/configured language indexers are runnable for refresh.`:`${n}/${e.indexers.length} detected/configured language indexers are runnable.`},...eg(e),{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:i?"available":"unavailable",evidence:"heuristic",reason:i?"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index.":"Heuristic detectors need an indexed code graph."},{id:"cleanup-verification",label:"Project cleanup verification",status:a,evidence:"checker",reason:a!=="unavailable"?o.map(c=>`${c.language}: ${c.cleanupVerification.status} (${c.cleanupVerification.reason})`).join("; "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-gate",label:"Git diff gate",status:e.gitAvailable&&i?"available":"unavailable",evidence:"git",reason:e.gitAvailable?"Git diff data is available for changed-file gates.":"Git is unavailable or the project root is not a git worktree."}]}}function eg(e){return tg(e).map(t=>{let n=ei(e,t),r=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${ng(t)} semantic provider`,status:r,evidence:"semantic",reason:rg(t,n)}})}function tg(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of Nc(e))t.add(n.language);return[...t].sort((n,r)=>Lc(n)-Lc(r))}function Lc(e){return e==="typescript"?0:1}function ng(e){return e==="typescript"?"TypeScript":"Rust"}function rg(e,t){return t?.available?e==="typescript"?"ts-morph can load the configured TypeScript project.":"rust-analyzer semantic queries are available.":t?t.reason??(e==="typescript"?"TypeScript semantic checks will fall back to SCIP/source evidence.":"Rust semantic checks will fall back to SCIP/source evidence."):e==="typescript"?"TypeScript is not detected/configured for this project.":"Rust is not detected/configured for this project."}function ig(e,t,n){let r=e.indexers.find(d=>d.language===t),i=r?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=i!=="unavailable",s=sg(t,n.runtimeProbe),a=cg(e,t),c=lg(e,t),l=c.length===0?"unavailable":c.every(d=>d.strength!=="syntax-only")?"available":"partial";return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:i==="available"?`${r?.binaryLabel??t} is runnable${r?.resolvedBinary?` at ${r.resolvedBinary}`:""}.`:i==="partial"?`An indexed ${t} graph is present, but ${r?.binaryLabel??t} is not currently runnable for refresh.`:r?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:o?s.status:"unavailable",evidence:"heuristic",reason:o?s.reason:"Source fallback needs indexed documents before it can attach evidence."},semantic:a,detectors:{id:"detectors",label:"Cleanup detectors",status:o?"available":"unavailable",evidence:"heuristic",reason:o?"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above.":"Cleanup detectors need an indexed graph for this language."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:l,evidence:"checker",reason:c.length>0?c.map(d=>d.label).join(", "):`No detected checker covers ${Dc[t].join(", ")} files.`}}}function og(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function sg(e,t){if(e==="go")return{status:"unavailable",reason:"No Go source-fallback adapter is registered; Go relies on SCIP graph facts."};if(e==="clojure")return(t?.(e)??Ac(e))==="unavailable"?{status:"unavailable",reason:"Clojure built-in reader is not available in this environment; no source-fallback evidence can be produced."}:{status:"available",reason:"Clojure source fallback uses the built-in reader for namespace imports plus callable, callsite, and protocol/record member evidence for .clj, .cljs, and .cljc files."};let n=Oc(e);if(n==="regex-only")return{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`};if(!n)return{status:"unavailable",reason:`No source-fallback adapter is registered for ${e}.`};let r=t?.(e)??Ac(e);return r==="unavailable"?{status:"partial",reason:"tree-sitter native module not loadable \u2014 regex/import-only evidence remains available where registered."}:r==="regex"?{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`}:r==="reader"?{status:"available",reason:`${e} source fallback is reader-backed.`}:{status:"available",reason:n==="ast-dispatch-with-regex-fallback"?`AST-dispatched source fallback covers ${e} imports.`:`AST/source fallback covers ${e} imports and source-backed evidence.`}}function Ac(e){let t=Xf[e];return t?fn(t):Oc(e)==="regex-only"?"regex":"unavailable"}function Oc(e){let t=Zf[e],n=t?jo(t):null;return n?.imports??n?.exports??n?.reExports??null}function ag(e,t,n){let r=[];return t.includes("typescript")&&r.push({language:"typescript",...xc(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")&&r.push({language:"rust",...Bo(e)}),r}function Nc(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function ei(e,t){return Nc(e).find(n=>n.language===t)}function cg(e,t){if(t!=="typescript"&&t!=="rust")return{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:`No semantic provider is registered for ${t}; commands use graph and source evidence instead.`};let n=ei(e,t);return n?{id:"semantic",label:"Semantic provider",status:n.available?"available":n.dependencyAvailable?"partial":"unavailable",evidence:"semantic",reason:n.available?t==="typescript"?"ts-morph can load the configured TypeScript project.":"rust-analyzer semantic queries are available.":n.reason??`${t} semantic checks fall back to SCIP/source evidence.`}:{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:t==="typescript"?"TypeScript is not detected/configured for this project.":"Rust is not detected/configured for this project."}}function lg(e,t){let n=new Set(Dc[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function dg(e){try{return Yf("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as ug,existsSync as Pt,readFileSync as Ct,rmSync as _c,writeFileSync as ni}from"fs";import{join as st}from"path";var ot="<!-- scip-query:agent-setup:begin -->",On="<!-- scip-query:agent-setup:end -->",ti="# scip-query:agent-setup";function Ht(){if(process.stdin.isTTY)return"";try{return Ct(0,"utf-8")}catch{return""}}function Nn(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function Wt(e){let t=In(e.findings),n=e.findings.length-t.length,r=e.rootCauseGroups?.length??e.findings.length,i=[`scip-query diff-gate found ${t.length} issue(s) in ${r} root-cause group(s) in this diff`+(n>0?` (+${n} advisory, non-blocking)`:"")+" \u2014 fix or knowingly accept them before finishing:"],o=e.rootCauseGroups?.filter(s=>s.count>1)??[];for(let s of o)i.push(`- group [${s.check}] ${s.count} finding(s): ${s.message}`),i.push(` -> ${s.remediation}`);for(let s of e.findings)i.push(`- [${s.check}]${s.advisory?" (advisory)":""} ${s.message}`),i.push(` -> ${s.remediation}`);return i.join(`
11
+ `)}function Fn(e,t={}){let n={written:[],unchanged:[],skipped:[]};return pg(e,n),t.gitHook&&mg(e,n),n}function qc(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Mc(e,"AGENTS.md",t,n),Mc(e,"CLAUDE.md",t,n),fg(e,t,n),n}function pg(e,t){let n=[ot,"## scip-query","","This repo is indexed by scip-query (compiler-resolved code intelligence).","","- Unsure how to explore, plan, verify, or clean up here: invoke the `scip-query` skill \u2014 it routes to the right specialist skill.","- Each specialist skill carries its own command shortlist \u2014 prefer it over the full `_shared` catalog.","- For non-trivial implementation requests: plan first (`scip-concrete-plan` skill, anchored by `scip-query plan-context <target>`), then implement.","- After the change, run the check matching what you did: extracted a helper -> `scip-query incomplete-migration`; new helper -> `scip-query recent-duplicates`; new params -> `scip-query unused-params`; new wrapper -> `scip-query wrapper-candidates`; schema/config change -> `scip-query co-change <file>`; deleted code -> `scip-query cleanup-plan --verify`.","- Before declaring the work done: `scip-query reindex && scip-query diff-gate` \u2014 fix findings or state why each is accepted.","- Repository records: commit `.scipquery/suppressions/*.json` and `.scipquery/events/*.json` with the code or docs change that produced them; do not ignore or drop these shared records.","- Checkout preferences: `.codex/hooks.json` and `.claude/settings.local.json` are local agent-tool settings and must not be committed.",On].join(`
12
+ `);Fc(e,"AGENTS.md",n,t);let r=Pt(st(e,"CLAUDE.md"))?Ct(st(e,"CLAUDE.md"),"utf-8"):"";if(r.includes("@AGENTS.md")&&!r.includes(ot)){t.unchanged.push("CLAUDE.md");return}let i=[ot,"@AGENTS.md",On].join(`
13
+ `);Fc(e,"CLAUDE.md",i,t)}function Fc(e,t,n,r){let i=st(e,t),o=Pt(i)?Ct(i,"utf-8"):"",s;if(o.includes(ot)){let a=new RegExp(`${ot}[\\s\\S]*?${On}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
14
14
 
15
15
  `)}${n}
16
16
  `:`${n}
17
- `;s===o?r.unchanged.push(t):(ni(i,s),r.written.push(t))}function Fc(e,t,n,r){let i=st(e,t);if(!Pt(i)){r.unchanged.push(t);return}let o=Ct(i,"utf-8");if(!o.includes(ot)){r.unchanged.push(t);return}let s=new RegExp(`${ot}[\\s\\S]*?${On}`),a=o.replace(s,"").replace(/\n{3,}/g,`
17
+ `;s===o?r.unchanged.push(t):(ni(i,s),r.written.push(t))}function Mc(e,t,n,r){let i=st(e,t);if(!Pt(i)){r.unchanged.push(t);return}let o=Ct(i,"utf-8");if(!o.includes(ot)){r.unchanged.push(t);return}let s=new RegExp(`${ot}[\\s\\S]*?${On}`),a=o.replace(s,"").replace(/\n{3,}/g,`
18
18
 
19
- `).trim();r.removed.push(t),!n.dryRun&&(a.length===0?Mc(i,{force:!0}):ni(i,`${a}
20
- `))}function pg(e,t){let n=st(e,".git","hooks");if(!Pt(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let r=st(n,"pre-commit"),i=["#!/bin/sh",ti,"scip-query diff-gate || {",' echo "scip-query diff-gate failed \u2014 fix findings or commit with --no-verify to knowingly accept." >&2'," exit 1","}",""].join(`
21
- `);if(Pt(r)){let o=Ct(r,"utf-8");if(o.includes(ti)){if(o===i){t.unchanged.push(".git/hooks/pre-commit");return}}else{t.skipped.push({target:".git/hooks/pre-commit",reason:"a pre-commit hook already exists \u2014 add `scip-query diff-gate` to it manually"});return}}ni(r,i),dg(r,493),t.written.push(".git/hooks/pre-commit")}function mg(e,t,n){let r=st(e,".git","hooks","pre-commit");if(!Pt(r)){n.unchanged.push(".git/hooks/pre-commit");return}if(!Ct(r,"utf-8").includes(ti)){n.skipped.push({target:".git/hooks/pre-commit",reason:"pre-commit hook is not managed by scip-query"});return}n.removed.push(".git/hooks/pre-commit"),t.dryRun||Mc(r,{force:!0})}import{createHash as fg}from"crypto";import{existsSync as _n,mkdirSync as gg,readFileSync as qn,readdirSync as hg,rmSync as qc,writeFileSync as Bc}from"fs";import{join as Be}from"path";var Bn=Be(".scipquery","events"),yg=Be(".scipquery","ledger"),Vc="events.jsonl";function Hc(e){return Be(e,yg)}function ri(e){return Be(Hc(e),Vc)}function Wc(e,t,n,r,i,o={}){let s=new Map(e.map(l=>[re(l.check,l.findingId),l])),a=[],c=(l,d)=>{let u=n.get(l.findingId),m=d==="resolved"?o.verifiedAgainstByFinding?.get(re(l.check,l.findingId)):void 0;a.push({ts:i,check:l.check,findingId:l.findingId,event:d,commit:r,...o.comparisonBaseCommit?{comparisonBaseCommit:o.comparisonBaseCommit}:{},...m?{verifiedAgainstCommit:m}:{},...u?{symbol:u}:{}})};for(let l of t){let d=s.get(re(l.check,l.findingId));if(!d){c(l,"caught"),l.outcome==="suppressed"&&c(l,"suppressed");continue}d.outcome!==l.outcome&&(l.outcome==="resolved"?c(l,"resolved"):l.outcome==="suppressed"?c(l,"suppressed"):l.outcome==="still-open"&&c(l,"reopened"))}return a}function Gc(e){return ii(e,"HEAD")}function ii(e,t){try{let n=qr(e,["rev-parse","--verify",`${t}^{commit}`]).trim();return/^[0-9a-f]{40}$/.test(n)?n:null}catch{return null}}function Uc(e){try{return qr(e,["status","--porcelain=v1","--untracked-files=all"]).trim()===""}catch{return!1}}function Jc(e,t){let n=ri(e),r=_n(n),i=[...r?zc(n):[],...t];if(i.length>0){let o=Be(e,Bn);gg(o,{recursive:!0});for(let s of i)bg(o,s)}r&&Sg(e)}function bg(e,t){let n=`${JSON.stringify({ts:t.ts,check:t.check,findingId:t.findingId,event:t.event,commit:t.commit,...t.comparisonBaseCommit?{comparisonBaseCommit:t.comparisonBaseCommit}:{},...t.verifiedAgainstCommit?{verifiedAgainstCommit:t.verifiedAgainstCommit}:{},...t.symbol?{symbol:t.symbol}:{}},null,2)}
22
- `,r=fg("sha256").update(n).digest("hex").slice(0,16).toUpperCase(),i=Be(e,`${t.ts}-${r}.json`);try{Bc(i,n,{flag:"wx"})}catch(o){if(o.code!=="EEXIST")throw o;if(qn(i,"utf-8")!==n)throw new Error(`outcome event filename collision: ${i}`,{cause:o})}}function Sg(e){qc(ri(e));let t=Be(Hc(e),".gitattributes");if(!_n(t))return;let n=qn(t,"utf-8").split(`
23
- `).filter(r=>r.trim()!==`${Vc} merge=union`).join(`
24
- `).replace(/^\n+|\n+$/g,"");n===""?qc(t):Bc(t,`${n}
25
- `)}function Vn(e){let t=[],n=Be(e,Bn);if(_n(n))for(let i of hg(n).sort()){if(!i.endsWith(".json"))continue;let o=Kc(qn(Be(n,i),"utf-8"));o&&t.push(o)}let r=ri(e);return _n(r)&&t.push(...zc(r)),vg(t)}function zc(e){let t=[];for(let n of qn(e,"utf-8").split(`
26
- `)){let r=Kc(n);r&&t.push(r)}return t}function Kc(e){if(e.trim()==="")return null;let t;try{t=JSON.parse(e)}catch{return null}return Rg(t)?t:null}function vg(e){let t=new Map;for(let n of e){let r=`${n.check}\0${n.findingId}\0${n.event}\0${n.commit??""}`,i=t.get(r);(!i||Mn(n)>Mn(i)||Mn(n)===Mn(i)&&n.ts<i.ts)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.ts-r.ts)}function Gt(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n?.event==="caught"||n?.event==="reopened")return n}}function Mn(e){return+(e.comparisonBaseCommit!==void 0)+ +(e.verifiedAgainstCommit!==void 0)*2}var xg=["caught","resolved","suppressed","reopened"];function Rg(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.ts=="number"&&typeof t.check=="string"&&typeof t.findingId=="string"&&xg.includes(t.event)&&(t.commit===null||typeof t.commit=="string")&&(t.comparisonBaseCommit===void 0||typeof t.comparisonBaseCommit=="string")&&(t.verifiedAgainstCommit===void 0||t.event==="resolved"&&typeof t.verifiedAgainstCommit=="string")&&(t.symbol===void 0||typeof t.symbol=="string")}function Hn(e,t,n={}){let r=(n.now??Date.now)(),i=wg(t),o=Pa(e),s=e.config.projectRoot,a=(n.headCommit??Gc)(s),c=(n.resolveCommit??ii)(s,t.base),l=kg({previous:o,observed:i,result:t,projectRoot:s,commit:a,comparisonBaseCommit:c,runtime:n}),d=Ca(e,l.ledgerObserved,l.checksRun,r,l.retainedKeys);try{let u=new Map;for(let f of t.findings)f.symbol&&u.set(f.id,f.symbol);for(let f of t.suppressed)f.finding.symbol&&u.set(f.finding.id,f.finding.symbol);for(let[f,g]of l.replaySymbols)u.set(f,g);let m=Wc(o,d,u,a,r,{...c?{comparisonBaseCommit:c}:{},verifiedAgainstByFinding:l.verifiedAgainstByFinding});return(n.appendEvents??Jc)(s,m),{ledger:d,observed:i,now:r,...l.warning?{warning:l.warning}:{}}}catch(u){return{ledger:d,observed:i,now:r,warning:[l.warning,`outcome event ledger not updated: ${u instanceof Error?u.message:String(u)}`].filter(Boolean).join("; ")}}}function kg(e){let t=[...e.observed],n=new Set(e.result.checksRun),r=new Set,i=new Map,o=new Map,s=new Set(e.observed.map(h=>re(h.check,h.findingId))),a=new Set(e.result.checksRun),c=e.result.changedFiles.length===0&&!Tn(e.result)&&e.commit!==null&&e.comparisonBaseCommit!==null,l=e.previous.filter(h=>h.outcome!=="resolved"&&(a.has(h.check)||c)&&!s.has(re(h.check,h.findingId)));if(at(`primary base=${String(e.comparisonBaseCommit)} head=${String(e.commit)} checks=${e.result.checksRun.join(",")} missing=${l.length}`),l.length===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let d;try{d=(e.runtime.readEvents??Vn)(e.projectRoot)}catch(h){for(let y of l)r.add(re(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,warning:`cross-HEAD outcome verification deferred: ${h instanceof Error?h.message:String(h)}`}}let u=new Map;for(let h of d){let y=re(h.check,h.findingId),S=u.get(y)??[];S.push(h),u.set(y,S)}let m=new Map;for(let h of l){let y=re(h.check,h.findingId),S=Gt(u.get(y)??[]),x=S?.comparisonBaseCommit??S?.commit;if(at(`candidate ${y} anchor=${String(x)} current=${String(e.comparisonBaseCommit)}`),!S?.comparisonBaseCommit&&S?.commit&&S.commit===e.commit){n.add(h.check);continue}if(!x||!e.commit||!e.comparisonBaseCommit){r.add(y);continue}if(x===e.comparisonBaseCommit){n.add(h.check);continue}let k=m.get(x)??[];k.push(h),m.set(x,k)}if(m.size===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let f=(e.runtime.worktreeIsClean??Uc)(e.projectRoot);if(at(`replay groups=${m.size} clean=${f} callback=${!!e.runtime.replayGate}`),!f||!e.runtime.replayGate){for(let h of m.values())for(let y of h)r.add(re(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o}}let g=[];for(let[h,y]of m){let S;try{S=e.runtime.replayGate(h),at(`replay base=${h} checks=${S.checksRun.join(",")} findings=${S.findings.length} suppressed=${S.suppressed.length}`)}catch(R){for(let D of y)r.add(re(D.check,D.findingId));g.push(`cross-HEAD outcome verification deferred for ${h.slice(0,12)}: ${R instanceof Error?R.message:String(R)}`);continue}let x=new Set(S.checksRun),k=$g(S);for(let R of y){let D=re(R.check,R.findingId);if(!x.has(R.check)){r.add(D);continue}n.add(R.check);let _=k.find(O=>O.key===D);if(_){at(`replay retained exact ${D}`),t.push(_.observed),_.symbol&&o.set(_.observed.findingId,_.symbol);continue}let z=Gt(u.get(D)??[]),T=z?.symbol?k.find(O=>O.check===R.check&&O.symbol===z.symbol):void 0;if(T){at(`replay moved ${D} -> ${T.key}`),t.push(T.observed),T.symbol&&o.set(T.observed.findingId,T.symbol);continue}i.set(D,h),at(`replay verified ${D} against ${h}`)}}return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,...g.length>0?{warning:g.join("; ")}:{}}}function at(e){process.env.SCIP_QUERY_DEBUG&&console.error(`outcome-verification: ${e}`)}function wg(e){return[...e.findings.map(t=>({check:t.check,findingId:t.id,suppressed:!1})),...e.suppressed.map(t=>({check:t.finding.check,findingId:t.finding.id,suppressed:!0}))]}function $g(e){return[...e.findings.map(t=>({key:re(t.check,t.id),check:t.check,observed:{check:t.check,findingId:t.id,suppressed:!1},...t.symbol?{symbol:t.symbol}:{}})),...e.suppressed.map(t=>({key:re(t.finding.check,t.finding.id),check:t.finding.check,observed:{check:t.finding.check,findingId:t.finding.id,suppressed:!0},...t.finding.symbol?{symbol:t.finding.symbol}:{}}))]}var il="SCIP_QUERY_SKIP_HOOK_INSTALL",oi="SCIP_QUERY_STOP_HOOK_MODE",jg="scip-query hook-",Lg="scip-query diff-gate --hook",Qc="# scip-query:local-hooks:begin",Yc="# scip-query:local-hooks:end",Ut=[{relativePath:".codex/hooks.json",label:".codex/hooks.json"},{relativePath:".claude/settings.local.json",label:".claude/settings.local.json"}];function Tt(e,t={}){let n=ol(),r=t.env??process.env;if(Ng(r))return n.skipped.push({target:"project agent hooks",reason:`${il}=1`}),n;let i=Hg(e);return t.shared&&n.warnings.push("--shared is deprecated; project hooks are always checkout-local and will not be committed."),Dg(e,n,t.dryRun),t.remove?(Zc(e,Ut[0],n,{dryRun:t.dryRun}),Zc(e,Ut[1],n,{writeDeclinedTombstone:!0,dryRun:t.dryRun}),n):(Xc(e,Ut[0],n,{provider:"codex",commandPrefix:i,force:t.force}),Xc(e,Ut[1],n,{provider:"claude",commandPrefix:i,force:t.force}),t.removeLegacyUserHooks!==!1&&Ag({homeDir:t.homeDir,result:n}),n)}function Ag(e={}){let t=e.result??ol(),n=e.homeDir??Tg();return si({configPath:Jt(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),si({configPath:Jt(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function ol(){return{installed:[],updated:[],unchanged:[],removed:[],gitExcluded:[],warnings:[],skipped:[]}}function Xc(e,t,n,r){if(ci(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook setup will not modify it"});return}let i=Jt(e,t.relativePath);Mg({provider:r.provider,rootDir:Gn(i),configPath:i,label:t.label,createRoot:!0,commandPrefix:r.commandPrefix,force:r.force,result:n})}function Zc(e,t,n,r){if(ci(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook removal will not modify it"});return}_g({configPath:Jt(e,t.relativePath),label:t.label,result:n,writeDeclinedTombstone:r.writeDeclinedTombstone,dryRun:r.dryRun})}function Dg(e,t,n=!1){let r=Og(e);if(!r){t.warnings.push("Could not locate .git/info/exclude; local hook files may appear as untracked.");return}let i=Ut.filter(d=>!ci(e,d.relativePath));if(i.length===0)return;let o=[Qc,...i.map(d=>`/${d.relativePath}`),Yc].join(`
27
- `),s=ct(r)?rl(r,"utf-8"):"",a=new RegExp(`${Le(Qc)}[\\s\\S]*?${Le(Yc)}\\n?`,"g"),c=s.replace(a,"").replace(/\n*$/,""),l=`${c}${c?`
19
+ `).trim();r.removed.push(t),!n.dryRun&&(a.length===0?_c(i,{force:!0}):ni(i,`${a}
20
+ `))}function mg(e,t){let n=st(e,".git","hooks");if(!Pt(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let r=st(n,"pre-commit"),i=["#!/bin/sh",ti,"scip-query diff-gate || {",' echo "scip-query diff-gate failed \u2014 fix findings or commit with --no-verify to knowingly accept." >&2'," exit 1","}",""].join(`
21
+ `);if(Pt(r)){let o=Ct(r,"utf-8");if(o.includes(ti)){if(o===i){t.unchanged.push(".git/hooks/pre-commit");return}}else{t.skipped.push({target:".git/hooks/pre-commit",reason:"a pre-commit hook already exists \u2014 add `scip-query diff-gate` to it manually"});return}}ni(r,i),ug(r,493),t.written.push(".git/hooks/pre-commit")}function fg(e,t,n){let r=st(e,".git","hooks","pre-commit");if(!Pt(r)){n.unchanged.push(".git/hooks/pre-commit");return}if(!Ct(r,"utf-8").includes(ti)){n.skipped.push({target:".git/hooks/pre-commit",reason:"pre-commit hook is not managed by scip-query"});return}n.removed.push(".git/hooks/pre-commit"),t.dryRun||_c(r,{force:!0})}import{createHash as gg}from"crypto";import{existsSync as _n,mkdirSync as hg,readFileSync as qn,readdirSync as yg,rmSync as Bc,writeFileSync as Vc}from"fs";import{join as Be}from"path";var Bn=Be(".scipquery","events"),bg=Be(".scipquery","ledger"),Hc="events.jsonl";function Wc(e){return Be(e,bg)}function ri(e){return Be(Wc(e),Hc)}function Gc(e,t,n,r,i,o={}){let s=new Map(e.map(l=>[re(l.check,l.findingId),l])),a=[],c=(l,d)=>{let u=n.get(l.findingId),m=d==="resolved"?o.verifiedAgainstByFinding?.get(re(l.check,l.findingId)):void 0;a.push({ts:i,check:l.check,findingId:l.findingId,event:d,commit:r,...o.comparisonBaseCommit?{comparisonBaseCommit:o.comparisonBaseCommit}:{},...m?{verifiedAgainstCommit:m}:{},...u?{symbol:u}:{}})};for(let l of t){let d=s.get(re(l.check,l.findingId));if(!d){c(l,"caught"),l.outcome==="suppressed"&&c(l,"suppressed");continue}d.outcome!==l.outcome&&(l.outcome==="resolved"?c(l,"resolved"):l.outcome==="suppressed"?c(l,"suppressed"):l.outcome==="still-open"&&c(l,"reopened"))}return a}function Uc(e){return ii(e,"HEAD")}function ii(e,t){try{let n=qr(e,["rev-parse","--verify",`${t}^{commit}`]).trim();return/^[0-9a-f]{40}$/.test(n)?n:null}catch{return null}}function Jc(e){try{return qr(e,["status","--porcelain=v1","--untracked-files=all"]).trim()===""}catch{return!1}}function zc(e,t){let n=ri(e),r=_n(n),i=[...r?Kc(n):[],...t];if(i.length>0){let o=Be(e,Bn);hg(o,{recursive:!0});for(let s of i)Sg(o,s)}r&&vg(e)}function Sg(e,t){let n=`${JSON.stringify({ts:t.ts,check:t.check,findingId:t.findingId,event:t.event,commit:t.commit,...t.comparisonBaseCommit?{comparisonBaseCommit:t.comparisonBaseCommit}:{},...t.verifiedAgainstCommit?{verifiedAgainstCommit:t.verifiedAgainstCommit}:{},...t.symbol?{symbol:t.symbol}:{}},null,2)}
22
+ `,r=gg("sha256").update(n).digest("hex").slice(0,16).toUpperCase(),i=Be(e,`${t.ts}-${r}.json`);try{Vc(i,n,{flag:"wx"})}catch(o){if(o.code!=="EEXIST")throw o;if(qn(i,"utf-8")!==n)throw new Error(`outcome event filename collision: ${i}`,{cause:o})}}function vg(e){Bc(ri(e));let t=Be(Wc(e),".gitattributes");if(!_n(t))return;let n=qn(t,"utf-8").split(`
23
+ `).filter(r=>r.trim()!==`${Hc} merge=union`).join(`
24
+ `).replace(/^\n+|\n+$/g,"");n===""?Bc(t):Vc(t,`${n}
25
+ `)}function Vn(e){let t=[],n=Be(e,Bn);if(_n(n))for(let i of yg(n).sort()){if(!i.endsWith(".json"))continue;let o=Qc(qn(Be(n,i),"utf-8"));o&&t.push(o)}let r=ri(e);return _n(r)&&t.push(...Kc(r)),xg(t)}function Kc(e){let t=[];for(let n of qn(e,"utf-8").split(`
26
+ `)){let r=Qc(n);r&&t.push(r)}return t}function Qc(e){if(e.trim()==="")return null;let t;try{t=JSON.parse(e)}catch{return null}return kg(t)?t:null}function xg(e){let t=new Map;for(let n of e){let r=`${n.check}\0${n.findingId}\0${n.event}\0${n.commit??""}`,i=t.get(r);(!i||Mn(n)>Mn(i)||Mn(n)===Mn(i)&&n.ts<i.ts)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.ts-r.ts)}function Gt(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n?.event==="caught"||n?.event==="reopened")return n}}function Mn(e){return+(e.comparisonBaseCommit!==void 0)+ +(e.verifiedAgainstCommit!==void 0)*2}var Rg=["caught","resolved","suppressed","reopened"];function kg(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.ts=="number"&&typeof t.check=="string"&&typeof t.findingId=="string"&&Rg.includes(t.event)&&(t.commit===null||typeof t.commit=="string")&&(t.comparisonBaseCommit===void 0||typeof t.comparisonBaseCommit=="string")&&(t.verifiedAgainstCommit===void 0||t.event==="resolved"&&typeof t.verifiedAgainstCommit=="string")&&(t.symbol===void 0||typeof t.symbol=="string")}function Hn(e,t,n={}){let r=(n.now??Date.now)(),i=$g(t),o=Ca(e),s=e.config.projectRoot,a=(n.headCommit??Uc)(s),c=(n.resolveCommit??ii)(s,t.base),l=wg({previous:o,observed:i,result:t,projectRoot:s,commit:a,comparisonBaseCommit:c,runtime:n}),d=Ta(e,l.ledgerObserved,l.checksRun,r,l.retainedKeys);try{let u=new Map;for(let f of t.findings)f.symbol&&u.set(f.id,f.symbol);for(let f of t.suppressed)f.finding.symbol&&u.set(f.finding.id,f.finding.symbol);for(let[f,g]of l.replaySymbols)u.set(f,g);let m=Gc(o,d,u,a,r,{...c?{comparisonBaseCommit:c}:{},verifiedAgainstByFinding:l.verifiedAgainstByFinding});return(n.appendEvents??zc)(s,m),{ledger:d,observed:i,now:r,...l.warning?{warning:l.warning}:{}}}catch(u){return{ledger:d,observed:i,now:r,warning:[l.warning,`outcome event ledger not updated: ${u instanceof Error?u.message:String(u)}`].filter(Boolean).join("; ")}}}function wg(e){let t=[...e.observed],n=new Set(e.result.checksRun),r=new Set,i=new Map,o=new Map,s=new Set(e.observed.map(h=>re(h.check,h.findingId))),a=new Set(e.result.checksRun),c=e.result.changedFiles.length===0&&!Tn(e.result)&&e.commit!==null&&e.comparisonBaseCommit!==null,l=e.previous.filter(h=>h.outcome!=="resolved"&&(a.has(h.check)||c)&&!s.has(re(h.check,h.findingId)));if(at(`primary base=${String(e.comparisonBaseCommit)} head=${String(e.commit)} checks=${e.result.checksRun.join(",")} missing=${l.length}`),l.length===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let d;try{d=(e.runtime.readEvents??Vn)(e.projectRoot)}catch(h){for(let y of l)r.add(re(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,warning:`cross-HEAD outcome verification deferred: ${h instanceof Error?h.message:String(h)}`}}let u=new Map;for(let h of d){let y=re(h.check,h.findingId),S=u.get(y)??[];S.push(h),u.set(y,S)}let m=new Map;for(let h of l){let y=re(h.check,h.findingId),S=Gt(u.get(y)??[]),x=S?.comparisonBaseCommit??S?.commit;if(at(`candidate ${y} anchor=${String(x)} current=${String(e.comparisonBaseCommit)}`),!S?.comparisonBaseCommit&&S?.commit&&S.commit===e.commit){n.add(h.check);continue}if(!x||!e.commit||!e.comparisonBaseCommit){r.add(y);continue}if(x===e.comparisonBaseCommit){n.add(h.check);continue}let k=m.get(x)??[];k.push(h),m.set(x,k)}if(m.size===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o};let f=(e.runtime.worktreeIsClean??Jc)(e.projectRoot);if(at(`replay groups=${m.size} clean=${f} callback=${!!e.runtime.replayGate}`),!f||!e.runtime.replayGate){for(let h of m.values())for(let y of h)r.add(re(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o}}let g=[];for(let[h,y]of m){let S;try{S=e.runtime.replayGate(h),at(`replay base=${h} checks=${S.checksRun.join(",")} findings=${S.findings.length} suppressed=${S.suppressed.length}`)}catch(R){for(let D of y)r.add(re(D.check,D.findingId));g.push(`cross-HEAD outcome verification deferred for ${h.slice(0,12)}: ${R instanceof Error?R.message:String(R)}`);continue}let x=new Set(S.checksRun),k=Pg(S);for(let R of y){let D=re(R.check,R.findingId);if(!x.has(R.check)){r.add(D);continue}n.add(R.check);let _=k.find(O=>O.key===D);if(_){at(`replay retained exact ${D}`),t.push(_.observed),_.symbol&&o.set(_.observed.findingId,_.symbol);continue}let z=Gt(u.get(D)??[]),T=z?.symbol?k.find(O=>O.check===R.check&&O.symbol===z.symbol):void 0;if(T){at(`replay moved ${D} -> ${T.key}`),t.push(T.observed),T.symbol&&o.set(T.observed.findingId,T.symbol);continue}i.set(D,h),at(`replay verified ${D} against ${h}`)}}return{ledgerObserved:t,checksRun:[...n],retainedKeys:r,verifiedAgainstByFinding:i,replaySymbols:o,...g.length>0?{warning:g.join("; ")}:{}}}function at(e){process.env.SCIP_QUERY_DEBUG&&console.error(`outcome-verification: ${e}`)}function $g(e){return[...e.findings.map(t=>({check:t.check,findingId:t.id,suppressed:!1})),...e.suppressed.map(t=>({check:t.finding.check,findingId:t.finding.id,suppressed:!0}))]}function Pg(e){return[...e.findings.map(t=>({key:re(t.check,t.id),check:t.check,observed:{check:t.check,findingId:t.id,suppressed:!1},...t.symbol?{symbol:t.symbol}:{}})),...e.suppressed.map(t=>({key:re(t.finding.check,t.finding.id),check:t.finding.check,observed:{check:t.finding.check,findingId:t.finding.id,suppressed:!0},...t.finding.symbol?{symbol:t.finding.symbol}:{}}))]}var ol="SCIP_QUERY_SKIP_HOOK_INSTALL",oi="SCIP_QUERY_STOP_HOOK_MODE",Lg="scip-query hook-",Ag="scip-query diff-gate --hook",Yc="# scip-query:local-hooks:begin",Xc="# scip-query:local-hooks:end",Ut=[{relativePath:".codex/hooks.json",label:".codex/hooks.json"},{relativePath:".claude/settings.local.json",label:".claude/settings.local.json"}];function Tt(e,t={}){let n=sl(),r=t.env??process.env;if(Fg(r))return n.skipped.push({target:"project agent hooks",reason:`${ol}=1`}),n;let i=Wg(e);return t.shared&&n.warnings.push("--shared is deprecated; project hooks are always checkout-local and will not be committed."),Og(e,n,t.dryRun),t.remove?(el(e,Ut[0],n,{dryRun:t.dryRun}),el(e,Ut[1],n,{writeDeclinedTombstone:!0,dryRun:t.dryRun}),n):(Zc(e,Ut[0],n,{provider:"codex",commandPrefix:i,force:t.force}),Zc(e,Ut[1],n,{provider:"claude",commandPrefix:i,force:t.force}),t.removeLegacyUserHooks!==!1&&Dg({homeDir:t.homeDir,result:n}),n)}function Dg(e={}){let t=e.result??sl(),n=e.homeDir??Ig();return si({configPath:Jt(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),si({configPath:Jt(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function sl(){return{installed:[],updated:[],unchanged:[],removed:[],gitExcluded:[],warnings:[],skipped:[]}}function Zc(e,t,n,r){if(ci(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook setup will not modify it"});return}let i=Jt(e,t.relativePath);_g({provider:r.provider,rootDir:Gn(i),configPath:i,label:t.label,createRoot:!0,commandPrefix:r.commandPrefix,force:r.force,result:n})}function el(e,t,n,r){if(ci(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook removal will not modify it"});return}qg({configPath:Jt(e,t.relativePath),label:t.label,result:n,writeDeclinedTombstone:r.writeDeclinedTombstone,dryRun:r.dryRun})}function Og(e,t,n=!1){let r=Ng(e);if(!r){t.warnings.push("Could not locate .git/info/exclude; local hook files may appear as untracked.");return}let i=Ut.filter(d=>!ci(e,d.relativePath));if(i.length===0)return;let o=[Yc,...i.map(d=>`/${d.relativePath}`),Xc].join(`
27
+ `),s=ct(r)?il(r,"utf-8"):"",a=new RegExp(`${Le(Yc)}[\\s\\S]*?${Le(Xc)}\\n?`,"g"),c=s.replace(a,"").replace(/\n*$/,""),l=`${c}${c?`
28
28
 
29
29
  `:""}${o}
30
- `;!n&&l!==s&&(ai(Gn(r),{recursive:!0}),Wn(r,l)),t.gitExcluded.push(...i.map(d=>d.label))}function Og(e){try{let t=nl("git",["-C",e,"rev-parse","--git-path","info/exclude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();return t?Ig(t)?t:Eg(e,t):null}catch{return null}}function ci(e,t){try{return nl("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore"}),!0}catch{return!1}}function Ng(e=process.env){let t=e[il];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function Fg(e=process.env){let t=e[oi]?.toLowerCase();return t==="block"||t==="blocking"?"block":t==="warn"?"warn":"feedback"}function Mg(e){if(!e.createRoot&&!ct(e.rootDir))return;let t=li(e.configPath,e.label,e.result);if(!t)return;if(t.scipQueryHooks==="declined"&&!e.force){e.result.skipped.push({target:e.label,reason:"scip-query hooks were previously removed; rerun with --force"});return}let n=qg(t,e.provider,e.commandPrefix);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let r=ct(e.configPath);ai(Gn(e.configPath),{recursive:!0}),Wn(e.configPath,`${JSON.stringify(n,null,2)}
31
- `),e.result[r?"updated":"installed"].push(e.label)}function si(e){if(!ct(e.configPath))return;let t=li(e.configPath,e.label,e.result);if(!t)return;let n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:{},r={...n},i=!1;for(let s of["SessionStart","UserPromptSubmit","Stop"]){let a=Array.isArray(n[s])?n[s]:[],c=sl(a);(c.length!==a.length||JSON.stringify(c)!==JSON.stringify(a))&&(i=!0,c.length>0?r[s]=c:delete r[s])}if(!i)return;let o={...t};Object.keys(r).length>0?o.hooks=r:delete o.hooks,e.dryRun||(Object.keys(o).length===0?Cg(e.configPath,{force:!0}):Wn(e.configPath,`${JSON.stringify(o,null,2)}
32
- `)),e.result.removed.push(e.label)}function _g(e){let t=e.result.removed.length;if(si(e),!e.writeDeclinedTombstone)return;let n=li(e.configPath,e.label,e.result);if(!n)return;let r={...n,scipQueryHooks:"declined"};e.dryRun||(ai(Gn(e.configPath),{recursive:!0}),Wn(e.configPath,`${JSON.stringify(r,null,2)}
33
- `)),e.result.removed.length===t&&e.result.removed.push(`${e.label} (declined)`)}function li(e,t,n){if(!ct(e))return{};try{let r=JSON.parse(rl(e,"utf-8"));if(!r||typeof r!="object"||Array.isArray(r)){n.skipped.push({target:t,reason:"existing hook config is not a JSON object"});return}return r}catch(r){n.skipped.push({target:t,reason:`could not parse existing hook config: ${r instanceof Error?r.message:String(r)}`});return}}function qg(e,t,n="scip-query"){let r=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},i={...e,hooks:{...r}};i.scipQueryHooks==="declined"&&delete i.scipQueryHooks;for(let o of["SessionStart","UserPromptSubmit","Stop"]){let s=Array.isArray(r[o])?r[o]:[];i.hooks[o]=[...sl(s),Vg(t,o,n)]}return i}function sl(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!Bg(n)):[]})).filter(t=>t.hooks.length>0)}function Bg(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(jg)||t===Lg)}function Vg(e,t,n){return t==="SessionStart"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:60,statusMessage:"Refreshing scip-query context"}]}:t==="UserPromptSubmit"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:60,statusMessage:"Checking scip-query freshness"}]}:{hooks:[{type:"command",command:`${n} hook-stop`,timeout:30,statusMessage:"Running scip-query diff gate"}]}}function Hg(e){let t=Jt(e,"node_modules",".bin","scip-query");return ct(t)?t:"scip-query"}async function al(){let e=await Jg(Ht());e&&console.log(JSON.stringify(e))}function Wg(e){if(Nn(e))return;let t=ll(e),n=dl(t);if(!(!n||!ct(n.paths.dbPath)))return nh(n,r=>{let i={minTogether:6,skip:[]},o=St(r,i),s=Hn(r,o,{replayGate:a=>St(r,{...i,base:a})});return s.warning&&console.error(`note: ${s.warning}`),o})}function cl(){let e=Wg(Ht());!e||e.findings.length===0||console.log(JSON.stringify(Gg(e,Fg())))}function Gg(e,t="feedback"){let n=Wt(e),r=Ug(e);return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${r}
30
+ `;!n&&l!==s&&(ai(Gn(r),{recursive:!0}),Wn(r,l)),t.gitExcluded.push(...i.map(d=>d.label))}function Ng(e){try{let t=rl("git",["-C",e,"rev-parse","--git-path","info/exclude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();return t?Eg(t)?t:jg(e,t):null}catch{return null}}function ci(e,t){try{return rl("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore"}),!0}catch{return!1}}function Fg(e=process.env){let t=e[ol];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function Mg(e=process.env){let t=e[oi]?.toLowerCase();return t==="block"||t==="blocking"?"block":t==="warn"?"warn":"feedback"}function _g(e){if(!e.createRoot&&!ct(e.rootDir))return;let t=li(e.configPath,e.label,e.result);if(!t)return;if(t.scipQueryHooks==="declined"&&!e.force){e.result.skipped.push({target:e.label,reason:"scip-query hooks were previously removed; rerun with --force"});return}let n=Bg(t,e.provider,e.commandPrefix);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let r=ct(e.configPath);ai(Gn(e.configPath),{recursive:!0}),Wn(e.configPath,`${JSON.stringify(n,null,2)}
31
+ `),e.result[r?"updated":"installed"].push(e.label)}function si(e){if(!ct(e.configPath))return;let t=li(e.configPath,e.label,e.result);if(!t)return;let n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:{},r={...n},i=!1;for(let s of["SessionStart","UserPromptSubmit","Stop"]){let a=Array.isArray(n[s])?n[s]:[],c=al(a);(c.length!==a.length||JSON.stringify(c)!==JSON.stringify(a))&&(i=!0,c.length>0?r[s]=c:delete r[s])}if(!i)return;let o={...t};Object.keys(r).length>0?o.hooks=r:delete o.hooks,e.dryRun||(Object.keys(o).length===0?Tg(e.configPath,{force:!0}):Wn(e.configPath,`${JSON.stringify(o,null,2)}
32
+ `)),e.result.removed.push(e.label)}function qg(e){let t=e.result.removed.length;if(si(e),!e.writeDeclinedTombstone)return;let n=li(e.configPath,e.label,e.result);if(!n)return;let r={...n,scipQueryHooks:"declined"};e.dryRun||(ai(Gn(e.configPath),{recursive:!0}),Wn(e.configPath,`${JSON.stringify(r,null,2)}
33
+ `)),e.result.removed.length===t&&e.result.removed.push(`${e.label} (declined)`)}function li(e,t,n){if(!ct(e))return{};try{let r=JSON.parse(il(e,"utf-8"));if(!r||typeof r!="object"||Array.isArray(r)){n.skipped.push({target:t,reason:"existing hook config is not a JSON object"});return}return r}catch(r){n.skipped.push({target:t,reason:`could not parse existing hook config: ${r instanceof Error?r.message:String(r)}`});return}}function Bg(e,t,n="scip-query"){let r=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},i={...e,hooks:{...r}};i.scipQueryHooks==="declined"&&delete i.scipQueryHooks;for(let o of["SessionStart","UserPromptSubmit","Stop"]){let s=Array.isArray(r[o])?r[o]:[];i.hooks[o]=[...al(s),Hg(t,o,n)]}return i}function al(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!Vg(n)):[]})).filter(t=>t.hooks.length>0)}function Vg(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(Lg)||t===Ag)}function Hg(e,t,n){return t==="SessionStart"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:60,statusMessage:"Refreshing scip-query context"}]}:t==="UserPromptSubmit"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:60,statusMessage:"Checking scip-query freshness"}]}:{hooks:[{type:"command",command:`${n} hook-stop`,timeout:30,statusMessage:"Running scip-query diff gate"}]}}function Wg(e){let t=Jt(e,"node_modules",".bin","scip-query");return ct(t)?t:"scip-query"}async function cl(){let e=await zg(Ht());e&&console.log(JSON.stringify(e))}function Gg(e){if(Nn(e))return;let t=dl(e),n=ul(t);if(!(!n||!ct(n.paths.dbPath)))return rh(n,r=>{let i={minTogether:6,skip:[]},o=St(r,i),s=Hn(r,o,{replayGate:a=>St(r,{...i,base:a})});return s.warning&&console.error(`note: ${s.warning}`),o})}function ll(){let e=Gg(Ht());!e||e.findings.length===0||console.log(JSON.stringify(Ug(e,Mg())))}function Ug(e,t="feedback"){let n=Wt(e),r=Jg(e);return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${r}
34
34
 
35
35
  This is non-error Stop hook feedback. Fix true findings, or explain why a finding is intentionally accepted before finishing.`}}:{systemMessage:`${r}
36
36
 
37
- Stop hook allowed this turn to finish. Review these findings when relevant. Set ${oi}=feedback to ask the agent to continue without a hook error, or ${oi}=block to enforce the gate.`}}function Ug(e){return Wt(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}async function Jg(e){let t=ll(e),n=th(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit")return;let r=dl(t);if(!r)return;let i=await Kg(r,n),o=n==="SessionStart"?Yg(r.projectRoot,r.config,r.paths):Xg(String(t.prompt??""),r.config),s=[i,o].filter(a=>!!a?.trim()).join(`
38
- `);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}var zg={prepare:rc,ensureService:Ko,freshness:Oe,requestRefresh:Yo,startOneShot(e){Pg("scip-query",["reindex","--allow-partial"],{cwd:e,detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_AUTO_INSTALL:"1"}}).unref()}};async function Kg(e,t,n=zg){let r=Pe(e.config);if(r.autoRefresh===!1)return;n.prepare?.(e.projectRoot,e.config,e.paths);let i=n.freshness(e.projectRoot,e.config,e.paths);if(r.enabled){let o=n.ensureService({commandName:`agent-${t}`,projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:Ne,config:e.config});return o.kind==="failed"?`scip-query watch service did not start: ${o.message}. Run 'scip-query watch --daemon' to repair it.`:o.kind==="skipped"?i.state==="fresh"?void 0:`scip-query index is ${i.state}; automatic watch service wake was skipped (${o.reason}).`:(Qg(o,i.state,e.paths.cacheDir,n),i.state!=="fresh"?`scip-query index is ${i.state}; ${o.kind==="started"?"started":"woke"} the watch service and requested refresh.`:o.kind==="started"?"scip-query watch service started for this project.":void 0)}if(i.state!=="fresh"){if(t==="UserPromptSubmit")return`scip-query index is ${i.state}; evidence commands will note staleness. Run 'scip-query reindex' to refresh.`;try{return n.startOneShot(e.projectRoot),`scip-query index is ${i.state}; started background refresh with auto-install disabled.`}catch(o){let s=o instanceof Error?o.message:String(o);return`scip-query auto-refresh skipped: index is ${i.state}, but background refresh failed to start: ${s}`}}}function Qg(e,t,n,r){t==="fresh"||e.kind==="started"||e.state.watcher.state!=="idle"||r.requestRefresh(kn(n).activityPath,`agent hook observed ${t} index while service was idle`)}function Yg(e,t,n){let r=Oe(e,t,n),i=he(e,t),s=Je(i).capabilities.filter(c=>c.status!=="available").map(c=>c.label),a=i.languages.length>0?i.languages.join(", "):"none detected";return[`scip-query is available in this repository. Index state: ${r.state} (${r.reason})`,r.lastRefresh?`Last refresh: ${r.lastRefresh.result} by ${r.lastRefresh.trigger.kind} at ${r.lastRefresh.completedAt}.`:void 0,`Detected languages: ${a}.`,s.length>0?`Unavailable or partial capabilities: ${s.join(", ")}.`:"Core capabilities are available.","Use the scip-query router skill when exploring, planning, verifying, debugging, diagramming, or cleaning up code.","For non-trivial edits, plan with scip-concrete-plan anchored by `scip-query plan-context <target>`, then verify with scip-verify."].filter(c=>c!==void 0).join(`
39
- `)}function Xg(e,t={},n=process.env){if(eh(t,n)==="off")return"";let r=Zg(e);return r?`scip-query routing reminder:
40
- ${r.message}`:""}var el=[{id:"setup",skillNames:["scip-setup"],keywords:["setup","adopt","install","bootstrap"],message:"Setup request: use scip-setup; keep CI setup out of the default path."},{id:"debug",skillNames:["scip-debug","scip-triage-issue"],keywords:["debug","bug","regression","failing","fails","error","wrong"],message:"Debug or bug request: use scip-debug. For issue-quality triage, use scip-triage-issue."},{id:"review",skillNames:["scip-maintainability","scip-api-impact","scip-verify"],keywords:["review","maintainability","architecture","boundary"],message:"Review request: use scip-maintainability, scip-api-impact, or scip-verify depending on whether this is architecture, API impact, or post-change verification."},{id:"implementation",skillNames:["scip-concrete-plan","scip-verify"],keywords:["implement","build","change","refactor","fix","add","update"],message:"Implementation request: plan first with scip-concrete-plan and `scip-query plan-context <target>`, then verify with scip-verify."},{id:"exploration",skillNames:["scip-explore"],keywords:["explain","how does","walk me through","trace","understand"],message:"Exploration request: use scip-explore before answering behavioral questions."},{id:"diagram",skillNames:["scip-diagram"],keywords:["diagram","visualize","visualise","flow map","architecture map"],message:"Diagram request: use scip-diagram and back every node and edge with scip-query evidence."},{id:"health",skillNames:["scip-cleanup-audit","scip-cleanup-improve"],keywords:["health","score","dossier","cleanup","dead code","duplicate","debloat","as high as","maximize","maximise"],message:"Health or cleanup request: use scip-cleanup-audit before editing; use scip-cleanup-improve when the user wants confirmed issues fixed autonomously."}];function Zg(e){let t=el.find(i=>i.skillNames.some(o=>tl(e,o)));if(t)return t;let n=0,r=[];for(let i of el){let o=i.keywords.filter(s=>tl(e,s)).length;n+=o,o>0&&r.push(i)}return n<2||r.length===0?null:r[0]}function eh(e,t){return t.SCIP_QUERY_ROUTER==="off"?"off":e.hooks?.router??"single"}function tl(e,t){let n=t.trim().split(/\s+/).map(r=>Le(r)).join("\\s+");return new RegExp(`(?<![A-Za-z0-9_-])${n}(?![A-Za-z0-9_-])`,"i").test(e)}function ll(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function th(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function dl(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=Wo(t);if(n)try{let r=fe(n),i=De(n,r);return{projectRoot:n,config:r,paths:i}}catch{return}}function nh(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,sharedEvidenceDbPath:ec(e.projectRoot,e.config),entryRoots:e.config.entryRoots,semantic:e.config.semantic,suppressions:e.config.suppressions,declaredCouplings:e.config.declaredCouplings,locality:e.config.locality,coverageContracts:e.config.coverageContracts,docs:e.config.docs},r=new Ae(n,vt(e.projectRoot));try{return t(r)}finally{r.close()}}import{existsSync as Jn,mkdirSync as ch,symlinkSync as lh,readlinkSync as pi,unlinkSync as mi,readdirSync as hl}from"fs";import{join as Te,dirname as Qt,resolve as ze,relative as dh,isAbsolute as uh}from"path";import{homedir as zn,platform as ph}from"os";import{fileURLToPath as yl}from"url";import{execFileSync as ul}from"child_process";import{createRequire as rh}from"module";import{existsSync as ih}from"fs";import{platform as zt,arch as pl}from"os";var ml="v0.8.1",di="https://github.com/sourcegraph/scip",fl="SCIP_QUERY_SCIP_BIN";function oh(e){if(e.isOnPath("scip"))return{source:"path",path:"scip"};let t=e.env[fl];if(t&&e.fileExists(t))return{source:"env",path:t};if(e.platform==="win32"){let n=e.resolveSidecar(e.arch);if(n&&e.fileExists(n))return{source:"sidecar",path:n}}return null}function sh(e){let t=rh(import.meta.url);for(let n of e==="arm64"?["arm64","x64"]:[e])try{return t.resolve(`scip-query-scip-windows/scip-win32-${n}.exe`)}catch{}return null}function Un(e=process.env){return oh({platform:zt(),arch:pl(),env:e,isOnPath:gt,fileExists:ih,resolveSidecar:sh})?.path??null}function Kt(){return Un()!==null}function ah(){let e=zt(),t=pl(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let o=`scip-${n}-${r}.${i}`;return{url:`${di}/releases/download/${ml}/${o}`,filename:o}}function ui(){let e=ah();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),zt()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
41
- `),console.log("Or download manually:")):zt()==="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 ${fl} to a local scip.exe path.
37
+ Stop hook allowed this turn to finish. Review these findings when relevant. Set ${oi}=feedback to ask the agent to continue without a hook error, or ${oi}=block to enforce the gate.`}}function Jg(e){return Wt(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}async function zg(e){let t=dl(e),n=nh(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit")return;let r=ul(t);if(!r)return;let i=await Qg(r,n),o=n==="SessionStart"?Xg(r.projectRoot,r.config,r.paths):Zg(String(t.prompt??""),r.config),s=[i,o].filter(a=>!!a?.trim()).join(`
38
+ `);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}var Kg={prepare:ic,ensureService:Qo,freshness:Oe,requestRefresh:Xo,startOneShot(e){Cg("scip-query",["reindex","--allow-partial"],{cwd:e,detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_AUTO_INSTALL:"1"}}).unref()}};async function Qg(e,t,n=Kg){let r=Pe(e.config);if(r.autoRefresh===!1)return;n.prepare?.(e.projectRoot,e.config,e.paths);let i=n.freshness(e.projectRoot,e.config,e.paths);if(r.enabled){let o=n.ensureService({commandName:`agent-${t}`,projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:Ne,config:e.config});return o.kind==="failed"?`scip-query watch service did not start: ${o.message}. Run 'scip-query watch --daemon' to repair it.`:o.kind==="skipped"?i.state==="fresh"?void 0:`scip-query index is ${i.state}; automatic watch service wake was skipped (${o.reason}).`:(Yg(o,i.state,e.paths.cacheDir,n),i.state!=="fresh"?`scip-query index is ${i.state}; ${o.kind==="started"?"started":"woke"} the watch service and requested refresh.`:o.kind==="started"?"scip-query watch service started for this project.":void 0)}if(i.state!=="fresh"){if(t==="UserPromptSubmit")return`scip-query index is ${i.state}; evidence commands will note staleness. Run 'scip-query reindex' to refresh.`;try{return n.startOneShot(e.projectRoot),`scip-query index is ${i.state}; started background refresh with auto-install disabled.`}catch(o){let s=o instanceof Error?o.message:String(o);return`scip-query auto-refresh skipped: index is ${i.state}, but background refresh failed to start: ${s}`}}}function Yg(e,t,n,r){t==="fresh"||e.kind==="started"||e.state.watcher.state!=="idle"||r.requestRefresh(kn(n).activityPath,`agent hook observed ${t} index while service was idle`)}function Xg(e,t,n){let r=Oe(e,t,n),i=he(e,t),s=Je(i).capabilities.filter(c=>c.status!=="available").map(c=>c.label),a=i.languages.length>0?i.languages.join(", "):"none detected";return[`scip-query is available in this repository. Index state: ${r.state} (${r.reason})`,r.lastRefresh?`Last refresh: ${r.lastRefresh.result} by ${r.lastRefresh.trigger.kind} at ${r.lastRefresh.completedAt}.`:void 0,`Detected languages: ${a}.`,s.length>0?`Unavailable or partial capabilities: ${s.join(", ")}.`:"Core capabilities are available.","Use the scip-query router skill when exploring, planning, verifying, debugging, diagramming, or cleaning up code.","For non-trivial edits, plan with scip-concrete-plan anchored by `scip-query plan-context <target>`, then verify with scip-verify."].filter(c=>c!==void 0).join(`
39
+ `)}function Zg(e,t={},n=process.env){if(th(t,n)==="off")return"";let r=eh(e);return r?`scip-query routing reminder:
40
+ ${r.message}`:""}var tl=[{id:"setup",skillNames:["scip-setup"],keywords:["setup","adopt","install","bootstrap"],message:"Setup request: use scip-setup; keep CI setup out of the default path."},{id:"debug",skillNames:["scip-debug","scip-triage-issue"],keywords:["debug","bug","regression","failing","fails","error","wrong"],message:"Debug or bug request: use scip-debug. For issue-quality triage, use scip-triage-issue."},{id:"review",skillNames:["scip-maintainability","scip-api-impact","scip-verify"],keywords:["review","maintainability","architecture","boundary"],message:"Review request: use scip-maintainability, scip-api-impact, or scip-verify depending on whether this is architecture, API impact, or post-change verification."},{id:"implementation",skillNames:["scip-concrete-plan","scip-verify"],keywords:["implement","build","change","refactor","fix","add","update"],message:"Implementation request: plan first with scip-concrete-plan and `scip-query plan-context <target>`, then verify with scip-verify."},{id:"exploration",skillNames:["scip-explore"],keywords:["explain","how does","walk me through","trace","understand"],message:"Exploration request: use scip-explore before answering behavioral questions."},{id:"diagram",skillNames:["scip-diagram"],keywords:["diagram","visualize","visualise","flow map","architecture map"],message:"Diagram request: use scip-diagram and back every node and edge with scip-query evidence."},{id:"health",skillNames:["scip-cleanup-audit","scip-cleanup-improve"],keywords:["health","score","dossier","cleanup","dead code","duplicate","debloat","as high as","maximize","maximise"],message:"Health or cleanup request: use scip-cleanup-audit before editing; use scip-cleanup-improve when the user wants confirmed issues fixed autonomously."}];function eh(e){let t=tl.find(i=>i.skillNames.some(o=>nl(e,o)));if(t)return t;let n=0,r=[];for(let i of tl){let o=i.keywords.filter(s=>nl(e,s)).length;n+=o,o>0&&r.push(i)}return n<2||r.length===0?null:r[0]}function th(e,t){return t.SCIP_QUERY_ROUTER==="off"?"off":e.hooks?.router??"single"}function nl(e,t){let n=t.trim().split(/\s+/).map(r=>Le(r)).join("\\s+");return new RegExp(`(?<![A-Za-z0-9_-])${n}(?![A-Za-z0-9_-])`,"i").test(e)}function dl(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function nh(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function ul(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=Go(t);if(n)try{let r=fe(n),i=De(n,r);return{projectRoot:n,config:r,paths:i}}catch{return}}function rh(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,sharedEvidenceDbPath:tc(e.projectRoot,e.config),entryRoots:e.config.entryRoots,semantic:e.config.semantic,suppressions:e.config.suppressions,declaredCouplings:e.config.declaredCouplings,locality:e.config.locality,coverageContracts:e.config.coverageContracts,docs:e.config.docs},r=new Ae(n,vt(e.projectRoot));try{return t(r)}finally{r.close()}}import{existsSync as Jn,mkdirSync as lh,symlinkSync as dh,readlinkSync as pi,unlinkSync as mi,readdirSync as yl}from"fs";import{join as Te,dirname as Qt,resolve as ze,relative as uh,isAbsolute as ph}from"path";import{homedir as zn,platform as mh}from"os";import{fileURLToPath as bl}from"url";import{execFileSync as pl}from"child_process";import{createRequire as ih}from"module";import{existsSync as oh}from"fs";import{platform as zt,arch as ml}from"os";var fl="v0.8.1",di="https://github.com/sourcegraph/scip",gl="SCIP_QUERY_SCIP_BIN";function sh(e){if(e.isOnPath("scip"))return{source:"path",path:"scip"};let t=e.env[gl];if(t&&e.fileExists(t))return{source:"env",path:t};if(e.platform==="win32"){let n=e.resolveSidecar(e.arch);if(n&&e.fileExists(n))return{source:"sidecar",path:n}}return null}function ah(e){let t=ih(import.meta.url);for(let n of e==="arm64"?["arm64","x64"]:[e])try{return t.resolve(`scip-query-scip-windows/scip-win32-${n}.exe`)}catch{}return null}function Un(e=process.env){return sh({platform:zt(),arch:ml(),env:e,isOnPath:gt,fileExists:oh,resolveSidecar:ah})?.path??null}function Kt(){return Un()!==null}function ch(){let e=zt(),t=ml(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let o=`scip-${n}-${r}.${i}`;return{url:`${di}/releases/download/${fl}/${o}`,filename:o}}function ui(){let e=ch();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),zt()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
41
+ `),console.log("Or download manually:")):zt()==="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 ${gl} to a local scip.exe path.
42
42
  `),console.log("Upstream release page:")):console.log("Download from:"),console.log(e?` ${e.url}
43
- `:` ${di}/releases/tag/${ml}
44
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function gl(e){if(zt()==="darwin"&&gt("brew")){e("Installing scip CLI via Homebrew...");try{if(ul("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),gt("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(gt("go")){e("Installing scip CLI via go install...");try{if(ul("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),gt("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: ${di}/releases`),!1}var mh=ph()==="win32",Kn=["_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-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 Qn(e={}){let t=e.quiet?()=>{}:console.log,n=yl(import.meta.url),r=ze(Qt(n),"..","skills"),i=[Te(zn(),".claude","skills"),Te(zn(),".codex","skills"),Te(zn(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of i){let a=Qt(s);if(!Jn(a))continue;ch(s,{recursive:!0});let c=vl(s);fh(s,r,c,o,t);for(let l of Kn){let d=Te(r,l),u=Te(s,l);if(!Jn(d)){o.skipped.push(`${c}/${l}`);continue}if(Jn(u)){try{let m=pi(u);if(ze(m)===ze(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}mi(u)}lh(d,u,mh?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function fh(e,t,n,r,i){let o=new Set(Kn);for(let s of hl(e)){if(o.has(s))continue;let a=Te(e,s),c;try{c=ze(Qt(a),pi(a))}catch{continue}Sl(c,t)&&(mi(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function bl(e={}){let t=yl(import.meta.url),n=ze(Qt(t),"..","skills"),r=e.homeDir??zn(),i=[Te(r,".claude","skills"),Te(r,".codex","skills"),Te(r,".agents","skills")],o={removed:[],left:[],skipped:[]};for(let s of i){if(!Jn(s))continue;let a=vl(s);for(let c of hl(s)){let l=Te(s,c),d;try{let u=pi(l);d=ze(Qt(l),u)}catch{o.left.push(`${a}/${c} (not a symlink)`);continue}if(!Sl(d,n)){o.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(o.removed.push(`${a}/${c}`),!e.dryRun)try{mi(l)}catch(u){o.skipped.push(`${a}/${c} (${u instanceof Error?u.message:String(u)})`)}}}return o}function Sl(e,t){let n=dh(ze(t),ze(e));return n===""||!n.startsWith("..")&&!uh(n)}function vl(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as qu}from"child_process";import{performance as Xe}from"perf_hooks";import{existsSync as ke,readFileSync as Ex,renameSync as jx,rmSync as Lx,unlinkSync as Ax,writeFileSync as Dx}from"fs";import{dirname as br,extname as Ox,join as ut,resolve as Nx}from"path";import{execFileSync as fS}from"child_process";import{createHash as gS}from"crypto";import{closeSync as hS,copyFileSync as cr,existsSync as Re,mkdirSync as ar,mkdtempSync as yS,openSync as bS,readdirSync as SS,readFileSync as lr,renameSync as Gd,rmSync as Ye,statSync as vS,writeFileSync as xS}from"fs";import{basename as sr,dirname as V,extname as RS,join as ne,resolve as Md}from"path";import{platform as kS}from"os";import gh from"better-sqlite3";import{execFileSync as hh}from"child_process";import{existsSync as yh,readdirSync as bh,readFileSync as Sh}from"fs";import{extname as Yn,join as xl}from"path";function lt(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Xn({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Xn(e){let t=new Set((e.extensions??Io).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!yh(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=vt(e.projectRoot),r=vh(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new gh(e.dbPath);try{let o=Rh(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
45
- VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let u=0;for(let m of d){if(o.has(m))continue;let f=Sh(xl(e.projectRoot,m),"utf-8"),g=s.run(kh(m),m,f);u+=Number(g.changes)}return u})(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 vh(e,t){let n=xh(e,t);if(n)return n;let r=[],i=o=>{let s=o?xl(e,o):e,a;try{a=bh(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Eo.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(Yn(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function xh(e,t){try{return hh("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
46
- `).filter(r=>r&&t.has(Yn(r).toLowerCase())).sort()}catch{return null}}function Rh(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 kh(e){return Yn(e).toLowerCase()===".vue"?"vue":Yn(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as wh}from"crypto";import{appendFileSync as $h,existsSync as Ph,mkdirSync as Ch,readFileSync as Th}from"fs";import{dirname as Pl,join as Rl}from"path";var Ih="<global-symbols>";function Eh(e){let t=[];for(let n of e.all(`
43
+ `:` ${di}/releases/tag/${fl}
44
+ `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function hl(e){if(zt()==="darwin"&&gt("brew")){e("Installing scip CLI via Homebrew...");try{if(pl("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),gt("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(gt("go")){e("Installing scip CLI via go install...");try{if(pl("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),gt("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: ${di}/releases`),!1}var fh=mh()==="win32",Kn=["_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 Qn(e={}){let t=e.quiet?()=>{}:console.log,n=bl(import.meta.url),r=ze(Qt(n),"..","skills"),i=[Te(zn(),".claude","skills"),Te(zn(),".codex","skills"),Te(zn(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of i){let a=Qt(s);if(!Jn(a))continue;lh(s,{recursive:!0});let c=xl(s);gh(s,r,c,o,t);for(let l of Kn){let d=Te(r,l),u=Te(s,l);if(!Jn(d)){o.skipped.push(`${c}/${l}`);continue}if(Jn(u)){try{let m=pi(u);if(ze(m)===ze(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}mi(u)}dh(d,u,fh?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function gh(e,t,n,r,i){let o=new Set(Kn);for(let s of yl(e)){if(o.has(s))continue;let a=Te(e,s),c;try{c=ze(Qt(a),pi(a))}catch{continue}vl(c,t)&&(mi(a),r.pruned.push(`${n}/${s}`),i(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function Sl(e={}){let t=bl(import.meta.url),n=ze(Qt(t),"..","skills"),r=e.homeDir??zn(),i=[Te(r,".claude","skills"),Te(r,".codex","skills"),Te(r,".agents","skills")],o={removed:[],left:[],skipped:[]};for(let s of i){if(!Jn(s))continue;let a=xl(s);for(let c of yl(s)){let l=Te(s,c),d;try{let u=pi(l);d=ze(Qt(l),u)}catch{o.left.push(`${a}/${c} (not a symlink)`);continue}if(!vl(d,n)){o.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(o.removed.push(`${a}/${c}`),!e.dryRun)try{mi(l)}catch(u){o.skipped.push(`${a}/${c} (${u instanceof Error?u.message:String(u)})`)}}}return o}function vl(e,t){let n=uh(ze(t),ze(e));return n===""||!n.startsWith("..")&&!ph(n)}function xl(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as Bu}from"child_process";import{performance as Xe}from"perf_hooks";import{existsSync as ke,readFileSync as jx,renameSync as Lx,rmSync as Ax,unlinkSync as Dx,writeFileSync as Ox}from"fs";import{dirname as br,extname as Nx,join as ut,resolve as Fx}from"path";import{execFileSync as gS}from"child_process";import{createHash as hS}from"crypto";import{closeSync as yS,copyFileSync as cr,existsSync as Re,mkdirSync as ar,mkdtempSync as bS,openSync as SS,readdirSync as vS,readFileSync as lr,renameSync as Ud,rmSync as Ye,statSync as xS,writeFileSync as RS}from"fs";import{basename as sr,dirname as V,extname as kS,join as ne,resolve as _d}from"path";import{platform as wS}from"os";import hh from"better-sqlite3";import{execFileSync as yh}from"child_process";import{existsSync as bh,readdirSync as Sh,readFileSync as vh}from"fs";import{extname as Yn,join as Rl}from"path";function lt(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Xn({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Xn(e){let t=new Set((e.extensions??Io).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!bh(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=vt(e.projectRoot),r=xh(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new hh(e.dbPath);try{let o=kh(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
45
+ VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let u=0;for(let m of d){if(o.has(m))continue;let f=vh(Rl(e.projectRoot,m),"utf-8"),g=s.run(wh(m),m,f);u+=Number(g.changes)}return u})(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 xh(e,t){let n=Rh(e,t);if(n)return n;let r=[],i=o=>{let s=o?Rl(e,o):e,a;try{a=Sh(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Eo.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(Yn(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function Rh(e,t){try{return yh("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
46
+ `).filter(r=>r&&t.has(Yn(r).toLowerCase())).sort()}catch{return null}}function kh(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 wh(e){return Yn(e).toLowerCase()===".vue"?"vue":Yn(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as $h}from"crypto";import{appendFileSync as Ph,existsSync as Ch,mkdirSync as Th,readFileSync as Ih}from"fs";import{dirname as Cl,join as kl}from"path";var Eh="<global-symbols>";function jh(e){let t=[];for(let n of e.all(`
47
47
  SELECT relative_path, language, position_encoding, text
48
48
  FROM documents
49
49
  `))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
@@ -99,9 +99,9 @@ ${r.message}`:""}var el=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
99
99
  ) AND NOT EXISTS (
100
100
  SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
101
101
  )
102
- `))t.push({relativePath:Ih,kind:"global-symbol",values:fi(n)});return jh(t)}function jh(e){let t=new Map;for(let r of e){let i=JSON.stringify([r.kind,r.values]),o=t.get(r.relativePath)??[];o.push(i),t.set(r.relativePath,o)}let n=new Map;for(let[r,i]of[...t].sort(([o],[s])=>o.localeCompare(s))){let o=wh("sha256");for(let s of i.sort())o.update(String(Buffer.byteLength(s))),o.update(":"),o.update(s),o.update(`
103
- `);n.set(r,o.digest("hex"))}return n}function Lh(e,t){let n=[],r=[],i=[],o=[],s=new Set([...e.keys(),...t.keys()]);for(let a of[...s].sort()){let c=e.get(a),l=t.get(a);c===void 0?n.push(a):l===void 0?i.push(a):c!==l?r.push(a):o.push(a)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function gi(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),s=e.affectedFiles.filter(c=>!i.has(c)).sort(),a=t.changedFiles.length-o.length;return{passed:o.length===0,recall:t.changedFiles.length===0?1:a/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:o,extraFiles:s}}function hi(e,t=Ah){let n=t.now();if(!t.databaseExists(e.previousDbPath))return Zn(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return Zn(e.refreshResult,"candidate-index-unavailable",n,t.now());let r=null,i=null;try{r=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),i=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let o=[...new Set([...t.indexedPaths(r),...t.indexedPaths(i)])].sort(),s=Pn(e.previousSnapshot,e.currentSnapshot),a=new Set(o),c=s.changes.length>0&&!os(s).fullProject&&s.changes.every(m=>a.has(m.path)),l=Cn(s,c?t.dependencyGraph(r):new Map,o),d=Lh(t.factDigests(r),t.factDigests(i)),u=t.now();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(u).toISOString(),durationMs:Math.max(0,u-n),manifest:s,plan:l,comparison:d,evaluation:gi(l,d,o.length)}}catch(o){return Zn(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{kl(r),kl(i)}}function Cl(e,t,n,r=Date.now()){return Zn(e,t,r,r,n)}function Tl(e){let t=Pl(e);return{latestPath:Rl(t,"affected-shadow-latest.json"),historyPath:Rl(t,"affected-shadow.jsonl")}}function Il(e,t=n=>Th(n,"utf-8")){let n=Tl(e),r;try{r=JSON.parse(t(n.latestPath))}catch(S){let x=Mh(S),k=x?"telemetry-missing":Fh(S);return Ke(n,k,x?void 0:S instanceof Error?S.message:String(S))}if(q(r)&&typeof r.version=="number"&&r.version!==1)return Ke(n,"unsupported-record-version",`Unsupported version ${r.version}.`);if(!Oh(r))return Ke(n,"telemetry-malformed");if(r.status==="unavailable")return Nh(r.reason)?{state:"unavailable",...n,reason:r.reason,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,...typeof r.error=="string"?{error:r.error}:{}}:Ke(n,"telemetry-malformed");if(r.status!=="evaluated")return Ke(n,"telemetry-malformed");let i=r.plan,o=r.comparison,s=r.evaluation;if(!q(r.manifest)||!q(i)||!q(o)||!q(s))return Ke(n,"telemetry-malformed");let a=i.mode,c=J(i.affectedFiles),l=J(i.reasons),d=J(o.changedFiles),u=J(s.predictedFiles),m=J(s.actualFiles),f=J(s.missingFiles),g=s.recall,h=s.affectedRatio;if(a!=="none"&&a!=="closure"&&a!=="full-project"||c===null||l===null||d===null||u===null||m===null||f===null||typeof s.passed!="boolean"||!wl(g)||!wl(h))return Ke(n,"telemetry-malformed");let y=m.length===0?1:(m.length-f.length)/m.length;return!$l(c,u)||!$l(d,m)||s.passed!==(f.length===0)||Math.abs(g-y)>Number.EPSILON||f.some(S=>!m.includes(S)||u.includes(S))?Ke(n,"telemetry-malformed"):{state:s.passed?"passing":"failing",...n,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,mode:a,recall:g,affectedRatio:h,predictedFiles:u,actualFiles:m,missingFiles:f,fallbackReasons:l}}function El(e){if(e.state==="unavailable")return`unavailable (${e.reason})`;let t=e.missingFiles.length>0?`, ${e.missingFiles.length} missed`:"",n=e.fallbackReasons.length>0?`; fallback: ${e.fallbackReasons.join(", ")}`:"";return`${e.state}, ${(e.recall*100).toFixed(1)}% recall, ${e.predictedFiles.length} predicted / ${e.actualFiles.length} changed, ${(e.affectedRatio*100).toFixed(1)}% of project${t}${n}`}function jl(e,t,n=Dh){let r=Tl(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}function fi(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var Ah={now:()=>Date.now(),databaseExists:e=>Ph(e),openDatabase:(e,t,n)=>new Ae({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>pn(e),dependencyGraph:e=>gn(e),factDigests:e=>Eh(e)},Dh={appendHistory:(e,t)=>{Ch(Pl(e),{recursive:!0}),$h(e,`${JSON.stringify(t)}
104
- `)},writeLatest:(e,t)=>yt(e,t,{spacing:2,trailingNewline:!0})};function Zn(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(r).toISOString(),durationMs:Math.max(0,r-n),reason:t,...i?{error:i}:{}}}function kl(e){try{e?.close()}catch{}}function Oh(e){return q(e)&&e.version===1&&typeof e.recordedAt=="string"&&(e.refreshResult==="rebuilt"||e.refreshResult==="reused")&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0}function Nh(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="oracle-error"}function wl(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function $l(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Ke(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function Fh(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function Mh(e){return e instanceof Error&&e.code==="ENOENT"}import{createHash as _h}from"crypto";import{copyFileSync as qh,existsSync as Ll,rmSync as Al}from"fs";import{resolve as Bh}from"path";import Nl from"better-sqlite3";var Vh={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},Hh={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Fl(e){let t=Date.now(),n=Wh(e.affectedFiles);if(Gh(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Al(e.candidateDbPath,{force:!0}),!Ll(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Ll(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");Dl(e.previousDbPath,"previous SQLite generation",!1),Dl(e.miniDbPath,"incremental SQLite mini database"),qh(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new Nl(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),yi(r,"main","candidate SQLite generation"),yi(r,"incremental","incremental SQLite mini database"),Uh(r,n),Jh(r,n.length);let i=bi(r,"main",!0),o=Qe(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{zh(r),Kh(r),Qh(r),e.onStage?.("after-delete"),Yh(r),e.onStage?.("after-symbol-reconciliation"),Xh(r),e.onStage?.("after-insert"),Zh(r),ey(r,n.length,o),e.onStage?.("before-commit")}).immediate(),Ml(r,"main","candidate SQLite generation");let c=[...ty(r)].filter(([l,d])=>i.get(l)!==d).map(([l])=>l).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:Date.now()-t}}catch(i){try{r?.close()}finally{Al(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function Wh(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function Gh(e,t,n){let r=[e,t,n].map(i=>Bh(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Dl(e,t,n=!0){let r=new Nl(e,{readonly:!0,fileMustExist:!0});try{yi(r,"main",t),n&&Ml(r,"main",t)}finally{r.close()}}function yi(e,t,n){for(let[r,i]of Object.entries(Vh)){let s=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:a,type:c,notnull:l,pk:d})=>({name:a,type:c.toUpperCase(),notnull:l,pk:d}));if(JSON.stringify(s)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Hh)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),s=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(a=>a.name);if(o?.tbl_name!==i.table||JSON.stringify(s)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}Ol(e,t,"documents",["relative_path"],n),Ol(e,t,"global_symbols",["symbol"],n)}function Ol(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(a=>{if(a.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${a.name}')`).all().map(l=>l.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function Ml(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function Uh(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let o of i)n.run(o)})(t)}function Jh(e,t){let n=Qe(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=Qe(e,`SELECT COUNT(*) AS value
102
+ `))t.push({relativePath:Eh,kind:"global-symbol",values:fi(n)});return Lh(t)}function Lh(e){let t=new Map;for(let r of e){let i=JSON.stringify([r.kind,r.values]),o=t.get(r.relativePath)??[];o.push(i),t.set(r.relativePath,o)}let n=new Map;for(let[r,i]of[...t].sort(([o],[s])=>o.localeCompare(s))){let o=$h("sha256");for(let s of i.sort())o.update(String(Buffer.byteLength(s))),o.update(":"),o.update(s),o.update(`
103
+ `);n.set(r,o.digest("hex"))}return n}function Ah(e,t){let n=[],r=[],i=[],o=[],s=new Set([...e.keys(),...t.keys()]);for(let a of[...s].sort()){let c=e.get(a),l=t.get(a);c===void 0?n.push(a):l===void 0?i.push(a):c!==l?r.push(a):o.push(a)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function gi(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),s=e.affectedFiles.filter(c=>!i.has(c)).sort(),a=t.changedFiles.length-o.length;return{passed:o.length===0,recall:t.changedFiles.length===0?1:a/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:o,extraFiles:s}}function hi(e,t=Dh){let n=t.now();if(!t.databaseExists(e.previousDbPath))return Zn(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return Zn(e.refreshResult,"candidate-index-unavailable",n,t.now());let r=null,i=null;try{r=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),i=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let o=[...new Set([...t.indexedPaths(r),...t.indexedPaths(i)])].sort(),s=Pn(e.previousSnapshot,e.currentSnapshot),a=new Set(o),c=s.changes.length>0&&!ss(s).fullProject&&s.changes.every(m=>a.has(m.path)),l=Cn(s,c?t.dependencyGraph(r):new Map,o),d=Ah(t.factDigests(r),t.factDigests(i)),u=t.now();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(u).toISOString(),durationMs:Math.max(0,u-n),manifest:s,plan:l,comparison:d,evaluation:gi(l,d,o.length)}}catch(o){return Zn(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{wl(r),wl(i)}}function Tl(e,t,n,r=Date.now()){return Zn(e,t,r,r,n)}function Il(e){let t=Cl(e);return{latestPath:kl(t,"affected-shadow-latest.json"),historyPath:kl(t,"affected-shadow.jsonl")}}function El(e,t=n=>Ih(n,"utf-8")){let n=Il(e),r;try{r=JSON.parse(t(n.latestPath))}catch(S){let x=_h(S),k=x?"telemetry-missing":Mh(S);return Ke(n,k,x?void 0:S instanceof Error?S.message:String(S))}if(q(r)&&typeof r.version=="number"&&r.version!==1)return Ke(n,"unsupported-record-version",`Unsupported version ${r.version}.`);if(!Nh(r))return Ke(n,"telemetry-malformed");if(r.status==="unavailable")return Fh(r.reason)?{state:"unavailable",...n,reason:r.reason,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,...typeof r.error=="string"?{error:r.error}:{}}:Ke(n,"telemetry-malformed");if(r.status!=="evaluated")return Ke(n,"telemetry-malformed");let i=r.plan,o=r.comparison,s=r.evaluation;if(!q(r.manifest)||!q(i)||!q(o)||!q(s))return Ke(n,"telemetry-malformed");let a=i.mode,c=J(i.affectedFiles),l=J(i.reasons),d=J(o.changedFiles),u=J(s.predictedFiles),m=J(s.actualFiles),f=J(s.missingFiles),g=s.recall,h=s.affectedRatio;if(a!=="none"&&a!=="closure"&&a!=="full-project"||c===null||l===null||d===null||u===null||m===null||f===null||typeof s.passed!="boolean"||!$l(g)||!$l(h))return Ke(n,"telemetry-malformed");let y=m.length===0?1:(m.length-f.length)/m.length;return!Pl(c,u)||!Pl(d,m)||s.passed!==(f.length===0)||Math.abs(g-y)>Number.EPSILON||f.some(S=>!m.includes(S)||u.includes(S))?Ke(n,"telemetry-malformed"):{state:s.passed?"passing":"failing",...n,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,mode:a,recall:g,affectedRatio:h,predictedFiles:u,actualFiles:m,missingFiles:f,fallbackReasons:l}}function jl(e){if(e.state==="unavailable")return`unavailable (${e.reason})`;let t=e.missingFiles.length>0?`, ${e.missingFiles.length} missed`:"",n=e.fallbackReasons.length>0?`; fallback: ${e.fallbackReasons.join(", ")}`:"";return`${e.state}, ${(e.recall*100).toFixed(1)}% recall, ${e.predictedFiles.length} predicted / ${e.actualFiles.length} changed, ${(e.affectedRatio*100).toFixed(1)}% of project${t}${n}`}function Ll(e,t,n=Oh){let r=Il(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}function fi(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var Dh={now:()=>Date.now(),databaseExists:e=>Ch(e),openDatabase:(e,t,n)=>new Ae({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>pn(e),dependencyGraph:e=>gn(e),factDigests:e=>jh(e)},Oh={appendHistory:(e,t)=>{Th(Cl(e),{recursive:!0}),Ph(e,`${JSON.stringify(t)}
104
+ `)},writeLatest:(e,t)=>yt(e,t,{spacing:2,trailingNewline:!0})};function Zn(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(r).toISOString(),durationMs:Math.max(0,r-n),reason:t,...i?{error:i}:{}}}function wl(e){try{e?.close()}catch{}}function Nh(e){return q(e)&&e.version===1&&typeof e.recordedAt=="string"&&(e.refreshResult==="rebuilt"||e.refreshResult==="reused")&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0}function Fh(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="oracle-error"}function $l(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function Pl(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Ke(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function Mh(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function _h(e){return e instanceof Error&&e.code==="ENOENT"}import{createHash as qh}from"crypto";import{copyFileSync as Bh,existsSync as Al,rmSync as Dl}from"fs";import{resolve as Vh}from"path";import Fl from"better-sqlite3";var Hh={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},Wh={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Ml(e){let t=Date.now(),n=Gh(e.affectedFiles);if(Uh(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Dl(e.candidateDbPath,{force:!0}),!Al(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Al(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");Ol(e.previousDbPath,"previous SQLite generation",!1),Ol(e.miniDbPath,"incremental SQLite mini database"),Bh(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new Fl(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),yi(r,"main","candidate SQLite generation"),yi(r,"incremental","incremental SQLite mini database"),Jh(r,n),zh(r,n.length);let i=bi(r,"main",!0),o=Qe(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{Kh(r),Qh(r),Yh(r),e.onStage?.("after-delete"),Xh(r),e.onStage?.("after-symbol-reconciliation"),Zh(r),e.onStage?.("after-insert"),ey(r),ty(r,n.length,o),e.onStage?.("before-commit")}).immediate(),_l(r,"main","candidate SQLite generation");let c=[...ny(r)].filter(([l,d])=>i.get(l)!==d).map(([l])=>l).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:Date.now()-t}}catch(i){try{r?.close()}finally{Dl(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function Gh(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function Uh(e,t,n){let r=[e,t,n].map(i=>Vh(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Ol(e,t,n=!0){let r=new Fl(e,{readonly:!0,fileMustExist:!0});try{yi(r,"main",t),n&&_l(r,"main",t)}finally{r.close()}}function yi(e,t,n){for(let[r,i]of Object.entries(Hh)){let s=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:a,type:c,notnull:l,pk:d})=>({name:a,type:c.toUpperCase(),notnull:l,pk:d}));if(JSON.stringify(s)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Wh)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),s=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(a=>a.name);if(o?.tbl_name!==i.table||JSON.stringify(s)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}Nl(e,t,"documents",["relative_path"],n),Nl(e,t,"global_symbols",["symbol"],n)}function Nl(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(a=>{if(a.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${a.name}')`).all().map(l=>l.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function _l(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function Jh(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let o of i)n.run(o)})(t)}function zh(e,t){let n=Qe(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=Qe(e,`SELECT COUNT(*) AS value
105
105
  FROM main.documents d
106
106
  JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
107
107
  FROM temp.incremental_affected_paths p
@@ -111,7 +111,7 @@ ${r.message}`:""}var el=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
111
111
  FROM incremental.documents d
112
112
  LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
113
113
  WHERE p.relative_path IS NULL
114
- LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function zh(e){e.exec(`
114
+ LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function Kh(e){e.exec(`
115
115
  CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
116
116
  INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
117
117
  SELECT g.symbol
@@ -138,7 +138,7 @@ ${r.message}`:""}var el=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
138
138
  FROM incremental.mentions m
139
139
  JOIN incremental.global_symbols g ON g.id = m.symbol_id
140
140
  WHERE m.role = 1;
141
- `)}function Kh(e){let t=e.prepare(`WITH changed_symbols AS (
141
+ `)}function Qh(e){let t=e.prepare(`WITH changed_symbols AS (
142
142
  SELECT symbol FROM temp.incremental_old_defined_symbols
143
143
  UNION
144
144
  SELECT symbol FROM temp.incremental_new_defined_symbols
@@ -161,7 +161,7 @@ ${r.message}`:""}var el=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
161
161
  SELECT u.symbol
162
162
  FROM unaffected_definitions u
163
163
  JOIN changed_symbols c ON c.symbol = u.symbol
164
- LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function Qh(e){e.exec(`
164
+ LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function Yh(e){e.exec(`
165
165
  DELETE FROM main.mentions
166
166
  WHERE chunk_id IN (
167
167
  SELECT c.id
@@ -183,7 +183,7 @@ ${r.message}`:""}var el=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
183
183
  );
184
184
  DELETE FROM main.documents
185
185
  WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
186
- `)}function Yh(e){e.exec(`
186
+ `)}function Xh(e){e.exec(`
187
187
  UPDATE main.global_symbols
188
188
  SET display_name = NULL,
189
189
  kind = NULL,
@@ -225,7 +225,7 @@ ${r.message}`:""}var el=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
225
225
  WHERE source.symbol = main.global_symbols.symbol
226
226
  )
227
227
  WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
228
- `)}function Xh(e){let t=Qe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=Qe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=Qe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
228
+ `)}function Zh(e){let t=Qe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=Qe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=Qe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
229
229
  SELECT id + ?, language, relative_path, position_encoding, text
230
230
  FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
231
231
  SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
@@ -240,15 +240,15 @@ ${r.message}`:""}var el=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
240
240
  r.start_line, r.start_char, r.end_line, r.end_char
241
241
  FROM incremental.defn_enclosing_ranges r
242
242
  JOIN incremental.global_symbols source ON source.id = r.symbol_id
243
- JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function Zh(e){e.exec(`
243
+ JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function ey(e){e.exec(`
244
244
  DELETE FROM main.global_symbols
245
245
  WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
246
246
  AND NOT EXISTS (
247
247
  SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
248
248
  );
249
- `)}function ey(e,t,n){let r=Qe(e,"SELECT COUNT(*) AS value FROM main.documents"),i=Qe(e,`SELECT COUNT(*) AS value
249
+ `)}function ty(e,t,n){let r=Qe(e,"SELECT COUNT(*) AS value FROM main.documents"),i=Qe(e,`SELECT COUNT(*) AS value
250
250
  FROM main.documents d
251
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),s=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||s!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function ty(e){let t=bi(e,"main",!0),n=bi(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function bi(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
251
+ JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),s=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||s!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function ny(e){let t=bi(e,"main",!0),n=bi(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function bi(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
252
252
  FROM ${t}.documents d
253
253
  ${r}
254
254
  ORDER BY d.relative_path`).all(),o=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
@@ -270,11 +270,11 @@ ${r.message}`:""}var el=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
270
270
  JOIN ${t}.documents d ON d.id = c.document_id
271
271
  JOIN ${t}.global_symbols g ON g.id = m.symbol_id
272
272
  ${r}
273
- ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,u]of Object.entries({documents:i,chunks:o,definitions:s,mentions:a}))for(let m of u){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,u]of[...c].sort(([m],[f])=>m.localeCompare(f))){let m=_h("sha256");for(let f of u.sort())m.update(f).update(`
274
- `);l.set(d,m.digest("hex"))}return l}function Qe(e,t){return e.prepare(t).get().value}import{readFileSync as ny,writeFileSync as ry}from"fs";function dt(e,t){let n=Date.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:Date.now()-n,result:r}}function ql(e){let t=e.readFingerprint(),n=iy(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return oy(e.cachePath,e.readFingerprint(),r),r}function iy(e,t){try{let n=JSON.parse(ny(e,"utf-8"));return _l(n.fingerprint)===_l(t)?{result:n.result}:null}catch{return null}}function oy(e,t,n){ry(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
275
- `)}function _l(e){return JSON.stringify(e)}import{createHash as sy}from"crypto";import{existsSync as Si,readFileSync as ay,readdirSync as cy}from"fs";import{dirname as vi,join as er,relative as ly,resolve as xi,sep as Bl}from"path";function Vl(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let s=Ul(o.path,t);s?r[s].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Hl(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=Ul(a,e);c&&c!==i&&s.add(c)}}return dy(e,r)}function Wl(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 Ri(e){if(e===".")return"root";let t=sy("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Gl(e,t){let n=xi(e),r={};for(let i of t)r[i]=uy(n,i);return r}function Ul(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 dy(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 uy(e,t){let n=t==="."?e:er(e,t),r=py(n),i=my(n),o=i?fy(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 py(e){let t=er(e,"package.json");if(!Si(t))return{name:void 0,dependencyNames:[],failed:!1};let n=ki(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 my(e){let t=er(e,"tsconfig.json");if(Si(t))return t;let n;try{n=cy(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?er(e,n[0]):void 0}function fy(e,t){let n=ki(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=gy(n.value,e,t),i=Jl(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function gy(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=vi(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=zl(a,i,n);c&&o.add(c)}return[...o]}function Jl(e,t,n,r){let i=hy(t);if(i)return{pathsTargets:yy(i,vi(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=by(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let s=ki(o);return s.ok?Jl(o,s.value,n,r+1):{pathsTargets:[],failed:!0}}function hy(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 yy(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=zl(o,t,n);s&&r.add(s)}return[...r]}function by(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=xi(vi(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Bl).includes("node_modules")&&me(n,i)&&Si(i))return i}function zl(e,t,n){let r=e.replace(/\/?\*+$/,""),i=xi(t,r===""?".":r);if(!me(n,i))return;let s=ly(n,i).split(Bl).join("/");return s===""?".":s}function Sy(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 ki(e){try{let t=ay(e,"utf-8"),n=JSON.parse(Sy(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{existsSync as vy,readFileSync as xy,readdirSync as Ry,statSync as ky}from"fs";import te from"path";var wy=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Yt(e,t=[]){let n=te.resolve(e),r=t.flatMap(c=>Py(n,c));if(r.length>0)return Kl(n,Ql(r));let i=$y(n),o=Ql(i),s=Ty(n,o)?[n,...o]:o,a=s.length>0?s:[n];return Kl(n,a)}function Kl(e,t){return[...new Set(t.map(n=>Ey(e,n)))].sort((n,r)=>n.localeCompare(r))}function $y(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=Ry(r,{withFileTypes:!0})}catch{continue}for(let o of i){let s=te.join(r,o.name);if(o.isDirectory()){!wy.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&Cy(s)&&t.push(te.dirname(s))}}return t}function Py(e,t){let n=t.trim();if(!n)return[];let r=te.resolve(e,n);if(!me(e,r))return[];try{let i=ky(r);if(i.isDirectory())return[r];if(i.isFile()&&Yl(te.basename(r)))return[te.dirname(r)]}catch{return[]}return[]}function Cy(e){if(!Yl(te.basename(e)))return!1;let t=Xl(e);return t?te.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function Yl(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function Ql(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&&jy(n,r)))}function Ty(e,t){if(t.length===0||t.some(r=>te.resolve(r)===e))return!1;let n=te.join(e,"tsconfig.json");return vy(n)&&Iy(n)}function Iy(e){let n=Xl(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 Xl(e){try{let t=JSON.parse(xy(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Ey(e,t){let n=te.relative(e,t);return n?n.split(te.sep).join("/"):"."}function jy(e,t){let n=te.relative(e,t);return!!n&&!n.startsWith("..")&&!te.isAbsolute(n)}import{createHash as Xy}from"crypto";import{existsSync as $i,readFileSync as ud,statSync as Zy,writeFileSync as Pi}from"fs";import{join as eb}from"path";import{readFileSync as Zl}from"fs";import{createRequire as Ly}from"module";import{dirname as Ay,isAbsolute as AC,relative as DC,resolve as OC,sep as NC}from"path";var ed=Ly(import.meta.url),Dy=1,td="0.4.0";function wi(){let e=Oy();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Oy(){try{let e=ed.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(Zl(e,"utf8"));if(t.version!==td)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${td}`};let n=Ay(e),r=ed.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(Zl(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:Ny(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Ny(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Dy}`}import{createHash as Fy}from"crypto";import{readFileSync as My}from"fs";import{dirname as _y,join as tr}from"path";var nr=2,qy="typescript-index";function nd(e){let t=tr(e,qy);return{rootDir:t,requestDir:tr(t,"requests"),responseDir:tr(t,"responses")}}function rd(e){try{let t=JSON.parse(My(tr(_y(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:Fy("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 By}from"crypto";import{existsSync as Vy,mkdirSync as id,readFileSync as Hy,rmSync as od}from"fs";import{resolve as sd}from"path";var Wy=12e4,Gy=5,rr=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=Uo(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Qy(),this.runtime=n.runtime??Yy}request(t){let n=kn(this.cacheDir),r=nd(this.cacheDir),i=Mr(n.statePath);if(!ad(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),s=sd(r.requestDir,`${o}.json`),a=sd(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;id(r.requestDir,{recursive:!0}),id(r.responseDir,{recursive:!0}),yt(s,{protocolVersion:nr,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(Vy(a))return Uy(Hy(a,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=Mr(n.statePath);if(!ad(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Gy)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{od(s,{force:!0}),od(a,{force:!0})}}};function ad(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Jo,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===nr&&n.isProcessAlive(e.pid)&&(r||i)}function Uy(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==nr||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=Jy(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 Jy(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(zy)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let s=o.bytesBase64===null?null:Ky(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 zy(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 Ky(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Qy(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Wy}var Yy={now:Date.now,randomId:By,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ht};function tb(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=Pn(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"||!_t(l.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=Cn(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=nb([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=cd(e.currentSnapshot,e.projectFiles,e.producerIdentity),s=cd(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==s)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let a=dd(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!a)return{eligible:!1,reason:"prior document identity unavailable"};let c=dd(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:ld(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:ld(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 nb(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 pd(e){let t=Date.now();try{if(!$i(e.previousDbPath)||!$i(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=wi();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new Ae({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),s,a;try{s=pn(o,{includeIgnored:!1}).filter(_t).sort(),a=gn(o)}finally{o.close()}let c=performance.now()-n,l=tb({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?Yt(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:s,graph:a,producerIdentity:r.producerIdentity,rootTsconfigExists:$i(eb(e.projectRoot,"tsconfig.json"))});if(!l.eligible)throw new Error(l.reason);let d=rd(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let m=new rr({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=Zy(e.previousShardPath).size>=Ua;n=performance.now();let h=g?null:ud(e.previousShardPath),y=g?{completeIndexBytes:null,affectedIndexBytes:Va(m.fragments)}:Ga({packageVersion:r.packageVersion,baseIndexBytes:h,fragments:m.fragments}),S=performance.now()-n;n=performance.now(),g?Ja({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,nextGenerationIdentity:l.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:m.fragments}):(Ha({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:h,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.previousFragmentGeneration,documentIdentities:l.previousDocumentIdentities,allowUntrackedDocuments:!0}),Wa({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&&Pi(e.candidateShardPath,y.completeIndexBytes),Pi(e.candidateAffectedScipPath,y.affectedIndexBytes);let k=performance.now()-n,R={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:Date.now()-t,cold:m.cold,changedFiles:l.plan.changedFiles,affectedFiles:l.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:l.previousFragmentGeneration,nextFragmentGeneration:l.nextFragmentGeneration,manifest:l.manifest,plan:l.plan,projectFileCount:s.length,referenceFragmentsByFile:new Map(m.fragments.map(D=>[D.relativePath,D.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:f,serviceMs:m.durationMs,assemblyMs:S,fragmentStoreMs:x,writeMs:k}};return e.onStatus(`Incremental TypeScript index emitted ${R.affectedFiles.length} affected document(s) in ${(R.durationMs/1e3).toFixed(3)}s (${R.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${f.toFixed(0)}ms, assembly ${S.toFixed(0)}ms, fragments ${x.toFixed(0)}ms, write ${k.toFixed(0)}ms).`),R}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function md(e){let t=wi();if(!t.available)throw new Error(t.reason);let n=za({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:ud(e.baseShardPath),packageVersion:t.packageVersion});Pi(e.candidateShardPath,n)}function cd(e,t,n){let r=e.files.filter(i=>Bo(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 Ci(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function ld(e,t){return Ci(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function dd(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,Ci(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return a}function Ci(e){return Xy("sha256").update(e).digest("hex")}import{execFile as rb}from"child_process";import{existsSync as ir,renameSync as Ii,rmSync as Ei,statSync as ib}from"fs";import{cpus as ob}from"os";import{join as fd}from"path";function sb(e,t,n){if(!e.defaultOutputPath)return;let r=fd(t,e.defaultOutputPath);n!==r&&ir(r)&&Ii(r,n)}function ab(e,t,n){if(!e.defaultOutputPath)return null;let r=fd(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Ei(i,{force:!0}),ir(r)?(Ii(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function cb(e){e&&(Ei(e.defaultOutputPath,{force:!0}),e.backupPath&&ir(e.backupPath)&&Ii(e.backupPath,e.defaultOutputPath))}function lb(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,ob().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function gd(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=lb(o.length,r),c=await ub(o,a,l=>Ti(l,t,n));if(a>1){let l=new Map;for(let d of c.filter(u=>u.skipped)){let u=o.find(m=>m.id===d.id);u&&(n(`Retrying ${u.label} indexer serially after parallel failure...`),l.set(u.id,await Ti(u,t,n)))}s.push(...c.map(d=>l.get(d.id)??d))}else s.push(...c);for(let l of i)s.push(await Ti(l,t,n));return s.sort((l,d)=>e.findIndex(u=>u.id===l.id)-e.findIndex(u=>u.id===d.id))}async function Ti(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Ei(e.scipPath,{force:!0});let r=ab(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{await db(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),sb(e.config,t,e.scipPath)}catch(a){let c=a instanceof Error?a.message:String(a),l=`${e.resolvedBinary} indexer failed: ${c.split(`
277
- `)[0]}`,d=e.label===e.language?l:`${e.label}: ${l}`;return n(`Skipping ${e.label}: ${l}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:d}}}finally{cb(r)}if(!ir(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=ib(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 db(e,t,n){return new Promise((r,i)=>{rb(e,[...t],n,o=>{o?i(o):r()})})}async function ub(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 Ub from"better-sqlite3";import{existsSync as Jb}from"fs";import{dirname as zb,join as Kb,resolve as Qb}from"path";import{readFileSync as mb,rmSync as fb,statSync as gb,mkdtempSync as hb}from"fs";import{tmpdir as yb}from"os";import{join as ji}from"path";import{Worker as bb}from"worker_threads";function pb(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function It(){return{skippedReferences:0,skippedReferenceReasons:pb(),skippedReferenceSamples:[]}}function or(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 hd(e){return e.length>=8&&bd(e.length)>1}function yd(e){let t=bd(e.vueFiles.length),n=vb(e.vueFiles),r=Rb(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=hb(ji(yb(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=Sb(),l=Date.now();try{for(let m=0;m<r.length;m++)new bb(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[m],resultPath:ji(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(mb(ji(o,`${f}.json`),"utf-8"));if(!g.ok)throw new Error(`Vue reference worker failed: ${g.error}`);return g.result}),u={occurrences:d.flatMap(m=>m.occurrences),...It()};for(let m of d)or(u,m);return u}finally{fb(o,{recursive:!0,force:!0})}}function bd(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 Sb(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function vb(e){let t=xb(),n=[];for(let r of e){let i=Sd(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 xb(){return Number.POSITIVE_INFINITY}function Rb(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:kb(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 kb(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Sd(e.fileName)-e.startOffset)}function Sd(e){try{return gb(e).size}catch{return 1}}import{createRequire as wb}from"module";import{existsSync as $b,readFileSync as Ai}from"fs";import{dirname as vd,extname as Pb,join as xd,relative as Cb,resolve as Tb}from"path";import{pathToFileURL as Ib}from"url";function Eb(e){e.transaction(()=>{e.prepare(`
273
+ ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,u]of Object.entries({documents:i,chunks:o,definitions:s,mentions:a}))for(let m of u){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,u]of[...c].sort(([m],[f])=>m.localeCompare(f))){let m=qh("sha256");for(let f of u.sort())m.update(f).update(`
274
+ `);l.set(d,m.digest("hex"))}return l}function Qe(e,t){return e.prepare(t).get().value}import{readFileSync as ry,writeFileSync as iy}from"fs";function dt(e,t){let n=Date.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:Date.now()-n,result:r}}function Bl(e){let t=e.readFingerprint(),n=oy(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return sy(e.cachePath,e.readFingerprint(),r),r}function oy(e,t){try{let n=JSON.parse(ry(e,"utf-8"));return ql(n.fingerprint)===ql(t)?{result:n.result}:null}catch{return null}}function sy(e,t,n){iy(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
275
+ `)}function ql(e){return JSON.stringify(e)}import{createHash as ay}from"crypto";import{existsSync as Si,readFileSync as cy,readdirSync as ly}from"fs";import{dirname as vi,join as er,relative as dy,resolve as xi,sep as Vl}from"path";function Hl(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let s=Jl(o.path,t);s?r[s].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Wl(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=Jl(a,e);c&&c!==i&&s.add(c)}}return uy(e,r)}function Gl(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 Ri(e){if(e===".")return"root";let t=ay("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Ul(e,t){let n=xi(e),r={};for(let i of t)r[i]=py(n,i);return r}function Jl(e,t){let n;for(let r of t)r!=="."&&(e===r||e.startsWith(`${r}/`))&&(!n||r.length>n.length)&&(n=r);return n}function uy(e,t){let n={};for(let r of e){let i=new Set,o=[...t.get(r)??[]];for(;o.length>0;){let s=o.pop();if(!(s===r||i.has(s))){i.add(s);for(let a of t.get(s)??[])a!==r&&!i.has(a)&&o.push(a)}}n[r]=[...i].sort((s,a)=>s.localeCompare(a))}return n}function py(e,t){let n=t==="."?e:er(e,t),r=my(n),i=fy(n),o=i?gy(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 my(e){let t=er(e,"package.json");if(!Si(t))return{name:void 0,dependencyNames:[],failed:!1};let n=ki(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 fy(e){let t=er(e,"tsconfig.json");if(Si(t))return t;let n;try{n=ly(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?er(e,n[0]):void 0}function gy(e,t){let n=ki(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=hy(n.value,e,t),i=zl(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function hy(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=vi(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=Kl(a,i,n);c&&o.add(c)}return[...o]}function zl(e,t,n,r){let i=yy(t);if(i)return{pathsTargets:by(i,vi(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Sy(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let s=ki(o);return s.ok?zl(o,s.value,n,r+1):{pathsTargets:[],failed:!0}}function yy(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 by(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=Kl(o,t,n);s&&r.add(s)}return[...r]}function Sy(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=xi(vi(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Vl).includes("node_modules")&&me(n,i)&&Si(i))return i}function Kl(e,t,n){let r=e.replace(/\/?\*+$/,""),i=xi(t,r===""?".":r);if(!me(n,i))return;let s=dy(n,i).split(Vl).join("/");return s===""?".":s}function vy(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 ki(e){try{let t=cy(e,"utf-8"),n=JSON.parse(vy(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{existsSync as xy,readFileSync as Ry,readdirSync as ky,statSync as wy}from"fs";import te from"path";var $y=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Yt(e,t=[]){let n=te.resolve(e),r=t.flatMap(c=>Cy(n,c));if(r.length>0)return Ql(n,Yl(r));let i=Py(n),o=Yl(i),s=Iy(n,o)?[n,...o]:o,a=s.length>0?s:[n];return Ql(n,a)}function Ql(e,t){return[...new Set(t.map(n=>jy(e,n)))].sort((n,r)=>n.localeCompare(r))}function Py(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=ky(r,{withFileTypes:!0})}catch{continue}for(let o of i){let s=te.join(r,o.name);if(o.isDirectory()){!$y.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&Ty(s)&&t.push(te.dirname(s))}}return t}function Cy(e,t){let n=t.trim();if(!n)return[];let r=te.resolve(e,n);if(!me(e,r))return[];try{let i=wy(r);if(i.isDirectory())return[r];if(i.isFile()&&Xl(te.basename(r)))return[te.dirname(r)]}catch{return[]}return[]}function Ty(e){if(!Xl(te.basename(e)))return!1;let t=Zl(e);return t?te.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function Xl(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function Yl(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&&Ly(n,r)))}function Iy(e,t){if(t.length===0||t.some(r=>te.resolve(r)===e))return!1;let n=te.join(e,"tsconfig.json");return xy(n)&&Ey(n)}function Ey(e){let n=Zl(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 Zl(e){try{let t=JSON.parse(Ry(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function jy(e,t){let n=te.relative(e,t);return n?n.split(te.sep).join("/"):"."}function Ly(e,t){let n=te.relative(e,t);return!!n&&!n.startsWith("..")&&!te.isAbsolute(n)}import{createHash as Zy}from"crypto";import{existsSync as $i,readFileSync as pd,statSync as eb,writeFileSync as Pi}from"fs";import{join as tb}from"path";import{readFileSync as ed}from"fs";import{createRequire as Ay}from"module";import{dirname as Dy,isAbsolute as DC,relative as OC,resolve as NC,sep as FC}from"path";var td=Ay(import.meta.url),Oy=1,nd="0.4.0";function wi(){let e=Ny();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Ny(){try{let e=td.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(ed(e,"utf8"));if(t.version!==nd)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${nd}`};let n=Dy(e),r=td.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(ed(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:Fy(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Fy(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Oy}`}import{createHash as My}from"crypto";import{readFileSync as _y}from"fs";import{dirname as qy,join as tr}from"path";var nr=2,By="typescript-index";function rd(e){let t=tr(e,By);return{rootDir:t,requestDir:tr(t,"requests"),responseDir:tr(t,"responses")}}function id(e){try{let t=JSON.parse(_y(tr(qy(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:My("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 Vy}from"crypto";import{existsSync as Hy,mkdirSync as od,readFileSync as Wy,rmSync as sd}from"fs";import{resolve as ad}from"path";var Gy=12e4,Uy=5,rr=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=Jo(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Yy(),this.runtime=n.runtime??Xy}request(t){let n=kn(this.cacheDir),r=rd(this.cacheDir),i=Mr(n.statePath);if(!cd(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),s=ad(r.requestDir,`${o}.json`),a=ad(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;od(r.requestDir,{recursive:!0}),od(r.responseDir,{recursive:!0}),yt(s,{protocolVersion:nr,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(Hy(a))return Jy(Wy(a,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=Mr(n.statePath);if(!cd(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Uy)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{sd(s,{force:!0}),sd(a,{force:!0})}}};function cd(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=zo,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===nr&&n.isProcessAlive(e.pid)&&(r||i)}function Jy(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==nr||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=zy(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 zy(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(Ky)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let s=o.bytesBase64===null?null:Qy(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 Ky(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 Qy(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Yy(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Gy}var Xy={now:Date.now,randomId:Vy,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ht};function nb(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."];if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let n=Pn(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"||!_t(l.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=Cn(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=rb([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=ld(e.currentSnapshot,e.projectFiles,e.producerIdentity),s=ld(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==s)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let a=ud(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!a)return{eligible:!1,reason:"prior document identity unavailable"};let c=ud(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:dd(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:dd(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 rb(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 md(e){let t=Date.now();try{if(!$i(e.previousDbPath)||!$i(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=wi();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new Ae({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),s,a;try{s=pn(o,{includeIgnored:!1}).filter(_t).sort(),a=gn(o)}finally{o.close()}let c=performance.now()-n,l=nb({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?Yt(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:s,graph:a,producerIdentity:r.producerIdentity,rootTsconfigExists:$i(tb(e.projectRoot,"tsconfig.json"))});if(!l.eligible)throw new Error(l.reason);let d=id(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let m=new rr({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=eb(e.previousShardPath).size>=Ja;n=performance.now();let h=g?null:pd(e.previousShardPath),y=g?{completeIndexBytes:null,affectedIndexBytes:Ha(m.fragments)}:Ua({packageVersion:r.packageVersion,baseIndexBytes:h,fragments:m.fragments}),S=performance.now()-n;n=performance.now(),g?za({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,nextGenerationIdentity:l.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:m.fragments}):(Wa({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:h,producerIdentity:r.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.previousFragmentGeneration,documentIdentities:l.previousDocumentIdentities,allowUntrackedDocuments:!0}),Ga({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&&Pi(e.candidateShardPath,y.completeIndexBytes),Pi(e.candidateAffectedScipPath,y.affectedIndexBytes);let k=performance.now()-n,R={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:Date.now()-t,cold:m.cold,changedFiles:l.plan.changedFiles,affectedFiles:l.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:l.previousFragmentGeneration,nextFragmentGeneration:l.nextFragmentGeneration,manifest:l.manifest,plan:l.plan,projectFileCount:s.length,referenceFragmentsByFile:new Map(m.fragments.map(D=>[D.relativePath,D.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:f,serviceMs:m.durationMs,assemblyMs:S,fragmentStoreMs:x,writeMs:k}};return e.onStatus(`Incremental TypeScript index emitted ${R.affectedFiles.length} affected document(s) in ${(R.durationMs/1e3).toFixed(3)}s (${R.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${f.toFixed(0)}ms, assembly ${S.toFixed(0)}ms, fragments ${x.toFixed(0)}ms, write ${k.toFixed(0)}ms).`),R}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function fd(e){let t=wi();if(!t.available)throw new Error(t.reason);let n=Ka({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:pd(e.baseShardPath),packageVersion:t.packageVersion});Pi(e.candidateShardPath,n)}function ld(e,t,n){let r=e.files.filter(i=>Vo(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 Ci(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function dd(e,t){return Ci(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function ud(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),s=as({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,Ci(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return a}function Ci(e){return Zy("sha256").update(e).digest("hex")}import{execFile as ib}from"child_process";import{existsSync as ir,renameSync as Ii,rmSync as Ei,statSync as ob}from"fs";import{cpus as sb}from"os";import{join as gd}from"path";function ab(e,t,n){if(!e.defaultOutputPath)return;let r=gd(t,e.defaultOutputPath);n!==r&&ir(r)&&Ii(r,n)}function cb(e,t,n){if(!e.defaultOutputPath)return null;let r=gd(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Ei(i,{force:!0}),ir(r)?(Ii(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function lb(e){e&&(Ei(e.defaultOutputPath,{force:!0}),e.backupPath&&ir(e.backupPath)&&Ii(e.backupPath,e.defaultOutputPath))}function db(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,sb().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function hd(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=db(o.length,r),c=await pb(o,a,l=>Ti(l,t,n));if(a>1){let l=new Map;for(let d of c.filter(u=>u.skipped)){let u=o.find(m=>m.id===d.id);u&&(n(`Retrying ${u.label} indexer serially after parallel failure...`),l.set(u.id,await Ti(u,t,n)))}s.push(...c.map(d=>l.get(d.id)??d))}else s.push(...c);for(let l of i)s.push(await Ti(l,t,n));return s.sort((l,d)=>e.findIndex(u=>u.id===l.id)-e.findIndex(u=>u.id===d.id))}async function Ti(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Ei(e.scipPath,{force:!0});let r=cb(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{let a=Oo(e.binary,e.args);await ub(a.binary,a.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),ab(e.config,t,e.scipPath)}catch(a){let c=a instanceof Error?a.message:String(a),l=`${e.resolvedBinary} indexer failed: ${c.split(`
277
+ `)[0]}`,d=e.label===e.language?l:`${e.label}: ${l}`;return n(`Skipping ${e.label}: ${l}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:d}}}finally{lb(r)}if(!ir(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=ob(e.scipPath).size}catch{s=void 0}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,outputBytes:s}}function ub(e,t,n){return new Promise((r,i)=>{ib(e,[...t],n,o=>{o?i(o):r()})})}async function pb(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 Jb from"better-sqlite3";import{existsSync as zb}from"fs";import{dirname as Kb,join as Qb,resolve as Yb}from"path";import{readFileSync as fb,rmSync as gb,statSync as hb,mkdtempSync as yb}from"fs";import{tmpdir as bb}from"os";import{join as ji}from"path";import{Worker as Sb}from"worker_threads";function mb(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function It(){return{skippedReferences:0,skippedReferenceReasons:mb(),skippedReferenceSamples:[]}}function or(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 yd(e){return e.length>=8&&Sd(e.length)>1}function bd(e){let t=Sd(e.vueFiles.length),n=xb(e.vueFiles),r=kb(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=yb(ji(bb(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=vb(),l=Date.now();try{for(let m=0;m<r.length;m++)new Sb(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[m],resultPath:ji(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(fb(ji(o,`${f}.json`),"utf-8"));if(!g.ok)throw new Error(`Vue reference worker failed: ${g.error}`);return g.result}),u={occurrences:d.flatMap(m=>m.occurrences),...It()};for(let m of d)or(u,m);return u}finally{gb(o,{recursive:!0,force:!0})}}function Sd(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 vb(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function xb(e){let t=Rb(),n=[];for(let r of e){let i=vd(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 Rb(){return Number.POSITIVE_INFINITY}function kb(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:wb(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 wb(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,vd(e.fileName)-e.startOffset)}function vd(e){try{return hb(e).size}catch{return 1}}import{createRequire as $b}from"module";import{existsSync as Pb,readFileSync as Ai}from"fs";import{dirname as xd,extname as Cb,join as Rd,relative as Tb,resolve as Ib}from"path";import{pathToFileURL as Eb}from"url";function jb(e){e.transaction(()=>{e.prepare(`
278
278
  DELETE FROM mentions
279
279
  WHERE chunk_id IN (
280
280
  SELECT c.id
@@ -289,12 +289,12 @@ ${r.message}`:""}var el=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
289
289
  FROM documents
290
290
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
291
291
  )
292
- `).run()})()}function Rd(e,t){return e.prepare(`
292
+ `).run()})()}function kd(e,t){return e.prepare(`
293
293
  SELECT relative_path AS relativePath
294
294
  FROM documents
295
295
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
296
296
  ORDER BY relative_path
297
- `).all().map(r=>Tb(t,r.relativePath))}function kd(e,t){let{vueCore:n,ts:r,volarTs:i}=jb(e),{parsed:o,vueOptions:s}=Lb(n,r,t),a=vd(t),c=n.createVueLanguagePlugin(r,o.options,s,f=>f),l=Ab(n,r,c),d=Db(a,o),{languageServiceHost:u}=i.createLanguageServiceHost(r,r.sys,l,f=>f,d),m=r.createLanguageService(u);return{ts:r,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function jb(e){let t=wb(Ib(xd(e,"package.json")).href);return{vueCore:Li(t,"@vue/language-core",e),ts:Li(t,"typescript",e),volarTs:Li(t,"@volar/typescript",e)}}function Lb(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.config)throw new Error(`Failed to read ${n}`);let o=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(o.globalTypesPath=e.createGlobalTypesWriter(o,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(r.config,t.sys,vd(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Ab(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!$b(o))return;let s=Ai(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??qb(o))});return r.current=i,i}function Db(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Li(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:r}):r}}function wd(e,t,n){let r=Ob(e);return i=>{if(!i.name)return null;let o=Ve(t,i.fileName),s=n.get(i.fileName);if(!s)return null;let a=n.positionAt(s,i.textSpan.start),c=r.get(o);if(!c)return null;let l=c.starts.find(u=>u.line===a.line&&u.displayName===i.name);if(l)return l.symbolId;let d=c.containingByLine.get(a.line);return d&&d.displayName===i.name?d.symbolId:Nb(c.starts,a.line,2,i.name)}}function Ob(e){let t=e.prepare(`
297
+ `).all().map(r=>Ib(t,r.relativePath))}function wd(e,t){let{vueCore:n,ts:r,volarTs:i}=Lb(e),{parsed:o,vueOptions:s}=Ab(n,r,t),a=xd(t),c=n.createVueLanguagePlugin(r,o.options,s,f=>f),l=Db(n,r,c),d=Ob(a,o),{languageServiceHost:u}=i.createLanguageServiceHost(r,r.sys,l,f=>f,d),m=r.createLanguageService(u);return{ts:r,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function Lb(e){let t=$b(Eb(Rd(e,"package.json")).href);return{vueCore:Li(t,"@vue/language-core",e),ts:Li(t,"typescript",e),volarTs:Li(t,"@volar/typescript",e)}}function Ab(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.config)throw new Error(`Failed to read ${n}`);let o=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(o.globalTypesPath=e.createGlobalTypesWriter(o,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(r.config,t.sys,xd(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Db(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!Pb(o))return;let s=Ai(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??Bb(o))});return r.current=i,i}function Ob(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Li(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:r}):r}}function $d(e,t,n){let r=Nb(e);return i=>{if(!i.name)return null;let o=Ve(t,i.fileName),s=n.get(i.fileName);if(!s)return null;let a=n.positionAt(s,i.textSpan.start),c=r.get(o);if(!c)return null;let l=c.starts.find(u=>u.line===a.line&&u.displayName===i.name);if(l)return l.symbolId;let d=c.containingByLine.get(a.line);return d&&d.displayName===i.name?d.symbolId:Fb(c.starts,a.line,2,i.name)}}function Nb(e){let t=e.prepare(`
298
298
  SELECT
299
299
  d.relative_path AS relativePath,
300
300
  der.start_line AS startLine,
@@ -305,22 +305,22 @@ ${r.message}`:""}var el=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
305
305
  JOIN documents d ON d.id = der.document_id
306
306
  JOIN global_symbols gs ON gs.id = der.symbol_id
307
307
  ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
308
- `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function Nb(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let a=Math.floor((i+o)/2);e[a].line<t?i=a+1:o=a-1}let s=null;for(let a of[o,i]){let c=e[a];if(!c||c.displayName!==r)continue;let l=Math.abs(c.line-t);l>n||(!s||l<s.distance)&&(s={distance:l,symbolId:c.symbolId})}return s?.symbolId??null}function $d(e,t,n){let r=Hb(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
308
+ `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function Fb(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let a=Math.floor((i+o)/2);e[a].line<t?i=a+1:o=a-1}let s=null;for(let a of[o,i]){let c=e[a];if(!c||c.displayName!==r)continue;let l=Math.abs(c.line-t);l>n||(!s||l<s.distance)&&(s={distance:l,symbolId:c.symbolId})}return s?.symbolId??null}function Pd(e,t,n){let r=Wb(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
309
309
  INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
310
310
  VALUES (?, ?, ?, ?)
311
- `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let d=Ve(t,l),u=Dd(r.name,r.version,d);o.run(u,"default",7,`Vue component|${d}`);let m=Wb(i,r,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Pd(e,t,n,r,i){return e.transaction(()=>(Eb(e),Fb(e,t,n,r),Mb(e,i)))()}function Fb(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
311
+ `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let d=Ve(t,l),u=Od(r.name,r.version,d);o.run(u,"default",7,`Vue component|${d}`);let m=Gb(i,r,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Cd(e,t,n,r,i){return e.transaction(()=>(jb(e),Mb(e,t,n,r),_b(e,i)))()}function Mb(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
312
312
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
313
313
  VALUES (?, ?, ?, ?, X'00')
314
314
  `),s=e.prepare(`
315
315
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
316
316
  VALUES (?, ?, 1)
317
- `);for(let a of n){let c=r.get(a);if(!c)continue;let l=Ve(t,a),d=i.get(l);if(!d)continue;let u=o.run(d.id,-1,0,0);s.run(Number(u.lastInsertRowid),c)}}function Cd(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),s=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&s){let a=r.language.maps.get(s,o);if(Di(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Td(e){let t=new Set,n=[];for(let r of e){let i=Id(r);t.has(i)||(t.add(i),n.push(r))}return n}function Id(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function Mb(e,t){let n=Vb(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
317
+ `);for(let a of n){let c=r.get(a);if(!c)continue;let l=Ve(t,a),d=i.get(l);if(!d)continue;let u=o.run(d.id,-1,0,0);s.run(Number(u.lastInsertRowid),c)}}function Td(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),s=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&s){let a=r.language.maps.get(s,o);if(Di(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Id(e){let t=new Set,n=[];for(let r of e){let i=Ed(r);t.has(i)||(t.add(i),n.push(r))}return n}function Ed(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function _b(e,t){let n=Hb(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
318
318
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
319
319
  VALUES (?, ?, ?, ?, X'00')
320
320
  `),i=e.prepare(`
321
321
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
322
322
  VALUES (?, ?, 0)
323
- `),o=new Set,s=0,a=0;for(let c of t){let l=Id(c);if(o.has(l))continue;o.add(l);let d=n.get(c.sourceFile);if(!d)continue;let u=r.run(d,a++,c.sourceLine,c.sourceLine),m=i.run(Number(u.lastInsertRowid),c.symbolId);s+=Number(m.changes)}return s}function*Ed(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function jd(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Di(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function _b(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function Ld(e,t){return Ve(e,t).startsWith("node_modules/")}function Ve(e,t){return Cb(e,t).replaceAll("\\","/")}function qb(e){switch(Pb(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function Ad(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Ai(t,"utf-8"),r={text:n,lineStarts:Bb(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:_b}}function Bb(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Vb(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),s=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.set(a.relativePath,a.id)}return n}function Hb(e){try{let t=JSON.parse(Ai(xd(e,"package.json"),"utf-8"));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function Wb(e,t,n,r){let i=Ve(n,r),o=Dd(t.name,t.version,i);return e.get(o)?.id??null}function Dd(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Nd(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Yb({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Fi(e){return dt(lt(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),dt(Nd({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function Yb(e){let t=Qb(e.projectRoot,e.tsconfig);if(!Jb(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Ub(e.dbPath);try{let r=Rd(n,e.projectRoot),i=Kb(zb(e.dbPath),"augment-vue-meta.json");return ql({cachePath:i,readFingerprint:()=>eS(n,e.projectRoot,e.tsconfig),compute:()=>Xb({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function Xb(e){let t=$d(e.db,e.projectRoot,e.vueFiles),n=Zb(e,t),r=Td(n.occurrences),i=Pd(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:lS(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:cS(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function Zb(e,t){if(hd(e.vueFiles))return yd({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=tS({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return nS({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function eS(e,t,n){let r=e.prepare(`
323
+ `),o=new Set,s=0,a=0;for(let c of t){let l=Ed(c);if(o.has(l))continue;o.add(l);let d=n.get(c.sourceFile);if(!d)continue;let u=r.run(d,a++,c.sourceLine,c.sourceLine),m=i.run(Number(u.lastInsertRowid),c.symbolId);s+=Number(m.changes)}return s}function*jd(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function Ld(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Di(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function qb(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function Ad(e,t){return Ve(e,t).startsWith("node_modules/")}function Ve(e,t){return Tb(e,t).replaceAll("\\","/")}function Bb(e){switch(Cb(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function Dd(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Ai(t,"utf-8"),r={text:n,lineStarts:Vb(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:qb}}function Vb(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Hb(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),s=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.set(a.relativePath,a.id)}return n}function Wb(e){try{let t=JSON.parse(Ai(Rd(e,"package.json"),"utf-8"));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function Gb(e,t,n,r){let i=Ve(n,r),o=Od(t.name,t.version,i);return e.get(o)?.id??null}function Od(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Fd(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Xb({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Fi(e){return dt(lt(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),dt(Fd({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function Xb(e){let t=Yb(e.projectRoot,e.tsconfig);if(!zb(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Jb(e.dbPath);try{let r=kd(n,e.projectRoot),i=Qb(Kb(e.dbPath),"augment-vue-meta.json");return Bl({cachePath:i,readFingerprint:()=>tS(n,e.projectRoot,e.tsconfig),compute:()=>Zb({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function Zb(e){let t=Pd(e.db,e.projectRoot,e.vueFiles),n=eS(e,t),r=Id(n.occurrences),i=Cd(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:dS(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:lS(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function eS(e,t){if(yd(e.vueFiles))return bd({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=nS({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return rS({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function tS(e,t,n){let r=e.prepare(`
324
324
  SELECT
325
325
  (SELECT COUNT(*) FROM documents) AS documents,
326
326
  (SELECT COUNT(*) FROM global_symbols) AS symbols,
@@ -329,22 +329,22 @@ ${r.message}`:""}var el=[{id:"setup",skillNames:["scip-setup"],keywords:["setup"
329
329
  (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
330
330
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
331
331
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
332
- `).get();return{version:3,tsconfig:n,files:vn(t),db:r}}function tS(e){let t=Ad();return{projectRoot:e.projectRoot,context:kd(e.projectRoot,e.configPath),symbolLookup:wd(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function nS(e){let t=[],n=It(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=rS(e,i);t.push(...o.occurrences),or(n,o)}return{occurrences:t,...n}}function rS(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Od(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 Od(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),s=Ve(e.projectRoot,t.fileName),a=[...Ed(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:uS(a),processedStarts:new Set};return iS({...e,fileName:t.fileName,sourceInfo:n,sourceFile:s,map:o,tokenContext:c})}function iS(e){let t=[],n=It();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||oS(e.sourceInfo.text,r.start))continue;let i=jd(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!Ld(e.projectRoot,d.fileName));if(!s){Oi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let a=Ve(e.projectRoot,s.fileName),c=sS(e.sourceFile,r.text,a);if(c){Oi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let l=Cd(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(l===null){Oi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}Fd(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a,l),e.tokenContext.processedStarts.add(r.start),dS(t,e,r,i,a,l)}return{occurrences:t,...n}}function oS(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 sS(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Od(e,t,n){let r=It();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 Oi(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 Ni(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 aS(e,t){let n=Ni(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=Ni(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function cS(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(...Ni(e.filter(c=>c.reason===o),a))}return r.slice(0,t)}function lS(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return aS(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function dS(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of pS(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&&(Fd(e,t.sourceReader,t.sourceInfo,t.sourceFile,a,i,o),t.tokenContext.processedStarts.add(s))}}function Fd(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 uS(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function pS(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=mS(r,l.textSpan.start,o,i.text);d!==null&&a.push(d)}return a}function mS(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Di(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function Et(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=$S(e),s=Date.now();ar(V(o.outputScip),{recursive:!0}),ar(V(o.outputDb),{recursive:!0});let a=e.languages??tt(t);if(a.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${a.join(", ")}`);let c=Nt("reindex.fingerprint",()=>iv(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:a.length}),l,d;if(e.skipIfUnchanged!==!1&&!Za(t,o.outputDb)&&Md(o.outputScip)===Md(ne(V(o.outputDb),"index.scip"))){let g=Rn(t);if(l=g?En(g,c):void 0,l){let h=jn(l);if(h){if(!wS(o,c))try{Vr({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: ${_i(y)}`)}}else{let y=await nc(l);if(y.kind==="owner")d=y.release;else if(y.kind==="generation-ready"){let S=jn(l);if(S)try{Vr({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: ${_i(x)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let u=Ba(ne(V(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!u)throw d?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${V(o.outputDb)}.`);let m;try{m=await Ft("reindex.lock",()=>YS(ne(V(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:a.length})}catch(g){throw u.release(),d?.(),g}let f=null;try{let g=null,h=Nt("reindex.reuse-check",()=>(g=PS({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r}),g),()=>({languages:a.length,reused:g!==null}));if(h)return _d({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),h;await Ft("reindex.scip-cli-ready",()=>HS(i,r));let y=TS(o);f=y.runDir;let S,x=await Ft("reindex.fresh",async()=>(S=await IS({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 _d({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),x}catch(g){throw tu(o.metaPath,ur({trigger:e.trigger,result:"failed",start:s,error:g instanceof Error?g.message:String(g)})),g}finally{f&&Ye(f,{recursive:!0,force:!0}),m(),u.release(),d?.()}}function _d(e){if(e.snapshot){if(jn(e.snapshot)){Hr(e.snapshot,V(e.paths.outputDb),"local-fresh");return}try{let t=Rn(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}tc({snapshot:e.snapshot,sourceCacheDir:V(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=Rn(e.projectRoot);return(r?En(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),Hr(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: ${_i(t)}`)}}}function wS(e,t){if(!Re(e.outputScip)||!Re(e.outputDb)||!eu(e.metaPath,t))return!1;let n=nt(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function _i(e){return e instanceof Error?e.message:String(e)}function $S(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 PS(e){let t=nt(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!Re(e.paths.outputScip)||!Re(e.paths.outputDb)||!eu(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;dt(lt(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=ur({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return tu(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:CS(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function CS(e,t,n,r){let i=Xd(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:Xt(i[o]),outputBytes:Zt(Bi(e.outputDb,o)),durationMs:0}))}function TS(e){let t=yS(ne(V(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:ne(t,sr(e.outputScip)),tempOutputDb:ne(t,sr(e.outputDb)),tempMetaPath:ne(t,sr(e.metaPath))}}async function IS(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await Ft("reindex.language-indexers",async()=>(n=await jS(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(", ")}`),ES({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:s})){let f=Nt("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 u=Nt("reindex.publish",()=>_S(e,t,i,o,s,a,l,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:s.length,skipped:o.length}),m=u.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:u,shards:c}}function ES(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=nt(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 jS(e,t){let n=NS({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=nt(e.paths.outputDb,e.paths.metaPath),a=tn(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?pd({projectRoot:e.projectRoot,cacheDir:V(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:en(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:en(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:qi(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,u=new Set(d?["typescript"]:[]),m=d?void 0:LS(e,n),{preparedRuns:f,skippedLanguages:g,languageOutputScipPaths:h}=WS({languages:e.languages.filter(O=>!i.has(O)&&!u.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 gd(y,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),x=[];if(m){DS(e.paths.outputDb,S);let O=h.typescript??e.tempPaths.tempOutputScip;x=OS({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:O,reusedProjects:m.reusedProjects})}let k=[...S,...x],{indexedOutputs:R}=US(k,g),D=d?[{language:"typescript",scipPath:d.scipPath}]:[],_=[...r,...D,...R];JS(_,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:Zt(d.scipPath)??void 0}]:[],T=FS(n,[...S,...z],m?{outputDb:e.paths.outputDb,classification:m.classification}:void 0);return{indexedOutputs:_,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:MS(n,e.languages),shards:T,typescriptProjectShardContext:m?{projects:m.allProjects,fingerprints:m.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function LS(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=Yt(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Gl(e.projectRoot,r),o=Vl(n.fingerprint.files,r),s=Hl(r,i),a=Wl(r,o,s),c=tn(e.paths.metaPath),d=AS(c,a,g=>Re(dr(e.paths.outputDb,g))),u=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),m=new Set(u),f=new Set(r.filter(g=>!m.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:a,classification:d,reusedProjects:u,missedProjectIds:f}}function AS(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 DS(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=dr(e,r);ar(V(i),{recursive:!0}),cr(n.scipPath,i)}}function OS(e){return e.reusedProjects.map((t,n)=>{let r=dr(e.outputDb,t),i=en(e.tempOutputScip,"typescript-project-cached",n);return cr(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Zt(i)??void 0}})}function NS(e){let t=tn(e.paths.metaPath),n=Xd(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Bi(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 FS(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:Xt(o.fingerprint),outputBytes:Zt(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?Xt(a.fingerprint):o?Xt(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:Xt(o.fingerprint),outputBytes:Zt(dr(n.outputDb,i)),durationMs:0});return r}function Xt(e){return gS("sha256").update(He(e)).digest("hex").slice(0,16)}function Zt(e){try{return vS(e).size}catch{return null}}function MS(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function _S(e,t,n,r,i,o,s,a){let c=!a||a.completeScipUpdated,l=!1;c&&(qd(e.paths.outputDb,n),l=Bd(n,e.tempPaths.tempOutputScip,e.onStatus));let d=zS({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..."),md({cacheDir:V(e.paths.outputDb),generationIdentity:a.nextFragmentGeneration,baseShardPath:a.scipPath,candidateShardPath:a.candidateScipPath});let x=n.map(k=>k.language==="typescript"?{language:k.language,scipPath:a.candidateScipPath}:k);return qd(e.paths.outputDb,x),l=Bd(x,e.tempPaths.tempOutputScip,e.onStatus),l}});if(dt(lt(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&a){let x=null,k=null;try{x=new Ae({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),k=new Ae({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let R=as(x,e.fingerprint,a.referenceFragmentsByFile,k);e.onStatus(`Cached exact TypeScript reference fragments for ${R} affected document(s).`)}catch(R){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${R instanceof Error?R.message:String(R)}.`)}finally{x?.close(),k?.close()}}let u=qi(e.paths.metaPath),m=d.mode==="incremental"&&a?QS(a,d.changedDocumentPaths):hi({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:u,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),f=ur({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}=Jd({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:h,typescriptProjectShardContext:s,lastRefresh:f});return y.scipCompanion=g?"deferred":"current",zd(e.paths.outputDb,S),Vi(e.tempPaths.tempMetaPath,y),_a({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}:{}}}),Ka(V(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[a.nextFragmentGeneration]:[]),Ud(e.paths.outputDb,m,e.onStatus),f}function qS(e,t,n,r,i,o){let s=qi(e.paths.metaPath),a=null;try{cr(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(u){a=Cl("reused","oracle-error",`Could not snapshot the prior database: ${u instanceof Error?u.message:String(u)}`)}dt(lt(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),a??=hi({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=ur({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(u=>u.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=Jd({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return zd(e.paths.outputDb,d),Vi(e.paths.metaPath,l),qa(e.paths.outputDb,e.paths.metaPath),Ud(e.paths.outputDb,a,e.onStatus),c}function qi(e){return is(tn(e)?.fingerprint)}function Ud(e,t,n){try{jl(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 Jd(e){let t=BS({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 BS(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=tn(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 zd(e,t){let n=Zd(e);if(t===null){Ye(n,{recursive:!0,force:!0});return}let r;try{r=SS(n)}catch{return}for(let i of VS(r,t))Ye(ne(n,i),{force:!0})}function VS(e,t){let n=new Set(t.map(r=>`${Ri(r)}.scip`));return e.filter(r=>!n.has(r))}function qd(e,t){for(let n of t){let r=Bi(e,n.language);ar(V(r),{recursive:!0}),n.scipPath!==r&&cr(n.scipPath,r)}}async function HS(e,t){if(!Un()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
334
- Install from: https://github.com/sourcegraph/scip/releases`);if(kS()==="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..."),!gl(t))throw new Error(`The scip CLI is required but could not be installed.
335
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function WS(e){let t=[],n=[],r=e.languages.map((o,s)=>({language:o,scipPath:e.languages.length>1?en(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=GS({...e,language:o,scipPath:s});for(let c of a)"skipped"in c?Kd(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function GS(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Mi({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??Yt(e.projectRoot,e.typescriptProjects);return t.length===0?[Mi({...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)=>Mi({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:en(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Mi(e){let t=et(e.language),n=Oo(t),r=Mo(t,e.projectRoot);if(!r&&!Fo(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...`),!Sn(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??No(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:_o(t,e.env,i)}}}function US(e,t){let n=new Map;for(let i of e)if(i.skipped)Kd(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)Ya(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&Gd(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function Kd(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 JS(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
332
+ `).get();return{version:3,tsconfig:n,files:vn(t),db:r}}function nS(e){let t=Dd();return{projectRoot:e.projectRoot,context:wd(e.projectRoot,e.configPath),symbolLookup:$d(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function rS(e){let t=[],n=It(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=iS(e,i);t.push(...o.occurrences),or(n,o)}return{occurrences:t,...n}}function iS(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Nd(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 Nd(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),s=Ve(e.projectRoot,t.fileName),a=[...jd(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:pS(a),processedStarts:new Set};return oS({...e,fileName:t.fileName,sourceInfo:n,sourceFile:s,map:o,tokenContext:c})}function oS(e){let t=[],n=It();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||sS(e.sourceInfo.text,r.start))continue;let i=Ld(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!Ad(e.projectRoot,d.fileName));if(!s){Oi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let a=Ve(e.projectRoot,s.fileName),c=aS(e.sourceFile,r.text,a);if(c){Oi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let l=Td(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(l===null){Oi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}Md(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a,l),e.tokenContext.processedStarts.add(r.start),uS(t,e,r,i,a,l)}return{occurrences:t,...n}}function sS(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 aS(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Nd(e,t,n){let r=It();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 Oi(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 Ni(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 cS(e,t){let n=Ni(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=Ni(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function lS(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(...Ni(e.filter(c=>c.reason===o),a))}return r.slice(0,t)}function dS(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return cS(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function uS(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of mS(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&&(Md(e,t.sourceReader,t.sourceInfo,t.sourceFile,a,i,o),t.tokenContext.processedStarts.add(s))}}function Md(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 pS(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function mS(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=fS(r,l.textSpan.start,o,i.text);d!==null&&a.push(d)}return a}function fS(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Di(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function Et(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=PS(e),s=Date.now();ar(V(o.outputScip),{recursive:!0}),ar(V(o.outputDb),{recursive:!0});let a=e.languages??tt(t);if(a.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${a.join(", ")}`);let c=Nt("reindex.fingerprint",()=>ov(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:a.length}),l,d;if(e.skipIfUnchanged!==!1&&!ec(t,o.outputDb)&&_d(o.outputScip)===_d(ne(V(o.outputDb),"index.scip"))){let g=Rn(t);if(l=g?En(g,c):void 0,l){let h=jn(l);if(h){if(!$S(o,c))try{Vr({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: ${_i(y)}`)}}else{let y=await rc(l);if(y.kind==="owner")d=y.release;else if(y.kind==="generation-ready"){let S=jn(l);if(S)try{Vr({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: ${_i(x)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let u=Va(ne(V(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!u)throw d?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${V(o.outputDb)}.`);let m;try{m=await Ft("reindex.lock",()=>XS(ne(V(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:a.length})}catch(g){throw u.release(),d?.(),g}let f=null;try{let g=null,h=Nt("reindex.reuse-check",()=>(g=CS({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r}),g),()=>({languages:a.length,reused:g!==null}));if(h)return qd({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),h;await Ft("reindex.scip-cli-ready",()=>WS(i,r));let y=IS(o);f=y.runDir;let S,x=await Ft("reindex.fresh",async()=>(S=await ES({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 qd({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),x}catch(g){throw nu(o.metaPath,ur({trigger:e.trigger,result:"failed",start:s,error:g instanceof Error?g.message:String(g)})),g}finally{f&&Ye(f,{recursive:!0,force:!0}),m(),u.release(),d?.()}}function qd(e){if(e.snapshot){if(jn(e.snapshot)){Hr(e.snapshot,V(e.paths.outputDb),"local-fresh");return}try{let t=Rn(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}nc({snapshot:e.snapshot,sourceCacheDir:V(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=Rn(e.projectRoot);return(r?En(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),Hr(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: ${_i(t)}`)}}}function $S(e,t){if(!Re(e.outputScip)||!Re(e.outputDb)||!tu(e.metaPath,t))return!1;let n=nt(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function _i(e){return e instanceof Error?e.message:String(e)}function PS(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 CS(e){let t=nt(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!Re(e.paths.outputScip)||!Re(e.paths.outputDb)||!tu(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;dt(lt(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=ur({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return nu(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:TS(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function TS(e,t,n,r){let i=Zd(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:Xt(i[o]),outputBytes:Zt(Bi(e.outputDb,o)),durationMs:0}))}function IS(e){let t=bS(ne(V(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:ne(t,sr(e.outputScip)),tempOutputDb:ne(t,sr(e.outputDb)),tempMetaPath:ne(t,sr(e.metaPath))}}async function ES(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await Ft("reindex.language-indexers",async()=>(n=await LS(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(", ")}`),jS({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:s})){let f=Nt("reindex.publish",()=>BS(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 u=Nt("reindex.publish",()=>qS(e,t,i,o,s,a,l,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:s.length,skipped:o.length}),m=u.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:u,shards:c}}function jS(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=nt(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 LS(e,t){let n=FS({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=nt(e.paths.outputDb,e.paths.metaPath),a=tn(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?md({projectRoot:e.projectRoot,cacheDir:V(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:en(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:en(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:qi(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,u=new Set(d?["typescript"]:[]),m=d?void 0:AS(e,n),{preparedRuns:f,skippedLanguages:g,languageOutputScipPaths:h}=GS({languages:e.languages.filter(O=>!i.has(O)&&!u.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 hd(y,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),x=[];if(m){OS(e.paths.outputDb,S);let O=h.typescript??e.tempPaths.tempOutputScip;x=NS({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:O,reusedProjects:m.reusedProjects})}let k=[...S,...x],{indexedOutputs:R}=JS(k,g),D=d?[{language:"typescript",scipPath:d.scipPath}]:[],_=[...r,...D,...R];zS(_,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:Zt(d.scipPath)??void 0}]:[],T=MS(n,[...S,...z],m?{outputDb:e.paths.outputDb,classification:m.classification}:void 0);return{indexedOutputs:_,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:_S(n,e.languages),shards:T,typescriptProjectShardContext:m?{projects:m.allProjects,fingerprints:m.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function AS(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=Yt(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Ul(e.projectRoot,r),o=Hl(n.fingerprint.files,r),s=Wl(r,i),a=Gl(r,o,s),c=tn(e.paths.metaPath),d=DS(c,a,g=>Re(dr(e.paths.outputDb,g))),u=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),m=new Set(u),f=new Set(r.filter(g=>!m.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:a,classification:d,reusedProjects:u,missedProjectIds:f}}function DS(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 OS(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=dr(e,r);ar(V(i),{recursive:!0}),cr(n.scipPath,i)}}function NS(e){return e.reusedProjects.map((t,n)=>{let r=dr(e.outputDb,t),i=en(e.tempOutputScip,"typescript-project-cached",n);return cr(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Zt(i)??void 0}})}function FS(e){let t=tn(e.paths.metaPath),n=Zd(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Bi(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 MS(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:Xt(o.fingerprint),outputBytes:Zt(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?Xt(a.fingerprint):o?Xt(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:Xt(o.fingerprint),outputBytes:Zt(dr(n.outputDb,i)),durationMs:0});return r}function Xt(e){return hS("sha256").update(He(e)).digest("hex").slice(0,16)}function Zt(e){try{return xS(e).size}catch{return null}}function _S(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function qS(e,t,n,r,i,o,s,a){let c=!a||a.completeScipUpdated,l=!1;c&&(Bd(e.paths.outputDb,n),l=Vd(n,e.tempPaths.tempOutputScip,e.onStatus));let d=KS({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..."),fd({cacheDir:V(e.paths.outputDb),generationIdentity:a.nextFragmentGeneration,baseShardPath:a.scipPath,candidateShardPath:a.candidateScipPath});let x=n.map(k=>k.language==="typescript"?{language:k.language,scipPath:a.candidateScipPath}:k);return Bd(e.paths.outputDb,x),l=Vd(x,e.tempPaths.tempOutputScip,e.onStatus),l}});if(dt(lt(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&a){let x=null,k=null;try{x=new Ae({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),k=new Ae({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let R=cs(x,e.fingerprint,a.referenceFragmentsByFile,k);e.onStatus(`Cached exact TypeScript reference fragments for ${R} affected document(s).`)}catch(R){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${R instanceof Error?R.message:String(R)}.`)}finally{x?.close(),k?.close()}}let u=qi(e.paths.metaPath),m=d.mode==="incremental"&&a?YS(a,d.changedDocumentPaths):hi({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:u,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),f=ur({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}=zd({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:h,typescriptProjectShardContext:s,lastRefresh:f});return y.scipCompanion=g?"deferred":"current",Kd(e.paths.outputDb,S),Vi(e.tempPaths.tempMetaPath,y),qa({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}:{}}}),Qa(V(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[a.nextFragmentGeneration]:[]),Jd(e.paths.outputDb,m,e.onStatus),f}function BS(e,t,n,r,i,o){let s=qi(e.paths.metaPath),a=null;try{cr(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(u){a=Tl("reused","oracle-error",`Could not snapshot the prior database: ${u instanceof Error?u.message:String(u)}`)}dt(lt(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),a??=hi({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=ur({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(u=>u.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=zd({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return Kd(e.paths.outputDb,d),Vi(e.paths.metaPath,l),Ba(e.paths.outputDb,e.paths.metaPath),Jd(e.paths.outputDb,a,e.onStatus),c}function qi(e){return os(tn(e)?.fingerprint)}function Jd(e,t,n){try{Ll(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 zd(e){let t=VS({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 VS(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=tn(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 Kd(e,t){let n=eu(e);if(t===null){Ye(n,{recursive:!0,force:!0});return}let r;try{r=vS(n)}catch{return}for(let i of HS(r,t))Ye(ne(n,i),{force:!0})}function HS(e,t){let n=new Set(t.map(r=>`${Ri(r)}.scip`));return e.filter(r=>!n.has(r))}function Bd(e,t){for(let n of t){let r=Bi(e,n.language);ar(V(r),{recursive:!0}),n.scipPath!==r&&cr(n.scipPath,r)}}async function WS(e,t){if(!Un()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
334
+ Install from: https://github.com/sourcegraph/scip/releases`);if(wS()==="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..."),!hl(t))throw new Error(`The scip CLI is required but could not be installed.
335
+ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function GS(e){let t=[],n=[],r=e.languages.map((o,s)=>({language:o,scipPath:e.languages.length>1?en(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=US({...e,language:o,scipPath:s});for(let c of a)"skipped"in c?Qd(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function US(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Mi({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??Yt(e.projectRoot,e.typescriptProjects);return t.length===0?[Mi({...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)=>Mi({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:en(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Mi(e){let t=et(e.language),n=No(t),r=_o(t,e.projectRoot);if(!r&&!Mo(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...`),!Sn(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??Fo(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:qo(t,e.env,i)}}}function JS(e,t){let n=new Map;for(let i of e)if(i.skipped)Qd(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)Xa(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&Ud(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function Qd(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 zS(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
- `))}function Bd(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=Xa(e.map(o=>o.scipPath),t);return Yd(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Gd(e[0].scipPath,t);return!1}function zS(e){let t;if(KS(e)){let i=ne(e.run.tempPaths.runDir,"typescript-affected.db");try{Qd(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();Vd(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=Fl({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),Ye(i,{force:!0}),Ye(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 Vd(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function KS(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 QS(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:gi(e.plan,o,e.projectFileCount)}}function Vd(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||Qd(e,r);let o=Un();if(!o)throw new Error("scip CLI is not available");fS(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 Qd(e,t){let n=Qa(e);Yd(n,t)}function Yd(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function en(e,t,n){let r=RS(e)||".scip",i=sr(e,r);return ne(V(e),`${i}.${n+1}.${t}${r}`)}async function YS(e,t){for(let n=0;n<2;n++){let r=XS(e,t);if(r)return r;let i=ZS(e);if(i&&ev(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await nv(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.`);Ye(e,{force:!0});continue}if(i&&!ht(i.pid)){Ye(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 XS(e,t){let n;try{n=bS(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 xS(n,JSON.stringify(r)+`
340
- `),()=>{try{hS(n)}finally{Ye(e,{force:!0})}}}function ZS(e){try{let t=JSON.parse(lr(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 ev(e,t){return e?.kind==="manual-cli"&&tv(t?.trigger)}function tv(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function nv(e){return Hd(e,"SIGTERM"),await Wd(e,2e3)?!0:(Hd(e,"SIGKILL"),Wd(e,1e3))}function Hd(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function Wd(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!ht(e))return!0;await rv(50)}return!ht(e)}function rv(e){return new Promise(t=>setTimeout(t,e))}function iv(e,t,n){return Ho(e,t,n)}function Xd(e,t,n){return Object.fromEntries(t.map(r=>{let i=et(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Vo(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},s=r==="clojure"?ov(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&sv(n),...o,clojureConfigPath:s,files:vn(e,{language:r,markerFiles:i})}]}))}function ov(e){return e?.trim()||void 0}function sv(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Bi(e,t){return ne(V(e),"language-indexes",`${t}.scip`)}function Zd(e){return ne(V(e),"language-indexes","typescript-projects")}function dr(e,t){return ne(Zd(e),`${Ri(t)}.scip`)}function tn(e){try{return JSON.parse(lr(e,"utf-8"))}catch{return null}}function eu(e,t){try{let n=JSON.parse(lr(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 Vi(e,t){yt(e,t,{spacing:2,trailingNewline:!0})}function tu(e,t){try{let n=JSON.parse(lr(e,"utf-8"));if(n.version!==2&&n.version!==3)return;Vi(e,{...n,lastRefresh:t})}catch{}}function ur(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 Hi=864e5;function nu(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}`,u=i.get(d);u||(u={check:l.check,findingId:l.findingId,caughtAt:l.ts,events:[]},i.set(d,u)),u.events.push(l)}let o=[...i.values()].filter(l=>t.sinceMs===void 0||l.caughtAt>=t.sinceMs),s=av(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 u=0,m=0,f=0,g=0,h=0,y=0,S=[];for(let k of d){f+=k.events.filter(_=>_.event==="reopened").length;let R=k.events[k.events.length-1],D=`${k.check}\0${k.findingId}`;if(R.event==="resolved"&&s.has(D))g+=1;else if(R.event==="resolved"){let _=Gt(k.events.slice(0,-1)),z=_?.comparisonBaseCommit??_?.commit,T=R.comparisonBaseCommit??R.commit;z&&(T===z||R.verifiedAgainstCommit===z)?(u+=1,S.push((R.ts-k.caughtAt)/Hi)):h+=1}else R.event==="suppressed"?m+=1:y+=1}let x=u+m;c.push({check:l,caught:d.length,fixed:u,suppressed:m,reopened:f,moved:g,unverified:h,open:y,precision:x>0?u/x:null,medianDaysToFix:S.length>0?cv(S):null})}return{totalEvents:r.length,windowStart:t.sinceMs??null,checks:c.sort((l,d)=>l.check.localeCompare(d.check))}}function av(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 ru(e,t){let n=/^(\d+)([dw])$/.exec(e.trim());if(n){let i=Number(n[1]),o=n[2]==="w"?7*Hi:Hi;return t-i*o}let r=Date.parse(e);return Number.isNaN(r)?null:r}function cv(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 lv}from"child_process";import{statSync as dv}from"fs";import{isAbsolute as uv,join as pv,relative as mv}from"path";import{watch as fv}from"chokidar";import gv from"ignore";var pr=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=Pe(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=vt(t.projectRoot),this.extraIgnore=gv(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let t=fv(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=iu(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=uv(t)?t:pv(this.projectRoot,t);return mv(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=iu(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=fe(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=lv(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:a.indexPath,SCIP_REINDEX_OUTPUT_DB:a.dbPath,SCIP_REINDEX_LANGUAGES:(s.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(s.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:t.kind,SCIP_REINDEX_TRIGGER_DETAIL:t.detail??""},stdio:"pipe"});d.on("exit",u=>{u===0?n(Date.now()-i):r(new Error(`Reindex worker exited with code ${u}`))}),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=Nr(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n=Go(this.projectRoot,t),r={head:Nr(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:n};try{let i=dv(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 iu(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 Fv}from"fs";import{existsSync as su,mkdirSync as au,readFileSync as cu,writeFileSync as lu}from"fs";import{homedir as hv}from"os";import{dirname as du,isAbsolute as yv,join as Wi,relative as ou,resolve as bv}from"path";function uu(e,t={}){let n=t.dossierDir?bv(e.projectRoot,t.dossierDir):Wi(e.projectRoot,"docs","scip-query"),r={markdownPath:Wi(n,"health-dossier.md"),jsonPath:Wi(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},i=Cv({...e,generatedAt:new Date().toISOString(),healthDossier:r},e.projectRoot);try{return wv(r.markdownPath,Sv(i),r),$v(r.jsonPath,i,r),r}catch(o){return{...r,status:"failed",error:o instanceof Error?o.message:String(o)}}}function Sv(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${Ui(e.health)}`,"","## Items That Need Attention","",...vv(e),"","## Blocked Or Unavailable Checks","",...xv(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","",...Rv(e),"","## JSON","",`Machine-readable report: \`${kv(e)}\``,""].join(`
341
- `)}`}function vv(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 xv(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 Rv(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 Ui(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function kv(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function wv(e,t,n){if(au(du(e),{recursive:!0}),(su(e)?cu(e,"utf-8"):null)===t){n.unchanged.push(e);return}lu(e,t),n.written.push(e)}function $v(e,t,n){au(du(e),{recursive:!0});let r=`${JSON.stringify(t,null,2)}
342
- `,i=su(e)?cu(e,"utf-8"):null;if(i&&Pv(i,r)){n.unchanged.push(e);return}lu(e,r),n.written.push(e)}function Pv(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 Cv(e,t){return Gi(e,t)}function Gi(e,t){return typeof e=="string"?Tv(e,t):Array.isArray(e)?e.map(n=>Gi(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Gi(r,t)])):e}function Tv(e,t){if(e===t)return".";if(!yv(e))return e;let n=ou(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let r=ou(hv(),e).replace(/\\/g,"/");return r&&!r.startsWith("..")?`~/${r}`:e}return n}import{spawnSync as Iv}from"child_process";import{readFileSync as mu}from"fs";import{dirname as pu,join as Ev,resolve as jv}from"path";import{fileURLToPath as Lv}from"url";var mr={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 Av(e,t){let n=new Set(["tree-sitter"]);for(let r of e)for(let i of mr[r]?.packages??[])n.add(i);return[...n].filter(r=>t[r]).sort().map(r=>`${r}@${t[r]}`)}function Ji(e){return[...new Set(e.filter(t=>mr[t]!==void 0))].sort()}function fu(e,t={}){let n=t.runtime??Nv,r=t.packageRoot??Dv(),i=Ji(e),o=i.filter(u=>n.probe(mr[u].ast)),s=i.filter(u=>!o.includes(u));if(s.length===0)return{supportedLanguages:i,availableBefore:o,installed:[],availableAfter:o,unavailable:[],attempted:!1};let a=Ov(r),c=Av(s,a),l=n.install(r,c);l.ok&&n.resetProbe();let d=i.filter(u=>n.probe(mr[u].ast));return{supportedLanguages:i,availableBefore:o,installed:l.ok?c:[],availableAfter:d,unavailable:i.filter(u=>!d.includes(u)),attempted:!0,...l.error?{error:l.error}:{}}}function Dv(){let e=pu(Lv(import.meta.url));for(;;){let t=Ev(e,"package.json");try{if(JSON.parse(mu(t,"utf8")).name==="scip-query")return e}catch{}let n=pu(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function Ov(e){return JSON.parse(mu(jv(e,"package.json"),"utf8")).optionalDependencies??{}}var Nv={probe:e=>fn(e)==="ast",resetProbe:Co,install:(e,t)=>{let n=Iv(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 yu(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 bu(e={}){let t=[],n=Fe(),{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=xt(c,{projectRoot:r}),d=l.filter(j=>j.level==="error"),u=null,m=null;if(d.length===0&&c.watch?.enabled!==s)try{u=Ma(r,c,s)}catch(j){m=jt(j)}let f=u?.config??c,g=Kt();F(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?u?.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."),...u?{details:[u.configPath]}:{}}),F(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:[]}:Qn({quiet:!0});F(t,{id:"skills",label:"Agent skills",status:e.installSkills===!1?"skipped":h.skipped.length>0?"warn":"ok",message:e.installSkills===!1?"Skipped by setup choice.":`${h.installed.length} installed, ${h.alreadyLinked.length} already linked, ${h.pruned.length} pruned, ${h.skipped.length} skipped.`,details:[...h.pruned.map(j=>`Pruned ${j}`),...h.skipped.map(j=>`Skipped ${j}`)]});let y=u?xt(f,{projectRoot:r}):l,S=y.filter(j=>j.level==="error");F(t,{id:"config",label:"Project config",status:S.length>0?"failed":y.length>0?"warn":"ok",message:y.length===0?"Config OK.":`${y.length} diagnostic(s), ${S.length} error(s).`,details:y.map(j=>`${j.level.toUpperCase()} ${j.path}: ${j.message}`)});let x=he(r,f);F(t,{id:"readiness",label:"Indexer readiness",status:x.languages.length===0?"failed":x.indexers.some(j=>!j.runnable)?"warn":"ok",message:x.languages.length===0?"No supported project languages detected.":`Detected languages: ${x.languages.join(", ")}`,details:x.indexers.map(j=>`${j.runnable?"OK":j.installed?"WARN":"MISSING"} ${j.language}: ${j.binaryLabel}${j.note?` - ${j.note}`:""}`)});let k=e.installAstParsers===!1?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:fu(x.languages);F(t,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers===!1?"skipped":k.unavailable.length>0?"warn":"ok",message:e.installAstParsers===!1?"Skipped by setup choice.":k.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${k.availableAfter.length}/${k.supportedLanguages.length} selected language parser(s) available${k.installed.length>0?`; installed ${k.installed.join(", ")}`:""}.`,details:[...k.unavailable.length>0?[`Unavailable: ${k.unavailable.join(", ")}`]:[],...k.error?[k.error]:[]]});let R=e.installIndexers??!0,D=R?zv(r,x,t):[];R||F(t,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped by guided setup choice."});let _=he(r,f),z=await Mv({projectRoot:r,paths:i,config:f,readiness:_,configHasErrors:S.length>0,steps:t,onStatus:e.onStatus}),T=z.reindexResult,O=z.freshness,Z=Pe(f),N=_v({projectRoot:r,cacheDir:i.cacheDir,watchConfig:Z,readiness:_,configHasErrors:S.length>0,reindexResult:T,postReindexFreshness:O,steps:t}),H=he(r,f),dn=Je(H),wo=Oe(r,f,i);F(t,{id:"capabilities",label:"Capability matrix",status:ex(dn),message:tx(dn)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let $o=e.runHealth===!1?Yv(t):await Qv(i.dbPath,t),we=H.languages.includes("rust")?xn(r,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;F(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?F(t,{id:"project-hooks",label:"Project agent hooks",status:"skipped",message:"Skipped by --no-hooks."}):(ee=Tt(r),F(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(j=>`Checkout-local Git exclude: ${j}`),...ee.removed.map(j=>`Removed ${j}`),...ee.skipped.map(j=>`Skipped ${j.target}: ${j.reason}`),...ee.warnings]}))}catch(j){F(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:jt(j)})}let be=null;try{e.noAgentGuidance?F(t,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(be=Fn(r,{gitHook:e.gitHook}),F(t,{id:"agent-guidance",label:"Project agent guidance",status:be.skipped.length>0?"warn":"ok",message:`${be.written.length} written, ${be.unchanged.length} already wired, ${be.skipped.length} skipped.`,details:be.skipped.map(j=>`Skipped ${j.target}: ${j.reason}`)}))}catch(j){F(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:jt(j)})}let un=qv({reindexResult:T,readiness:H,capabilities:dn,freshness:wo,health:$o,hooksResult:ee,agentResult:be,watchConfig:Z,watchService:N,rustSemanticSession:we,steps:t});F(t,{id:"smoke-tests",label:"Setup smoke tests",status:Bv(un),message:Vv(un),details:un.map(j=>`${j.command}: ${j.status} - ${j.evidence}`)});let ff={repository:[...a?.changed?[a.configPath]:[],...u?.changed?[u.configPath]:[],...be?.written.filter(j=>!j.startsWith(".git/hooks/"))??[]],checkout:[...new Set([...ee?.installed??[],...ee?.updated??[],...ee?.gitExcluded??[],...be?.written.filter(j=>j.startsWith(".git/hooks/"))??[]])],user:[...h.installed,...k.installed,...D.filter(j=>j.attempted).map(j=>`${j.binaryLabel} installer`)]},je={projectRoot:r,dbPath:o,configuredDbPath:i.dbPath,scipCliInstalled:g,languages:H.languages,steps:t,skills:h,astParsers:k,initialReadiness:x,indexerRemediation:D,readiness:H,capabilities:dn,freshness:wo,reindex:T,automaticRefreshConfig:u,watchService:N,rustSemanticSession:we,health:$o,smokeTests:un,healthDossier:null,hooks:ee,setupAgent:be,changeScopes:ff,filesWritten:be?.written??[],verdict:Ki(t,H)};if(e.runHealth===!1)return F(t,{id:"health-dossier",label:"Health dossier",status:"skipped",message:"Skipped because the optional health audit was not selected."}),je.verdict=Ki(t,H),je;let $e=uu(je,{dossierDir:e.dossierDir});return je.healthDossier=$e,je.changeScopes.repository.push(...$e.written),je.filesWritten=[...je.filesWritten,...$e.written],F(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]}),je.verdict=Ki(t,H),je}async function Mv(e){if(e.readiness.languages.length===0||e.configHasErrors)return F(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 Et({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=Oe(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.");F(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){F(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:jt(i),details:t})}return{reindexResult:n,freshness:r}}function _v(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 F(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",message:t}),null;try{let n=wn({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 F(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 F(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:jt(n)}),null}}function Su(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${Ui(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:"),zi("Repository records (commit)",e.changeScopes.repository),zi("Checkout preferences (do not commit)",e.changeScopes.checkout),zi("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 zi(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:Hv(e.steps),evidence:Wv(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?Gv(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:gu(e.readiness,e.freshness),evidence:hu(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:gu(e.readiness,e.freshness),evidence:hu(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:Uv(e.capabilities),evidence:Jv(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 Bv(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function Vv(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 Hv(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function Wv(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function Gv(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 gu(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function hu(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 Uv(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function Jv(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 zv(e,t,n){let r=[];if(t.languages.length===0)return F(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=et(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,d=!1;l?d=Sn(a,m=>c.push(m)):s.installed?c.push(s.note??`${s.binaryLabel} is installed but is not runnable.`):a.installMethods?.length||c.push(`No auto-install method is configured for ${s.binaryLabel}.`);let u=Kv(bn(a,e));r.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:d,before:s,after:u,messages:c,recovery:u.runnable?void 0:u.note??u.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(r.length===0)return F(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 F(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 Kv(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function Qv(e,t){if(!Fv(e)){let n="Skipped because no SQLite index database exists yet.";return F(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Qi(n)}try{let n=await An({full:!0,json:!0});return F(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),Xv(n)}catch(n){let r=jt(n);return F(t,{id:"health",label:"Health audit",status:"failed",message:r}),Qi(r)}}function Yv(e){let t="Skipped by setup choice; run `scip-query health --full` when wanted.";return F(e,{id:"health",label:"Health audit",status:"skipped",message:t}),Qi(t)}function Xv(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(Zv),warnings:e.warnings??[]}}function Zv(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 Qi(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function Ki(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 ex(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 tx(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 F(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function jt(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as nx}from"readline";function rx(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function ix(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 vu(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let r=rx(e);nx(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
339
+ `))}function Vd(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=Za(e.map(o=>o.scipPath),t);return Xd(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Ud(e[0].scipPath,t);return!1}function KS(e){let t;if(QS(e)){let i=ne(e.run.tempPaths.runDir,"typescript-affected.db");try{Yd(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();Hd(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=Ml({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),Ye(i,{force:!0}),Ye(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 Hd(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function QS(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 YS(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:gi(e.plan,o,e.projectFileCount)}}function Hd(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||Yd(e,r);let o=Un();if(!o)throw new Error("scip CLI is not available");gS(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 Yd(e,t){let n=Ya(e);Xd(n,t)}function Xd(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function en(e,t,n){let r=kS(e)||".scip",i=sr(e,r);return ne(V(e),`${i}.${n+1}.${t}${r}`)}async function XS(e,t){for(let n=0;n<2;n++){let r=ZS(e,t);if(r)return r;let i=ev(e);if(i&&tv(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await rv(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.`);Ye(e,{force:!0});continue}if(i&&!ht(i.pid)){Ye(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 ZS(e,t){let n;try{n=SS(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 RS(n,JSON.stringify(r)+`
340
+ `),()=>{try{yS(n)}finally{Ye(e,{force:!0})}}}function ev(e){try{let t=JSON.parse(lr(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 tv(e,t){return e?.kind==="manual-cli"&&nv(t?.trigger)}function nv(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function rv(e){return Wd(e,"SIGTERM"),await Gd(e,2e3)?!0:(Wd(e,"SIGKILL"),Gd(e,1e3))}function Wd(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function Gd(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!ht(e))return!0;await iv(50)}return!ht(e)}function iv(e){return new Promise(t=>setTimeout(t,e))}function ov(e,t,n){return Wo(e,t,n)}function Zd(e,t,n){return Object.fromEntries(t.map(r=>{let i=et(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Ho(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},s=r==="clojure"?sv(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&av(n),...o,clojureConfigPath:s,files:vn(e,{language:r,markerFiles:i})}]}))}function sv(e){return e?.trim()||void 0}function av(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Bi(e,t){return ne(V(e),"language-indexes",`${t}.scip`)}function eu(e){return ne(V(e),"language-indexes","typescript-projects")}function dr(e,t){return ne(eu(e),`${Ri(t)}.scip`)}function tn(e){try{return JSON.parse(lr(e,"utf-8"))}catch{return null}}function tu(e,t){try{let n=JSON.parse(lr(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 Vi(e,t){yt(e,t,{spacing:2,trailingNewline:!0})}function nu(e,t){try{let n=JSON.parse(lr(e,"utf-8"));if(n.version!==2&&n.version!==3)return;Vi(e,{...n,lastRefresh:t})}catch{}}function ur(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 Hi=864e5;function ru(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}`,u=i.get(d);u||(u={check:l.check,findingId:l.findingId,caughtAt:l.ts,events:[]},i.set(d,u)),u.events.push(l)}let o=[...i.values()].filter(l=>t.sinceMs===void 0||l.caughtAt>=t.sinceMs),s=cv(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 u=0,m=0,f=0,g=0,h=0,y=0,S=[];for(let k of d){f+=k.events.filter(_=>_.event==="reopened").length;let R=k.events[k.events.length-1],D=`${k.check}\0${k.findingId}`;if(R.event==="resolved"&&s.has(D))g+=1;else if(R.event==="resolved"){let _=Gt(k.events.slice(0,-1)),z=_?.comparisonBaseCommit??_?.commit,T=R.comparisonBaseCommit??R.commit;z&&(T===z||R.verifiedAgainstCommit===z)?(u+=1,S.push((R.ts-k.caughtAt)/Hi)):h+=1}else R.event==="suppressed"?m+=1:y+=1}let x=u+m;c.push({check:l,caught:d.length,fixed:u,suppressed:m,reopened:f,moved:g,unverified:h,open:y,precision:x>0?u/x:null,medianDaysToFix:S.length>0?lv(S):null})}return{totalEvents:r.length,windowStart:t.sinceMs??null,checks:c.sort((l,d)=>l.check.localeCompare(d.check))}}function cv(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 iu(e,t){let n=/^(\d+)([dw])$/.exec(e.trim());if(n){let i=Number(n[1]),o=n[2]==="w"?7*Hi:Hi;return t-i*o}let r=Date.parse(e);return Number.isNaN(r)?null:r}function lv(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 dv}from"child_process";import{statSync as uv}from"fs";import{isAbsolute as pv,join as mv,relative as fv}from"path";import{watch as gv}from"chokidar";import hv from"ignore";var pr=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=Pe(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=vt(t.projectRoot),this.extraIgnore=hv(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let t=gv(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=ou(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=pv(t)?t:mv(this.projectRoot,t);return fv(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=ou(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=fe(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=dv(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:a.indexPath,SCIP_REINDEX_OUTPUT_DB:a.dbPath,SCIP_REINDEX_LANGUAGES:(s.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(s.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:t.kind,SCIP_REINDEX_TRIGGER_DETAIL:t.detail??""},stdio:"pipe"});d.on("exit",u=>{u===0?n(Date.now()-i):r(new Error(`Reindex worker exited with code ${u}`))}),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=Nr(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n=Uo(this.projectRoot,t),r={head:Nr(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:n};try{let i=uv(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 ou(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}import{existsSync as Mv}from"fs";import{existsSync as au,mkdirSync as cu,readFileSync as lu,writeFileSync as du}from"fs";import{homedir as yv}from"os";import{dirname as uu,isAbsolute as bv,join as Wi,relative as su,resolve as Sv}from"path";function pu(e,t={}){let n=t.dossierDir?Sv(e.projectRoot,t.dossierDir):Wi(e.projectRoot,"docs","scip-query"),r={markdownPath:Wi(n,"health-dossier.md"),jsonPath:Wi(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},i=Tv({...e,generatedAt:new Date().toISOString(),healthDossier:r},e.projectRoot);try{return $v(r.markdownPath,vv(i),r),Pv(r.jsonPath,i,r),r}catch(o){return{...r,status:"failed",error:o instanceof Error?o.message:String(o)}}}function vv(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${Ui(e.health)}`,"","## Items That Need Attention","",...xv(e),"","## Blocked Or Unavailable Checks","",...Rv(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","",...kv(e),"","## JSON","",`Machine-readable report: \`${wv(e)}\``,""].join(`
341
+ `)}`}function xv(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 Rv(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 kv(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 Ui(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function wv(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function $v(e,t,n){if(cu(uu(e),{recursive:!0}),(au(e)?lu(e,"utf-8"):null)===t){n.unchanged.push(e);return}du(e,t),n.written.push(e)}function Pv(e,t,n){cu(uu(e),{recursive:!0});let r=`${JSON.stringify(t,null,2)}
342
+ `,i=au(e)?lu(e,"utf-8"):null;if(i&&Cv(i,r)){n.unchanged.push(e);return}du(e,r),n.written.push(e)}function Cv(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 Tv(e,t){return Gi(e,t)}function Gi(e,t){return typeof e=="string"?Iv(e,t):Array.isArray(e)?e.map(n=>Gi(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Gi(r,t)])):e}function Iv(e,t){if(e===t)return".";if(!bv(e))return e;let n=su(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let r=su(yv(),e).replace(/\\/g,"/");return r&&!r.startsWith("..")?`~/${r}`:e}return n}import{spawnSync as Ev}from"child_process";import{readFileSync as fu}from"fs";import{dirname as mu,join as jv,resolve as Lv}from"path";import{fileURLToPath as Av}from"url";var mr={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 Dv(e,t){let n=new Set(["tree-sitter"]);for(let r of e)for(let i of mr[r]?.packages??[])n.add(i);return[...n].filter(r=>t[r]).sort().map(r=>`${r}@${t[r]}`)}function Ji(e){return[...new Set(e.filter(t=>mr[t]!==void 0))].sort()}function gu(e,t={}){let n=t.runtime??Fv,r=t.packageRoot??Ov(),i=Ji(e),o=i.filter(u=>n.probe(mr[u].ast)),s=i.filter(u=>!o.includes(u));if(s.length===0)return{supportedLanguages:i,availableBefore:o,installed:[],availableAfter:o,unavailable:[],attempted:!1};let a=Nv(r),c=Dv(s,a),l=n.install(r,c);l.ok&&n.resetProbe();let d=i.filter(u=>n.probe(mr[u].ast));return{supportedLanguages:i,availableBefore:o,installed:l.ok?c:[],availableAfter:d,unavailable:i.filter(u=>!d.includes(u)),attempted:!0,...l.error?{error:l.error}:{}}}function Ov(){let e=mu(Av(import.meta.url));for(;;){let t=jv(e,"package.json");try{if(JSON.parse(fu(t,"utf8")).name==="scip-query")return e}catch{}let n=mu(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function Nv(e){return JSON.parse(fu(Lv(e,"package.json"),"utf8")).optionalDependencies??{}}var Fv={probe:e=>fn(e)==="ast",resetProbe:Co,install:(e,t)=>{let n=Ev(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 bu(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 Su(e={}){let t=[],n=Fe(),{projectRoot:r,paths:i,dbPath:o}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,a=e.languages?Ma(r,n.config,e.languages):null,c=a?.config??n.config,l=xt(c,{projectRoot:r}),d=l.filter(j=>j.level==="error"),u=null,m=null;if(d.length===0&&c.watch?.enabled!==s)try{u=_a(r,c,s)}catch(j){m=jt(j)}let f=u?.config??c,g=Kt();F(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?u?.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."),...u?{details:[u.configPath]}:{}}),F(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:[]}:Qn({quiet:!0});F(t,{id:"skills",label:"Agent skills",status:e.installSkills===!1?"skipped":h.skipped.length>0?"warn":"ok",message:e.installSkills===!1?"Skipped by setup choice.":`${h.installed.length} installed, ${h.alreadyLinked.length} already linked, ${h.pruned.length} pruned, ${h.skipped.length} skipped.`,details:[...h.pruned.map(j=>`Pruned ${j}`),...h.skipped.map(j=>`Skipped ${j}`)]});let y=u?xt(f,{projectRoot:r}):l,S=y.filter(j=>j.level==="error");F(t,{id:"config",label:"Project config",status:S.length>0?"failed":y.length>0?"warn":"ok",message:y.length===0?"Config OK.":`${y.length} diagnostic(s), ${S.length} error(s).`,details:y.map(j=>`${j.level.toUpperCase()} ${j.path}: ${j.message}`)});let x=he(r,f);F(t,{id:"readiness",label:"Indexer readiness",status:x.languages.length===0?"failed":x.indexers.some(j=>!j.runnable)?"warn":"ok",message:x.languages.length===0?"No supported project languages detected.":`Detected languages: ${x.languages.join(", ")}`,details:x.indexers.map(j=>`${j.runnable?"OK":j.installed?"WARN":"MISSING"} ${j.language}: ${j.binaryLabel}${j.note?` - ${j.note}`:""}`)});let k=e.installAstParsers===!1?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:gu(x.languages);F(t,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers===!1?"skipped":k.unavailable.length>0?"warn":"ok",message:e.installAstParsers===!1?"Skipped by setup choice.":k.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${k.availableAfter.length}/${k.supportedLanguages.length} selected language parser(s) available${k.installed.length>0?`; installed ${k.installed.join(", ")}`:""}.`,details:[...k.unavailable.length>0?[`Unavailable: ${k.unavailable.join(", ")}`]:[],...k.error?[k.error]:[]]});let R=e.installIndexers??!0,D=R?Kv(r,x,t):[];R||F(t,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped by guided setup choice."});let _=he(r,f),z=await _v({projectRoot:r,paths:i,config:f,readiness:_,configHasErrors:S.length>0,steps:t,onStatus:e.onStatus}),T=z.reindexResult,O=z.freshness,Z=Pe(f),N=qv({projectRoot:r,cacheDir:i.cacheDir,watchConfig:Z,readiness:_,configHasErrors:S.length>0,reindexResult:T,postReindexFreshness:O,steps:t}),H=he(r,f),dn=Je(H),wo=Oe(r,f,i);F(t,{id:"capabilities",label:"Capability matrix",status:tx(dn),message:nx(dn)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let $o=e.runHealth===!1?Xv(t):await Yv(i.dbPath,t),we=H.languages.includes("rust")?xn(r,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;F(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?F(t,{id:"project-hooks",label:"Project agent hooks",status:"skipped",message:"Skipped by --no-hooks."}):(ee=Tt(r),F(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(j=>`Checkout-local Git exclude: ${j}`),...ee.removed.map(j=>`Removed ${j}`),...ee.skipped.map(j=>`Skipped ${j.target}: ${j.reason}`),...ee.warnings]}))}catch(j){F(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:jt(j)})}let be=null;try{e.noAgentGuidance?F(t,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(be=Fn(r,{gitHook:e.gitHook}),F(t,{id:"agent-guidance",label:"Project agent guidance",status:be.skipped.length>0?"warn":"ok",message:`${be.written.length} written, ${be.unchanged.length} already wired, ${be.skipped.length} skipped.`,details:be.skipped.map(j=>`Skipped ${j.target}: ${j.reason}`)}))}catch(j){F(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:jt(j)})}let un=Bv({reindexResult:T,readiness:H,capabilities:dn,freshness:wo,health:$o,hooksResult:ee,agentResult:be,watchConfig:Z,watchService:N,rustSemanticSession:we,steps:t});F(t,{id:"smoke-tests",label:"Setup smoke tests",status:Vv(un),message:Hv(un),details:un.map(j=>`${j.command}: ${j.status} - ${j.evidence}`)});let gf={repository:[...a?.changed?[a.configPath]:[],...u?.changed?[u.configPath]:[],...be?.written.filter(j=>!j.startsWith(".git/hooks/"))??[]],checkout:[...new Set([...ee?.installed??[],...ee?.updated??[],...ee?.gitExcluded??[],...be?.written.filter(j=>j.startsWith(".git/hooks/"))??[]])],user:[...h.installed,...k.installed,...D.filter(j=>j.attempted).map(j=>`${j.binaryLabel} installer`)]},je={projectRoot:r,dbPath:o,configuredDbPath:i.dbPath,scipCliInstalled:g,languages:H.languages,steps:t,skills:h,astParsers:k,initialReadiness:x,indexerRemediation:D,readiness:H,capabilities:dn,freshness:wo,reindex:T,automaticRefreshConfig:u,watchService:N,rustSemanticSession:we,health:$o,smokeTests:un,healthDossier:null,hooks:ee,setupAgent:be,changeScopes:gf,filesWritten:be?.written??[],verdict:Ki(t,H)};if(e.runHealth===!1)return F(t,{id:"health-dossier",label:"Health dossier",status:"skipped",message:"Skipped because the optional health audit was not selected."}),je.verdict=Ki(t,H),je;let $e=pu(je,{dossierDir:e.dossierDir});return je.healthDossier=$e,je.changeScopes.repository.push(...$e.written),je.filesWritten=[...je.filesWritten,...$e.written],F(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]}),je.verdict=Ki(t,H),je}async function _v(e){if(e.readiness.languages.length===0||e.configHasErrors)return F(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 Et({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=Oe(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.");F(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){F(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:jt(i),details:t})}return{reindexResult:n,freshness:r}}function qv(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 F(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",message:t}),null;try{let n=wn({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 F(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 F(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:jt(n)}),null}}function vu(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${Ui(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:"),zi("Repository records (commit)",e.changeScopes.repository),zi("Checkout preferences (do not commit)",e.changeScopes.checkout),zi("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 zi(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function Bv(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:Wv(e.steps),evidence:Gv(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?Uv(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:hu(e.readiness,e.freshness),evidence:yu(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:hu(e.readiness,e.freshness),evidence:yu(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:Jv(e.capabilities),evidence:zv(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 Vv(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function Hv(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 Wv(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function Gv(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function Uv(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 hu(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function yu(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 Jv(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function zv(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 Kv(e,t,n){let r=[];if(t.languages.length===0)return F(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=et(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,d=!1;l?d=Sn(a,m=>c.push(m)):s.installed?c.push(s.note??`${s.binaryLabel} is installed but is not runnable.`):a.installMethods?.length||c.push(`No auto-install method is configured for ${s.binaryLabel}.`);let u=Qv(bn(a,e));r.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:d,before:s,after:u,messages:c,recovery:u.runnable?void 0:u.note??u.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(r.length===0)return F(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 F(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 Qv(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function Yv(e,t){if(!Mv(e)){let n="Skipped because no SQLite index database exists yet.";return F(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Qi(n)}try{let n=await An({full:!0,json:!0});return F(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),Zv(n)}catch(n){let r=jt(n);return F(t,{id:"health",label:"Health audit",status:"failed",message:r}),Qi(r)}}function Xv(e){let t="Skipped by setup choice; run `scip-query health --full` when wanted.";return F(e,{id:"health",label:"Health audit",status:"skipped",message:t}),Qi(t)}function Zv(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(ex),warnings:e.warnings??[]}}function ex(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 Qi(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function Ki(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 tx(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 nx(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 F(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function jt(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as rx}from"readline";function ix(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function ox(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 xu(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let r=ix(e);rx(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,u)=>{if(u.ctrl&&u.name==="c"){l(),a(new Error("Setup cancelled."));return}if(u.name==="return"||u.name==="enter"){l(),n.write(`
347
- `),s(r.selected);return}let m=u.name==="up"?"up":u.name==="down"?"down":u.name==="space"?"toggle":null;m&&(r=ix(r,m,e),o())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!i),t.pause()}}import{existsSync as xu,mkdirSync as ox,writeFileSync as sx}from"fs";import{dirname as ax,join as Ru}from"path";function ku(e,t={}){let n=Ru(e,".github","workflows","scip-query.yml"),r=cx({hasNpmProject:xu(Ru(e,"package.json"))});return xu(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(ox(ax(n),{recursive:!0}),sx(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function cx(e){let t=`scip-query@${Ne}`;return`name: scip-query
347
+ `),s(r.selected);return}let m=u.name==="up"?"up":u.name==="down"?"down":u.name==="space"?"toggle":null;m&&(r=ox(r,m,e),o())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!i),t.pause()}}import{existsSync as Ru,mkdirSync as sx,writeFileSync as ax}from"fs";import{dirname as cx,join as ku}from"path";function wu(e,t={}){let n=ku(e,".github","workflows","scip-query.yml"),r=lx({hasNpmProject:Ru(ku(e,"package.json"))});return Ru(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(sx(cx(n),{recursive:!0}),ax(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function lx(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 lx}from"fs";import{join as fr}from"path";function wu(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=bl({dryRun:e.dryRun,homeDir:e.homeDir})),o&&(s.project=dx(e.projectRoot,{dryRun:e.dryRun})),s}function dx(e,t={}){return{hooks:Tt(e,{remove:!0,dryRun:t.dryRun}),agentSetup:_c(e,{dryRun:t.dryRun}),left:ux(e)}}function ux(e){return[[".scipquery.json",fr(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",fr(e,".scipquery","suppressions")],[".scipquery/ledger/ (repository records)",fr(e,".scipquery","ledger")],["docs/scip-query/",fr(e,"docs","scip-query")]].filter(([,t])=>lx(t)).map(([t])=>t)}import{existsSync as px,readFileSync as mx}from"fs";import{createRequire as fx}from"module";import hr from"path";import{performance as gr}from"perf_hooks";var gx=fx(import.meta.url),nn;function Iu(e){let t=hx();if(!t)return $n("typescript is not installed");let n=ts(e);if(n.length===0)return $n("no tsconfig found");try{return new Yi(e.config.projectRoot,t,n.map(r=>yx(t,r)))}catch(r){return $n(r instanceof Error?r.message:String(r),n[0],n)}}function Eu(e,t,n){let r=gr.now(),i=$u(t,e),o=gr.now()-r,s=gr.now(),a=$u(n,e),c=gr.now()-s,l=[],d=0,u=0,m=0,f=0,g=0;for(let h of e){let y=i.get(h.symbolId)??[],S=a.get(h.symbolId)??[];u+=y.length,m+=S.length;let x=Pu(y),k=Pu(S),R=Cu(y,k),D=Cu(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:u,candidateReferenceCount:m,baselineMs:Number(o.toFixed(3)),candidateMs:Number(c.toFixed(3)),mismatches:l}}var Yi=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=hr.join(this.projectRoot,t.relativePath),r=this.bundleForFile(n);if(!r)return[];let i=r.service.getProgram()?.getSourceFile(n);if(!i)return[];let o=Sx(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=vx(this.ts,r.service,this.projectRoot,l);d&&(d.file===t.relativePath&&d.line>=t.startLine&&d.line<=t.endLine||a.push(d))}return Zo(a)}bundleForFile(t){let n=Lu(t);return this.bundles.find(r=>r.files.has(n))??null}};function hx(){if(nn!==void 0)return nn;try{nn=gx("typescript")}catch{nn=null}return nn}function yx(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(Tu(e,n.error));let r=e.parseJsonConfigFileContent(n.config,e.sys,hr.dirname(t));if(r.errors.length>0)throw new Error(r.errors.map(s=>Tu(e,s)).join(`
376
- `));let i=new Set(r.fileNames.map(Lu)),o=e.createLanguageService(bx(e,r),e.createDocumentRegistry());return{tsconfigPath:t,service:o,files:i}}function bx(e,t){return{getCompilationSettings:()=>t.options,getCurrentDirectory:()=>t.options.configFilePath?hr.dirname(String(t.options.configFilePath)):process.cwd(),getDefaultLibFileName:n=>e.getDefaultLibFilePath(n),getDirectories:e.sys.getDirectories,getScriptFileNames:()=>t.fileNames,getScriptSnapshot:n=>{if(px(n))return e.ScriptSnapshot.fromString(mx(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 Sx(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 vx(e,t,n,r){let i=es(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 $u(e,t){return e.referencesForDefinitions?e.referencesForDefinitions(t):new Map(t.map(n=>[n.symbolId,e.referencesFor(n)]))}function Pu(e){return new Set(e.map(ju))}function Cu(e,t){return e.filter(n=>!t.has(ju(n)))}function ju(e){return`${e.file}:${e.line}:${e.column}`}function Lu(e){return hr.resolve(e).replace(/\\/g,"/")}function Tu(e,t){return e.flattenDiagnosticMessageText(t.messageText,`
378
- `)}import{readFileSync as xx}from"fs";function Au(e){let t=[];for(let[n,r]of xx(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 Du(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,u=0;for(let[y,S]of e.entries()){let x=ye(S.name)??ye(S.phase),k=Tx(S.durationMs),R=ye(S.runId);x&&k!==null&&(l+=1,s.add(x),R&&o.add(R),Rx(i,S,x,k),kx(r,S,x,k,R),ye(S.subsystemWorkIdentity)&&c.add(x));let D=ye(S.workIdentity);if(!D)continue;d+=1,x&&a.add(x);let _=Cx(S.workOutcome);if(!x||k===null||!_){u+=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:ye(S.command)??"unknown",durationMs:k,outcome:_}),n.set(T,O)}let m=[...n.values()].map(Px).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(wx).filter(y=>y!==null).sort((y,S)=>S.laterRunMs-y.laterRunMs||S.laterRunEvents-y.laterRunEvents||y.spanName.localeCompare(S.spanName)),g=[...i.values()].map($x).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:u,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 Ou(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 dx}from"fs";import{join as fr}from"path";function $u(e){let t=e.global===!0,n=e.project===!0,r=!t&&!n,i=t||r,o=n||r,s={dryRun:e.dryRun===!0};return i&&(s.global=Sl({dryRun:e.dryRun,homeDir:e.homeDir})),o&&(s.project=ux(e.projectRoot,{dryRun:e.dryRun})),s}function ux(e,t={}){return{hooks:Tt(e,{remove:!0,dryRun:t.dryRun}),agentSetup:qc(e,{dryRun:t.dryRun}),left:px(e)}}function px(e){return[[".scipquery.json",fr(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",fr(e,".scipquery","suppressions")],[".scipquery/ledger/ (repository records)",fr(e,".scipquery","ledger")],["docs/scip-query/",fr(e,"docs","scip-query")]].filter(([,t])=>dx(t)).map(([t])=>t)}import{existsSync as mx,readFileSync as fx}from"fs";import{createRequire as gx}from"module";import hr from"path";import{performance as gr}from"perf_hooks";var hx=gx(import.meta.url),nn;function Eu(e){let t=yx();if(!t)return $n("typescript is not installed");let n=ns(e);if(n.length===0)return $n("no tsconfig found");try{return new Yi(e.config.projectRoot,t,n.map(r=>bx(t,r)))}catch(r){return $n(r instanceof Error?r.message:String(r),n[0],n)}}function ju(e,t,n){let r=gr.now(),i=Pu(t,e),o=gr.now()-r,s=gr.now(),a=Pu(n,e),c=gr.now()-s,l=[],d=0,u=0,m=0,f=0,g=0;for(let h of e){let y=i.get(h.symbolId)??[],S=a.get(h.symbolId)??[];u+=y.length,m+=S.length;let x=Cu(y),k=Cu(S),R=Tu(y,k),D=Tu(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:u,candidateReferenceCount:m,baselineMs:Number(o.toFixed(3)),candidateMs:Number(c.toFixed(3)),mismatches:l}}var Yi=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=hr.join(this.projectRoot,t.relativePath),r=this.bundleForFile(n);if(!r)return[];let i=r.service.getProgram()?.getSourceFile(n);if(!i)return[];let o=vx(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=xx(this.ts,r.service,this.projectRoot,l);d&&(d.file===t.relativePath&&d.line>=t.startLine&&d.line<=t.endLine||a.push(d))}return es(a)}bundleForFile(t){let n=Au(t);return this.bundles.find(r=>r.files.has(n))??null}};function yx(){if(nn!==void 0)return nn;try{nn=hx("typescript")}catch{nn=null}return nn}function bx(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(Iu(e,n.error));let r=e.parseJsonConfigFileContent(n.config,e.sys,hr.dirname(t));if(r.errors.length>0)throw new Error(r.errors.map(s=>Iu(e,s)).join(`
376
+ `));let i=new Set(r.fileNames.map(Au)),o=e.createLanguageService(Sx(e,r),e.createDocumentRegistry());return{tsconfigPath:t,service:o,files:i}}function Sx(e,t){return{getCompilationSettings:()=>t.options,getCurrentDirectory:()=>t.options.configFilePath?hr.dirname(String(t.options.configFilePath)):process.cwd(),getDefaultLibFileName:n=>e.getDefaultLibFilePath(n),getDirectories:e.sys.getDirectories,getScriptFileNames:()=>t.fileNames,getScriptSnapshot:n=>{if(mx(n))return e.ScriptSnapshot.fromString(fx(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 vx(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 xx(e,t,n,r){let i=ts(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 Pu(e,t){return e.referencesForDefinitions?e.referencesForDefinitions(t):new Map(t.map(n=>[n.symbolId,e.referencesFor(n)]))}function Cu(e){return new Set(e.map(Lu))}function Tu(e,t){return e.filter(n=>!t.has(Lu(n)))}function Lu(e){return`${e.file}:${e.line}:${e.column}`}function Au(e){return hr.resolve(e).replace(/\\/g,"/")}function Iu(e,t){return e.flattenDiagnosticMessageText(t.messageText,`
378
+ `)}import{readFileSync as Rx}from"fs";function Du(e){let t=[];for(let[n,r]of Rx(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 Ou(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,u=0;for(let[y,S]of e.entries()){let x=ye(S.name)??ye(S.phase),k=Ix(S.durationMs),R=ye(S.runId);x&&k!==null&&(l+=1,s.add(x),R&&o.add(R),kx(i,S,x,k),wx(r,S,x,k,R),ye(S.subsystemWorkIdentity)&&c.add(x));let D=ye(S.workIdentity);if(!D)continue;d+=1,x&&a.add(x);let _=Tx(S.workOutcome);if(!x||k===null||!_){u+=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:ye(S.command)??"unknown",durationMs:k,outcome:_}),n.set(T,O)}let m=[...n.values()].map(Cx).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($x).filter(y=>y!==null).sort((y,S)=>S.laterRunMs-y.laterRunMs||S.laterRunEvents-y.laterRunEvents||y.spanName.localeCompare(S.spanName)),g=[...i.values()].map(Px).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:u,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 Nu(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 Rx(e,t,n,r){let i=ye(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),ye(t.subsystemWorkIdentity)&&(o.workloadIdentifiedEvents+=1,o.workloadIdentifiedSpanNames.add(n)),ye(t.workIdentity)&&(o.exactIdentifiedEvents+=1,o.exactIdentifiedSpanNames.add(n)),e.set(i,o)}function kx(e,t,n,r,i){let o=ye(t.subsystemWorkIdentity);if(!o||!i||t.workloadIdentityKind!=="published-project")return;let s=ye(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:ye(t.command)??"unknown",durationMs:r}),e.set(a,c)}function wx(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:Lt(e.observations.map(o=>o.durationMs)),firstRunMs:Lt(r.map(o=>o.durationMs)),laterRunMs:Lt(i.map(o=>o.durationMs))}}function $x(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 Px(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=Lt(r.flatMap(a=>a.slice(1).map(c=>c.durationMs))),o=Lt(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:Lt(t.map(a=>a.durationMs)),firstComputeMs:t[0]?.durationMs??0,withinRunAvoidableMs:i,crossRunRecomputeMs:o,estimatedAvoidableMs:i+o,cacheHits:yr(e.observations,"cache-hit"),cacheMisses:yr(e.observations,"cache-miss"),reused:yr(e.observations,"reused"),skipped:yr(e.observations,"skipped")}}function Cx(e){switch(e){case"computed":case"cache-hit":case"cache-miss":case"reused":case"skipped":return e;default:return null}}function yr(e,t){return e.filter(n=>n.outcome===t).length}function Tx(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function ye(e){return typeof e=="string"&&e.length>0?e:null}function Lt(e){return e.reduce((t,n)=>t+n,0)}var Nu={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 Fu(e,t){let n=Ix(t);return{...e,warnings:[...e.warnings??[],Nu.note,...n],capabilities:t,scoreInterpretation:Nu}}function Ix(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 Fx=new Set(Oa),Mx=18e4,Bu=100*1024*1024,_x=new Set(To),qx=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],Bx=[["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 Vx(e){return e.filter(t=>Fx.has(t))}async function Vu(e){let t=G(e),n=Y(),r=fe(n),i=De(n,r),o=b(t,"json");try{let s=Vx(wt(t,"language")),a=await Et({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 Hu(){let e=Y(),t=Rt(e);try{let n=Xn({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 Wu(e){let t=G(e),n=Y(),r=Rt(n);try{let i=Fi({projectRoot:n,dbPath:r,tsconfig:w(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${i.vueFiles}; resolved references: ${i.resolvedReferences}; inserted mentions: ${i.insertedMentions}; not-inserted identifier tokens: ${i.skippedReferences}; synthetic symbols: ${i.syntheticSymbols}.`),console.log(`Not inserted by reason: no definition ${i.skippedReferenceReasons["no-definition"]}; same-file definition ${i.skippedReferenceReasons["same-file-definition"]}; unindexed definition ${i.skippedReferenceReasons["unindexed-definition"]}; missing source ${i.skippedReferenceReasons["missing-source-file"]}; missing service script ${i.skippedReferenceReasons["missing-service-script"]}. Samples: ${i.skippedReferenceSamples.length} omitted, ${i.resolvedReferenceSamples.length} resolved.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}}function Gu(e){let t=G(e);le(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=Zs(n,{base:w(t,"base")}),o=ea(n,r,i.changedFiles,i.changedRanges);console.log(JSON.stringify(o))})}async function Uu(e){let t=G(e);try{let n=await ac({base:w(t,"base")});if(b(t,"json")){I("diff-impact",[],t,n);return}cc(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Ju(e,t){let n=G(t),r=String(e).split(",").filter(i=>i.length>0);le(i=>{let o=[];for(let c of r)Ta.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:w(n,"scope"),full:b(n,"full")},a=o.length===1?Ia(i,o[0],s):Ea(i,o,s);console.log(JSON.stringify(a))})}async function zu(e){let t=G(e);if(b(t,"writeBaseline")||b(t,"baseline")){nR(t);return}try{let n=await An({scope:w(t,"scope"),full:b(t,"full"),json:b(t,"json")}),{projectRoot:r,config:i,dbPath:o}=Fe(),s=Je(he(r,i),{hasIndexedGraph:ke(o)}),a=Fu(n,s);if(b(t,"json")){I("health",[],t,a);return}sc(a,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function Ku(e){let t=G(e),n=Y(),r=U(t,"timeoutMs")??Mx,i=b(t,"progress"),o=b(t,"profile"),s=w(t,"profileOut"),a={projectRoot:n,...Xx(n),index:Xi(ke(Rt(n))),commands:[]};b(t,"coldIndex")&&(At(i,"cold index started"),a.coldIndex=await Hx(n),At(i,`cold index finished ${a.coldIndex.durationMs}ms`),Mt({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),At(i,"warm index started"),a.warmIndex=await Jx(n),At(i,`warm index finished ${a.warmIndex.durationMs}ms`),Mt({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=Xi(ke(Rt(n))));for(let c of zx(t))a.commands.push(Qx(n,c,r,{progress:i,profile:o,profileOut:s}));if(b(t,"json")){I("bench",[],t,a);return}Zx(a)}function Qu(e,t){let n=G(t),r=Nx(String(e)),i=Du(Au(r),{top:U(n,"top")??20});if(b(n,"json")){I("work-audit",[r],n,{profilePath:r,...i});return}process.stdout.write(Ou(i,r))}function Yu(e){let t=G(e);le(n=>{let r=n.config.projectRoot,i=w(t,"scope")??null,o=b(t,"full"),s=U(t,"limit")??200,a=Math.max(0,U(t,"maxMismatches")??10),c=Ao(n).filter(k=>_t(k.relativePath)).filter(k=>!n.isIgnored(k.relativePath)).sort(tR),l=i?c.filter(k=>k.relativePath.includes(i)):c,d=o?l:l.slice(0,s),u=Xe.now(),m=rs(n),f=Number((Xe.now()-u).toFixed(3)),g=Xe.now(),h=Iu(n),y=Number((Xe.now()-g).toFixed(3)),S=Eu(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}eR(x)})}async function Hx(e){let t=fe(e),n=De(e,t),r=br(n.dbPath),i=`${r}.bench-backup-${Date.now()}`;Wx(r);let o=Gx(r,i);try{let s=await Xu(()=>Et({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 Mu(r,i,o,"discard-backup"),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...Zu(e)}}catch(s){throw Mu(r,i,o,"restore-backup"),s}}var Zi={existsSync:ke,readFileSync:Ex,writeFileSync:Dx,renameSync:jx,rmSync:Lx,unlinkSync:Ax};function eo(e){return ut(br(e),"bench-restore.json")}function Wx(e,t=Zi){let n=eo(e);if(!t.existsSync(n))return!1;let r=Ux(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 Gx(e,t,n=Zi){return n.existsSync(e)?(n.writeFileSync(eo(e),JSON.stringify({originalPath:e,backupPath:t})),n.renameSync(e,t),!0):!1}function Mu(e,t,n,r,i=Zi){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=eo(e);i.existsSync(o)&&i.unlinkSync(o)}function Ux(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 Jx(e){let t=fe(e),n=De(e,t),r=await Xu(()=>Et({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,...Zu(e)}}async function Xu(e){let t=Xe.now(),n=await e();return{durationMs:Math.round(Xe.now()-t),value:n}}function Zu(e){return ke(Rt(e))?le(t=>{let n=bt(t);return{files:n.documents,symbols:n.symbols}}):{}}function zx(e){let t=wt(e,"command");return t.length>0?t.map(Kx).filter(n=>n.length>0):[...qx.map(n=>[...n]),...b(e,"includeHeavy")?Bx.map(n=>[...n]):[]]}function Kx(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function Qx(e,t,n,r={}){let i=`scip-query ${t.join(" ")}`;At(r.progress,`${i} started`),Mt({type:"bench-command-start",command:i,projectRoot:e},r.profileOut);let o=Xe.now(),s={...r.profile?Yx(i,r.profileOut):process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"},a=qu(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:Bu,timeout:n}),c=Math.round(Xe.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 At(r.progress,`${i} finished ${c}ms exit=${l.exitCode??l.signal??"unknown"}${l.timedOut?" timed-out":""}`),Mt({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 At(e,t){e&&process.stderr.write(`[bench] ${t}
382
- `)}function Yx(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function Xx(e){let t=qu("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:Bu});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=>_x.has(Ox(r).toLowerCase())).length}}function Zx(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, ${Ue(e.index.indexSizeBytes)}`),e.coldIndex&&_u("Cold index",e.coldIndex),e.warmIndex&&_u("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 _u(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function eR(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 tR(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||(e.startChar??0)-(t.startChar??0)||e.symbolId-t.symbolId}function nR(e){let t=w(e,"scope");le(n=>{if(b(e,"writeBaseline")){let i=ca(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=la(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 ep(){let e=Qn(),t=e.installed.length+e.alreadyLinked.length;console.log(`
386
- ${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.pruned.length} pruned, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function tp(e){let t=G(e),n=Y(),r=Tt(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(`
381
+ `}function kx(e,t,n,r){let i=ye(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),ye(t.subsystemWorkIdentity)&&(o.workloadIdentifiedEvents+=1,o.workloadIdentifiedSpanNames.add(n)),ye(t.workIdentity)&&(o.exactIdentifiedEvents+=1,o.exactIdentifiedSpanNames.add(n)),e.set(i,o)}function wx(e,t,n,r,i){let o=ye(t.subsystemWorkIdentity);if(!o||!i||t.workloadIdentityKind!=="published-project")return;let s=ye(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:ye(t.command)??"unknown",durationMs:r}),e.set(a,c)}function $x(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:Lt(e.observations.map(o=>o.durationMs)),firstRunMs:Lt(r.map(o=>o.durationMs)),laterRunMs:Lt(i.map(o=>o.durationMs))}}function Px(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 Cx(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=Lt(r.flatMap(a=>a.slice(1).map(c=>c.durationMs))),o=Lt(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:Lt(t.map(a=>a.durationMs)),firstComputeMs:t[0]?.durationMs??0,withinRunAvoidableMs:i,crossRunRecomputeMs:o,estimatedAvoidableMs:i+o,cacheHits:yr(e.observations,"cache-hit"),cacheMisses:yr(e.observations,"cache-miss"),reused:yr(e.observations,"reused"),skipped:yr(e.observations,"skipped")}}function Tx(e){switch(e){case"computed":case"cache-hit":case"cache-miss":case"reused":case"skipped":return e;default:return null}}function yr(e,t){return e.filter(n=>n.outcome===t).length}function Ix(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function ye(e){return typeof e=="string"&&e.length>0?e:null}function Lt(e){return e.reduce((t,n)=>t+n,0)}var Fu={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 Mu(e,t){let n=Ex(t);return{...e,warnings:[...e.warnings??[],Fu.note,...n],capabilities:t,scoreInterpretation:Fu}}function Ex(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 Mx=new Set(Na),_x=18e4,Vu=100*1024*1024,qx=new Set(To),Bx=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],Vx=[["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 Hx(e){return e.filter(t=>Mx.has(t))}async function Hu(e){let t=G(e),n=Y(),r=fe(n),i=De(n,r),o=b(t,"json");try{let s=Hx(wt(t,"language")),a=await Et({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 Wu(){let e=Y(),t=Rt(e);try{let n=Xn({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 Gu(e){let t=G(e),n=Y(),r=Rt(n);try{let i=Fi({projectRoot:n,dbPath:r,tsconfig:w(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${i.vueFiles}; resolved references: ${i.resolvedReferences}; inserted mentions: ${i.insertedMentions}; not-inserted identifier tokens: ${i.skippedReferences}; synthetic symbols: ${i.syntheticSymbols}.`),console.log(`Not inserted by reason: no definition ${i.skippedReferenceReasons["no-definition"]}; same-file definition ${i.skippedReferenceReasons["same-file-definition"]}; unindexed definition ${i.skippedReferenceReasons["unindexed-definition"]}; missing source ${i.skippedReferenceReasons["missing-source-file"]}; missing service script ${i.skippedReferenceReasons["missing-service-script"]}. Samples: ${i.skippedReferenceSamples.length} omitted, ${i.resolvedReferenceSamples.length} resolved.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}}function Uu(e){let t=G(e);le(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=ea(n,{base:w(t,"base")}),o=ta(n,r,i.changedFiles,i.changedRanges);console.log(JSON.stringify(o))})}async function Ju(e){let t=G(e);try{let n=await cc({base:w(t,"base")});if(b(t,"json")){I("diff-impact",[],t,n);return}lc(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function zu(e,t){let n=G(t),r=String(e).split(",").filter(i=>i.length>0);le(i=>{let o=[];for(let c of r)Ia.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:w(n,"scope"),full:b(n,"full")},a=o.length===1?Ea(i,o[0],s):ja(i,o,s);console.log(JSON.stringify(a))})}async function Ku(e){let t=G(e);if(b(t,"writeBaseline")||b(t,"baseline")){rR(t);return}try{let n=await An({scope:w(t,"scope"),full:b(t,"full"),json:b(t,"json")}),{projectRoot:r,config:i,dbPath:o}=Fe(),s=Je(he(r,i),{hasIndexedGraph:ke(o)}),a=Mu(n,s);if(b(t,"json")){I("health",[],t,a);return}ac(a,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function Qu(e){let t=G(e),n=Y(),r=U(t,"timeoutMs")??_x,i=b(t,"progress"),o=b(t,"profile"),s=w(t,"profileOut"),a={projectRoot:n,...Zx(n),index:Xi(ke(Rt(n))),commands:[]};b(t,"coldIndex")&&(At(i,"cold index started"),a.coldIndex=await Wx(n),At(i,`cold index finished ${a.coldIndex.durationMs}ms`),Mt({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),At(i,"warm index started"),a.warmIndex=await zx(n),At(i,`warm index finished ${a.warmIndex.durationMs}ms`),Mt({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=Xi(ke(Rt(n))));for(let c of Kx(t))a.commands.push(Yx(n,c,r,{progress:i,profile:o,profileOut:s}));if(b(t,"json")){I("bench",[],t,a);return}eR(a)}function Yu(e,t){let n=G(t),r=Fx(String(e)),i=Ou(Du(r),{top:U(n,"top")??20});if(b(n,"json")){I("work-audit",[r],n,{profilePath:r,...i});return}process.stdout.write(Nu(i,r))}function Xu(e){let t=G(e);le(n=>{let r=n.config.projectRoot,i=w(t,"scope")??null,o=b(t,"full"),s=U(t,"limit")??200,a=Math.max(0,U(t,"maxMismatches")??10),c=Ao(n).filter(k=>_t(k.relativePath)).filter(k=>!n.isIgnored(k.relativePath)).sort(nR),l=i?c.filter(k=>k.relativePath.includes(i)):c,d=o?l:l.slice(0,s),u=Xe.now(),m=is(n),f=Number((Xe.now()-u).toFixed(3)),g=Xe.now(),h=Eu(n),y=Number((Xe.now()-g).toFixed(3)),S=ju(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}tR(x)})}async function Wx(e){let t=fe(e),n=De(e,t),r=br(n.dbPath),i=`${r}.bench-backup-${Date.now()}`;Gx(r);let o=Ux(r,i);try{let s=await Zu(()=>Et({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 _u(r,i,o,"discard-backup"),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...ep(e)}}catch(s){throw _u(r,i,o,"restore-backup"),s}}var Zi={existsSync:ke,readFileSync:jx,writeFileSync:Ox,renameSync:Lx,rmSync:Ax,unlinkSync:Dx};function eo(e){return ut(br(e),"bench-restore.json")}function Gx(e,t=Zi){let n=eo(e);if(!t.existsSync(n))return!1;let r=Jx(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 Ux(e,t,n=Zi){return n.existsSync(e)?(n.writeFileSync(eo(e),JSON.stringify({originalPath:e,backupPath:t})),n.renameSync(e,t),!0):!1}function _u(e,t,n,r,i=Zi){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=eo(e);i.existsSync(o)&&i.unlinkSync(o)}function Jx(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 zx(e){let t=fe(e),n=De(e,t),r=await Zu(()=>Et({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,...ep(e)}}async function Zu(e){let t=Xe.now(),n=await e();return{durationMs:Math.round(Xe.now()-t),value:n}}function ep(e){return ke(Rt(e))?le(t=>{let n=bt(t);return{files:n.documents,symbols:n.symbols}}):{}}function Kx(e){let t=wt(e,"command");return t.length>0?t.map(Qx).filter(n=>n.length>0):[...Bx.map(n=>[...n]),...b(e,"includeHeavy")?Vx.map(n=>[...n]):[]]}function Qx(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function Yx(e,t,n,r={}){let i=`scip-query ${t.join(" ")}`;At(r.progress,`${i} started`),Mt({type:"bench-command-start",command:i,projectRoot:e},r.profileOut);let o=Xe.now(),s={...r.profile?Xx(i,r.profileOut):process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"},a=Bu(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:Vu,timeout:n}),c=Math.round(Xe.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 At(r.progress,`${i} finished ${c}ms exit=${l.exitCode??l.signal??"unknown"}${l.timedOut?" timed-out":""}`),Mt({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 At(e,t){e&&process.stderr.write(`[bench] ${t}
382
+ `)}function Xx(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function Zx(e){let t=Bu("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:Vu});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=>qx.has(Nx(r).toLowerCase())).length}}function eR(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, ${Ue(e.index.indexSizeBytes)}`),e.coldIndex&&qu("Cold index",e.coldIndex),e.warmIndex&&qu("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 qu(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function tR(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 nR(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||(e.startChar??0)-(t.startChar??0)||e.symbolId-t.symbolId}function rR(e){let t=w(e,"scope");le(n=>{if(b(e,"writeBaseline")){let i=la(n,{scope:t});console.log(`Baseline written to ${i.path} (${i.findingCount} finding(s)).`);return}let r=da(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 tp(){let e=Qn(),t=e.installed.length+e.alreadyLinked.length;console.log(`
386
+ ${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.pruned.length} pruned, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function np(e){let t=G(e),n=Y(),r=Tt(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
- No project-local hook config was written.`)}function np(){let e=!1;Kt()?console.log("scip CLI: installed"):(ui(),e=!0);let t=Y(),n=fe(t),r=he(t,n);if(r.languages.length===0){console.log(`
388
+ No project-local hook config was written.`)}function rp(){let e=!1;Kt()?console.log("scip CLI: installed"):(ui(),e=!0);let t=Y(),n=fe(t),r=he(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
- 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=vp(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}: ${pR(o)}${xp(o)}`),o.reason&&console.log(` ${o.reason}`)}process.exitCode=e?1:0}function rp(e){op(e,"capabilities")}function ip(e){b(G(e),"json")||console.error('note: capability-matrix is deprecated; use "scip-query capabilities --matrix".'),op(e,"capability-matrix")}function op(e,t){let n=G(e),{projectRoot:r,config:i,paths:o,dbPath:s}=Fe(),a=he(r,i),c=Oe(r,i,o),l=Je(a,{hasIndexedGraph:ke(s)&&c.state!=="missing"});if(b(n,"json")){I(t,[],n,l);return}to(l)}function sp(){let e=Y(),t=tt(e),n=Na(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function ap(e){let t=G(e),n=Y(),r=fe(n),i=xt(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 cp(e,t){let n=G(t),r=w(n,"reason");if(!r||r.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let i=pa(Y(),{id:String(e),check:w(n,"check"),file:w(n,"file"),reason:r,expiresAt:w(n,"expiresAt")});if(b(n,"json")){I("suppress",[String(e)],n,i);return}console.log(`Suppression written to ${i.path}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exitCode=1}}function lp(e){let t=G(e),n=Date.now(),r=w(t,"since"),i;if(r){let y=ru(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=Vn(o),a=nu(s,{sinceMs:i,check:w(t,"check")});if(b(t,"json")){I("effectiveness",[],t,a);return}if(a.checks.length===0){console.log(s.length===0?`No outcome events recorded yet (${ut(Bn,"*.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))),u=y=>y.map((S,x)=>S.padEnd(d[x])).join(" ");console.log(u(c));for(let y of l)console.log(u(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(`
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=xp(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}: ${mR(o)}${Rp(o)}`),o.reason&&console.log(` ${o.reason}`)}process.exitCode=e?1:0}function ip(e){sp(e,"capabilities")}function op(e){b(G(e),"json")||console.error('note: capability-matrix is deprecated; use "scip-query capabilities --matrix".'),sp(e,"capability-matrix")}function sp(e,t){let n=G(e),{projectRoot:r,config:i,paths:o,dbPath:s}=Fe(),a=he(r,i),c=Oe(r,i,o),l=Je(a,{hasIndexedGraph:ke(s)&&c.state!=="missing"});if(b(n,"json")){I(t,[],n,l);return}to(l)}function ap(){let e=Y(),t=tt(e),n=Fa(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function cp(e){let t=G(e),n=Y(),r=fe(n),i=xt(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 lp(e,t){let n=G(t),r=w(n,"reason");if(!r||r.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let i=ma(Y(),{id:String(e),check:w(n,"check"),file:w(n,"file"),reason:r,expiresAt:w(n,"expiresAt")});if(b(n,"json")){I("suppress",[String(e)],n,i);return}console.log(`Suppression written to ${i.path}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exitCode=1}}function dp(e){let t=G(e),n=Date.now(),r=w(t,"since"),i;if(r){let y=iu(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=Vn(o),a=ru(s,{sinceMs:i,check:w(t,"check")});if(b(t,"json")){I("effectiveness",[],t,a);return}if(a.checks.length===0){console.log(s.length===0?`No outcome events recorded yet (${ut(Bn,"*.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))),u=y=>y.map((S,x)=>S.padEnd(d[x])).join(" ");console.log(u(c));for(let y of l)console.log(u(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 dp(e){let t=G(e),{report:n,hasIndexerProblems:r,hasErrors:i}=up("doctor");b(t,"json")?I("doctor",[],t,n):cR(n,r),process.exitCode=i?1:0}function up(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=Fe(),o=xt(n,{projectRoot:t}),s=he(t,n),a=Oe(t,n,r),c=ke(i),l=Je(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=Sc(t,n,r),u=s.indexers.some(g=>!g.runnable),m=o.some(g=>g.level==="error")||u||a.state==="missing"||a.state==="stale",f=o.some(g=>g.level==="error")||u||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:u,hasErrors:f}}function pp(e){let t=G(e),n=Y(),r=Fn(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 mp(e){let t=G(e);try{let n={gitHook:b(t,"gitHook"),noHooks:b(t,"noHooks")||t.hooks===!1,dossierDir:w(t,"dossierDir"),runHealth:b(t,"yes")?!1:t.health!==!1,installSkills:t.skills!==!1,installAstParsers:t.parsers!==!1,...b(t,"yes")?{automaticRefresh:!0}:{}},r=b(t,"json"),i=!r&&!b(t,"yes")&&process.stdin.isTTY&&process.stdout.isTTY;(b(t,"guided")||i)&&(n=await rR(n,{json:b(t,"json")})),r||(n.onStatus=s=>console.log(` ${s}`));let o=await bu(n);b(t,"json")?I("setup",[],t,o):Su(o),process.exitCode=o.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function rR(e,t){let{projectRoot:n,config:r}=Fe(),i=he(n,r),o=yu({files:iR(n),watchEnabled:Pe(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=Ji(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 vu([...s,...a]):new Set([...oR(o.actions),...s.map(g=>g.id)]);l&&sR(o.actions,d);let u=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:!u,...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 iR(e){return{agentsMd:ke(ut(e,"AGENTS.md")),claudeMd:ke(ut(e,"CLAUDE.md")),codexHooks:ke(ut(e,".codex","hooks.json")),claudeSettings:ke(ut(e,".claude","settings.local.json"))}}function oR(e){return new Set([...e.filter(t=>t.recommended).map(t=>t.id),"install-agent-skills","install-ast-parsers"])}function sR(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 fp(e){let t=G(e),n=Y(),r=ku(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 gp(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=wu({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 hp(e){let t=G(e),n=Y(),r=fe(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"),u=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(u&&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=Pe(r);r.watch=h;let y=De(n,r),S={projectRoot:n,cacheDir:y.cacheDir,cliVersion:Ne,watchOverrides:g};if(l){let R=yp(Fr(S),h.enabled);u?I("watch",[],t,R):bp(R);return}if(d){try{let R=Qo(S);u?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=wn(S);u?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=Xo(ut(br(y.dbPath),zo),n);if(!x.acquired){console.error(x.message),process.exitCode=1;return}let k=new pr({projectRoot:n,config:r,languages:r.languages,onStatus:R=>{process.stdout.write(`\r\x1B[K${Wr(R)}`)},onReindexComplete:R=>{console.log(`
394
+ ${g} finding(s) disappeared without comparable comparison-base evidence; precision is not available.`)}function up(e){let t=G(e),{report:n,hasIndexerProblems:r,hasErrors:i}=pp("doctor");b(t,"json")?I("doctor",[],t,n):lR(n,r),process.exitCode=i?1:0}function pp(e){let{projectRoot:t,config:n,paths:r,dbPath:i}=Fe(),o=xt(n,{projectRoot:t}),s=he(t,n),a=Oe(t,n,r),c=ke(i),l=Je(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=vc(t,n,r),u=s.indexers.some(g=>!g.runnable),m=o.some(g=>g.level==="error")||u||a.state==="missing"||a.state==="stale",f=o.some(g=>g.level==="error")||u||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:u,hasErrors:f}}function mp(e){let t=G(e),n=Y(),r=Fn(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 fp(e){let t=G(e);try{let n={gitHook:b(t,"gitHook"),noHooks:b(t,"noHooks")||t.hooks===!1,dossierDir:w(t,"dossierDir"),runHealth:b(t,"yes")?!1:t.health!==!1,installSkills:t.skills!==!1,installAstParsers:t.parsers!==!1,...b(t,"yes")?{automaticRefresh:!0}:{}},r=b(t,"json"),i=!r&&!b(t,"yes")&&process.stdin.isTTY&&process.stdout.isTTY;(b(t,"guided")||i)&&(n=await iR(n,{json:b(t,"json")})),r||(n.onStatus=s=>console.log(` ${s}`));let o=await Su(n);b(t,"json")?I("setup",[],t,o):vu(o),process.exitCode=o.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function iR(e,t){let{projectRoot:n,config:r}=Fe(),i=he(n,r),o=bu({files:oR(n),watchEnabled:Pe(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=Ji(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 xu([...s,...a]):new Set([...sR(o.actions),...s.map(g=>g.id)]);l&&aR(o.actions,d);let u=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:!u,...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 oR(e){return{agentsMd:ke(ut(e,"AGENTS.md")),claudeMd:ke(ut(e,"CLAUDE.md")),codexHooks:ke(ut(e,".codex","hooks.json")),claudeSettings:ke(ut(e,".claude","settings.local.json"))}}function sR(e){return new Set([...e.filter(t=>t.recommended).map(t=>t.id),"install-agent-skills","install-ast-parsers"])}function aR(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 gp(e){let t=G(e),n=Y(),r=wu(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 hp(e){let t=G(e);if(b(t,"global")&&b(t,"project")){console.error("error: choose either --global or --project, not both."),process.exitCode=1;return}let n=$u({projectRoot:Y(),global:b(t,"global"),project:b(t,"project"),dryRun:b(t,"dryRun")});if(b(t,"json")){I("uninstall",[],t,n);return}let r=n.dryRun?"would ":"";if(n.global){for(let o of n.global.removed)console.log(` ${r}remove: ${o}`);for(let o of n.global.left)console.log(` left: ${o}`);for(let o of n.global.skipped)console.log(` skip: ${o}`)}if(n.project){for(let o of n.project.hooks.removed)console.log(` ${r}remove: ${o}`);for(let o of n.project.agentSetup.removed)console.log(` ${r}remove: ${o}`);for(let o of n.project.agentSetup.unchanged)console.log(` ok: ${o} (no managed block)`);for(let o of n.project.hooks.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);for(let o of n.project.agentSetup.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);for(let o of n.project.left)console.log(` left: ${o}`)}(n.global?.removed.length??0)+(n.project?.hooks.removed.length??0)+(n.project?.agentSetup.removed.length??0)===0&&console.log(n.dryRun?"No scip-query-owned files would be removed.":"No scip-query-owned files removed.")}function yp(e){let t=G(e),n=Y(),r=fe(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"),u=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(u&&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=Pe(r);r.watch=h;let y=De(n,r),S={projectRoot:n,cacheDir:y.cacheDir,cliVersion:Ne,watchOverrides:g};if(l){let R=bp(Fr(S),h.enabled);u?I("watch",[],t,R):Sp(R);return}if(d){try{let R=Yo(S);u?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=wn(S);u?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=Zo(ut(br(y.dbPath),Ko),n);if(!x.acquired){console.error(x.message),process.exitCode=1;return}let k=new pr({projectRoot:n,config:r,languages:r.languages,onStatus:R=>{process.stdout.write(`\r\x1B[K${Wr(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
  `),k.start(),process.on("SIGINT",()=>{k.stop(),x.release(),console.log(`
399
- Stopped.`),process.exit(0)}),process.once("exit",x.release)}function yp(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 aR(n)}}function bp(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: ${Wr(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 aR(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function Sp(e){let t=G(e),{report:n}=up("status"),r=Pe(fe(n.projectRoot)).enabled,i=yp(Fr({projectRoot:n.projectRoot,cacheDir:br(n.configuredDbPath),cliVersion:Ne}),r),o=Il(n.dbPath),s=nt(n.dbPath,n.freshness.metaPath),a=xn(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:Xi(n.exists)});return}lR(n,{affectedSetShadow:o,capabilities:b(t,"capabilities"),sqliteGeneration:s,rustSemanticSession:a,watchService:i})}function cR(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})`:""}`),to(e.capabilities)}function lR(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 vp(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}${xp(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: ${mR(e.freshness.lastRefresh)}`),bp(t.watchService),dR(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"),uR(t.sqliteGeneration),console.log(`Shadow: ${El(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),fR(e.exists),t.capabilities&&(console.log(""),to(e.capabilities))}function dR(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), ${Ue(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${Ue(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), ${Ue(e.cleanup.deletedBytes??0)} removed`)}function uR(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 vp(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function pR(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function xp(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function mR(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 Xi(e){if(e)return le(t=>{let n=bt(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function fR(e){e&&le(t=>{let n=bt(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${Ue(n.indexSizeBytes)}`),n.lastBuilt){let r=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${r}s ago`)}})}function to(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 rn(e){return{...e,options:C(e.options)}}function Ie({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,...a}){let c=rn(a);return{...c,renderShape:"list",handler:dc({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s})}}function Sr({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c,...l}){let d=rn(l);return{...d,renderShape:"table",handler:uc({commandName:d.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c})}}function Rp({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a,...c}){let l=rn(c);return{...l,renderShape:"grouped-by-file",handler:pc({commandName:l.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a})}}function kp({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=rn(a);return{...c,renderShape:"sectioned-report",handler:mc({commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}function vr({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=rn(a);return{...c,budget:c.budget??"semantic",renderShape:"sectioned-report",handler:fc(c.id,{commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}import{existsSync as UR,mkdirSync as JR,writeFileSync as zR}from"fs";import{dirname as KR,relative as QR}from"path";import{existsSync as Ge,readdirSync as vR,readFileSync as pt}from"fs";import{basename as xR,dirname as Ep,isAbsolute as jp,join as RR,relative as kR,resolve as on,sep as wR}from"path";import{spawnSync as hR}from"child_process";import{dirname as yR}from"path";function $p(e){let n=(e.spawnSync??hR)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:yR(e.specPath),maxBuffer:1024*1024*32});if(n.status!==0)return null;let r=n.stdout??"";return r.includes("<?xml")?r:null}function Pp(e){let t=SR(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=Cp(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 bR=8;function SR(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=no(s,"uniquename"),c=no(s,"kind"),l=no(s,"filename");t.push({uid:r[1],type:r[2],uniquename:a===null?null:wp(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:wp(l),block:s})}return t}function Cp(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[,u,m]of l){if(u==="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(u==="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(u==="UserDefinedOpKindRef"){d==="unchanged-run"&&(d="read");let f=r.get(m);if(f&&s<bR&&!o.has(f.uid)&&f.filename===i){let g=Cp(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 no(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function wp(e){return e.replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}var Lp=["update","insert","delete"],Ap=["select","query","findFirst","findMany"],ro=new Set([...Lp,...Ap]);function io(e){let t=e.methods&&e.methods.length>0?e.methods:[...ro],n=new Set(Lp),r=new Set(Ap);return{write:t.filter(i=>n.has(i)),read:t.filter(i=>r.has(i))}}var $R=/^(.*)@L(\d+)-L(\d+)$/;function oo(e){let t=e.match($R);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 PR=new Set(["auto","sany","tlc","apalache","none"]),Rr=/^[A-Za-z_][A-Za-z0-9_]*$/;function Dp(e){return PR.has(e)}function kr(e,t){let n=[],r=pe(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(pt(r,"utf8"))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let o=CR(i,n);return o?{loaded:{contract:o,mapPath:r,mapDir:Ep(r)},errors:n}:{errors:n}}function pe(e,t){if(!t)return null;let n=jp(t)?on(t):on(e,t);return me(e,n)?n:null}function Op(e,t,n){if(!n)return null;if(jp(n)){let s=on(n);return me(e,s)?s:null}let r=on(e,n);if(me(e,r)&&Ge(r))return r;let i=on(t,n);if(me(e,i)&&Ge(i))return i;let o=me(e,r)?r:i;return me(e,o)?o:null}function Np(e,t){let n=pe(e,t);if(!n||!Ge(n))return null;let r=pt(n,"utf8");return{path:n,modelParse:"regex-fallback",text:r,variables:BR(r),operators:VR(r),actions:[]}}function Fp(e,t,n){let r=pe(e,t);if(!r||!Ge(r))return null;let i=pt(r,"utf8"),o=Pp(n);return{path:r,modelParse:"sany",text:i,variables:o.variables,operators:o.operators,actions:o.actions}}function so(e,t){let n=pe(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(pt(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 ao(e,t){let n=new Set,r=[];for(let i of t){let o=pe(e,i)??i;n.has(o)||(n.add(o),r.push(i))}return r}function CR(e,t){if(!q(e))return t.push("map file must contain a JSON object"),null;let n=AR(e.variables,t);LR(n,t);let r=_R(e.actions,n,t),i=TR(e.init,t);ER(i,r,t);let o={module:Ip(e.module,"module",t),config:Ip(e.config,"config",t),scope:J(e.scope)??[],variables:n,actions:r,...i?{init:i}:{},invariants:J(e.invariants)??[],traces:J(e.traces)??[],unmappedWriteScope:jR(e.unmappedWriteScope,t)};return WR(e.scope,t),t.length===0?o:null}function TR(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=IR(e.waive,t);return{codeRefs:n,...r?{waive:r}:{}}}function IR(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 ER(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 jR(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 LR(e,t){xr(e,t,"alias",n=>n.aliases),xr(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),xr(e,t,"statement pattern",n=>n.statements?n.statements.map(r=>r.pattern):[]),xr(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(r=>{let{write:i,read:o}=io(r);return[...i,...o].map(s=>`${r.table}:${s}`)}))}function xr(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 AR(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(!Rr.test(r)){t.push(`invalid TLA+ variable name: ${r}`);continue}if(!q(i)){t.push(`variables.${r} must be an object`);continue}let o=_p(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=OR(i.resource,r,t),c=NR(i.statements,r,t),l=FR(i.ormCalls,r,t),d=MR(i.waive,r,t),u=DR(i.selfAlias,r,t),m=u?[...new Set([r,...s])]:[...new Set(s)];u===!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}:{},...u===!1?{selfAlias:!1}:{}}}return n}function DR(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 OR(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 NR(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 FR(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=>!ro.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${o}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...ro].join(", ")}`);return}r.push(a.length>0?{table:s,methods:a}:{table:s})}),r.length>0?r:void 0}function MR(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 _R(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(!Rr.test(o)){n.push(`invalid TLA+ action name: ${o}`);continue}if(!q(s)){n.push(`actions.${o} must be an object`);continue}let a=_p(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=oo(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 u=qR(s.waive,s.allowUnknown===!0,c,l,r,o,n);i[o]={code:a,reads:c,writes:l,calls:d,...u?{waive:u}:{}}}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`),Tp(o,"reads",c,i,s),Tp(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 Tp(e,t,n,r,i){for(let o of n)r.has(o)||i.push(`actions.${e}.waive.${t} references unknown variable: ${o}`)}function BR(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();Rr.test(o)&&t.add(o)}}return[...t].sort()}function VR(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 HR=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function Mp(e){if(!e||!Ge(e))return[];let t=pt(e,"utf8").replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,r=!1;for(let i of t.split(/[\s,]+/))if(i){if(HR.has(i)){r=i==="INVARIANT"||i==="INVARIANTS";continue}r&&Rr.test(i)&&n.add(i)}return[...n].sort()}function Ip(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function _p(e){return typeof e=="string"?[e]:J(e)}function WR(e,t){e!==void 0&&(J(e)||t.push("scope must be an array of strings when present"))}function wr(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var GR=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function qp(e,t){if(!Ge(t))return{status:"none"};let r=pt(t,"utf8").match(GR)?.[1],i=kR(e,t).split(wR).join("/"),o=xR(t),s=new Set([r,i,o,o.replace(/\.tla$/i,"")].filter(d=>!!d)),a=Ep(t);if(!Ge(a))return{status:"none"};let c=[];for(let d of vR(a)){if(!d.endsWith(".scip-tla.json"))continue;let u=RR(a,d),m;try{m=JSON.parse(pt(u,"utf8"))}catch{continue}q(m)&&typeof m.module=="string"&&s.has(m.module)&&c.push(u)}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 $r(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((u,m)=>u+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((u,m)=>u.startLine-m.startLine);for(let u of d){let m=u.implicitUsageReason?` [implicit usage: ${u.implicitUsageReason}]`:"";console.log(` ${oe(u.startLine,u.endLine)} (${u.loc} LOC) ${u.shortName}${m}`)}}}var co=20,Bp=K("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:B(t,0)||void 0,minLoc:P(n,"minLoc",1),includeTests:b(n,"includeTests"),skipBarrels:b(n,"skipBarrels"),includeMembers:b(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=bs(e,i),s=o.symbols.filter(N=>N.kind==="dead-code"),a=o.symbols.filter(N=>N.kind==="file-internal"),c=o.symbols.filter(N=>N.kind==="implicit-usage"),l=!b(n,"onlyInternal"),d=!b(n,"onlyDead"),u=!b(n,"onlyDead")&&!b(n,"onlyInternal"),m=l?s:[],f=d?a:[],g=u?c:[],h=m.reduce((N,H)=>N+H.loc,0),y=f.reduce((N,H)=>N+H.loc,0),S=g.reduce((N,H)=>N+H.loc,0),x=b(n,"full"),k=x?m:m.slice(0,co),R=x?f:f.slice(0,co),D=x?g:g.slice(0,co),_=k.reduce((N,H)=>N+H.loc,0),z=R.reduce((N,H)=>N+H.loc,0),T=D.reduce((N,H)=>N+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){E.empty("No matching dead-code symbols found.");return}m.length>0&&($r(k,"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 bp(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 cR(n)}}function Sp(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: ${Wr(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 cR(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function vp(e){let t=G(e),{report:n}=pp("status"),r=Pe(fe(n.projectRoot)).enabled,i=bp(Fr({projectRoot:n.projectRoot,cacheDir:br(n.configuredDbPath),cliVersion:Ne}),r),o=El(n.dbPath),s=nt(n.dbPath,n.freshness.metaPath),a=xn(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:Xi(n.exists)});return}dR(n,{affectedSetShadow:o,capabilities:b(t,"capabilities"),sqliteGeneration:s,rustSemanticSession:a,watchService:i})}function lR(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})`:""}`),to(e.capabilities)}function dR(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 xp(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}${Rp(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: ${fR(e.freshness.lastRefresh)}`),Sp(t.watchService),uR(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"),pR(t.sqliteGeneration),console.log(`Shadow: ${jl(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),gR(e.exists),t.capabilities&&(console.log(""),to(e.capabilities))}function uR(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), ${Ue(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${Ue(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), ${Ue(e.cleanup.deletedBytes??0)} removed`)}function pR(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 xp(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function mR(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function Rp(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function fR(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 Xi(e){if(e)return le(t=>{let n=bt(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function gR(e){e&&le(t=>{let n=bt(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${Ue(n.indexSizeBytes)}`),n.lastBuilt){let r=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${r}s ago`)}})}function to(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 rn(e){return{...e,options:C(e.options)}}function Ie({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,...a}){let c=rn(a);return{...c,renderShape:"list",handler:uc({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s})}}function Sr({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c,...l}){let d=rn(l);return{...d,renderShape:"table",handler:pc({commandName:d.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,headers:a,dashWidths:c})}}function kp({query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a,...c}){let l=rn(c);return{...l,renderShape:"grouped-by-file",handler:mc({commandName:l.id,query:e,format:t,emptyMessage:n,heuristicLabel:r,before:i,toJson:o,after:s,key:a})}}function wp({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=rn(a);return{...c,renderShape:"sectioned-report",handler:fc({commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}function vr({query:e,emptyMessage:t,heuristicLabel:n,sections:r,before:i,toJson:o,after:s,...a}){let c=rn(a);return{...c,budget:c.budget??"semantic",renderShape:"sectioned-report",handler:gc(c.id,{commandName:c.id,query:e,emptyMessage:t,heuristicLabel:n,before:i,sections:r,toJson:o,after:s})}}import{existsSync as JR,mkdirSync as zR,writeFileSync as KR}from"fs";import{dirname as QR,relative as YR}from"path";import{existsSync as Ge,readdirSync as xR,readFileSync as pt}from"fs";import{basename as RR,dirname as jp,isAbsolute as Lp,join as kR,relative as wR,resolve as on,sep as $R}from"path";import{spawnSync as yR}from"child_process";import{dirname as bR}from"path";function Pp(e){let n=(e.spawnSync??yR)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:bR(e.specPath),maxBuffer:1024*1024*32});if(n.status!==0)return null;let r=n.stdout??"";return r.includes("<?xml")?r:null}function Cp(e){let t=vR(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=Tp(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 SR=8;function vR(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=no(s,"uniquename"),c=no(s,"kind"),l=no(s,"filename");t.push({uid:r[1],type:r[2],uniquename:a===null?null:$p(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:$p(l),block:s})}return t}function Tp(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[,u,m]of l){if(u==="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(u==="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(u==="UserDefinedOpKindRef"){d==="unchanged-run"&&(d="read");let f=r.get(m);if(f&&s<SR&&!o.has(f.uid)&&f.filename===i){let g=Tp(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 no(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function $p(e){return e.replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&amp;","&")}var Ap=["update","insert","delete"],Dp=["select","query","findFirst","findMany"],ro=new Set([...Ap,...Dp]);function io(e){let t=e.methods&&e.methods.length>0?e.methods:[...ro],n=new Set(Ap),r=new Set(Dp);return{write:t.filter(i=>n.has(i)),read:t.filter(i=>r.has(i))}}var PR=/^(.*)@L(\d+)-L(\d+)$/;function oo(e){let t=e.match(PR);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 CR=new Set(["auto","sany","tlc","apalache","none"]),Rr=/^[A-Za-z_][A-Za-z0-9_]*$/;function Op(e){return CR.has(e)}function kr(e,t){let n=[],r=pe(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(pt(r,"utf8"))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let o=TR(i,n);return o?{loaded:{contract:o,mapPath:r,mapDir:jp(r)},errors:n}:{errors:n}}function pe(e,t){if(!t)return null;let n=Lp(t)?on(t):on(e,t);return me(e,n)?n:null}function Np(e,t,n){if(!n)return null;if(Lp(n)){let s=on(n);return me(e,s)?s:null}let r=on(e,n);if(me(e,r)&&Ge(r))return r;let i=on(t,n);if(me(e,i)&&Ge(i))return i;let o=me(e,r)?r:i;return me(e,o)?o:null}function Fp(e,t){let n=pe(e,t);if(!n||!Ge(n))return null;let r=pt(n,"utf8");return{path:n,modelParse:"regex-fallback",text:r,variables:VR(r),operators:HR(r),actions:[]}}function Mp(e,t,n){let r=pe(e,t);if(!r||!Ge(r))return null;let i=pt(r,"utf8"),o=Cp(n);return{path:r,modelParse:"sany",text:i,variables:o.variables,operators:o.operators,actions:o.actions}}function so(e,t){let n=pe(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(pt(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 ao(e,t){let n=new Set,r=[];for(let i of t){let o=pe(e,i)??i;n.has(o)||(n.add(o),r.push(i))}return r}function TR(e,t){if(!q(e))return t.push("map file must contain a JSON object"),null;let n=DR(e.variables,t);AR(n,t);let r=qR(e.actions,n,t),i=IR(e.init,t);jR(i,r,t);let o={module:Ep(e.module,"module",t),config:Ep(e.config,"config",t),scope:J(e.scope)??[],variables:n,actions:r,...i?{init:i}:{},invariants:J(e.invariants)??[],traces:J(e.traces)??[],unmappedWriteScope:LR(e.unmappedWriteScope,t)};return GR(e.scope,t),t.length===0?o:null}function IR(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=ER(e.waive,t);return{codeRefs:n,...r?{waive:r}:{}}}function ER(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 jR(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 LR(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 AR(e,t){xr(e,t,"alias",n=>n.aliases),xr(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),xr(e,t,"statement pattern",n=>n.statements?n.statements.map(r=>r.pattern):[]),xr(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(r=>{let{write:i,read:o}=io(r);return[...i,...o].map(s=>`${r.table}:${s}`)}))}function xr(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 DR(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(!Rr.test(r)){t.push(`invalid TLA+ variable name: ${r}`);continue}if(!q(i)){t.push(`variables.${r} must be an object`);continue}let o=qp(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=NR(i.resource,r,t),c=FR(i.statements,r,t),l=MR(i.ormCalls,r,t),d=_R(i.waive,r,t),u=OR(i.selfAlias,r,t),m=u?[...new Set([r,...s])]:[...new Set(s)];u===!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}:{},...u===!1?{selfAlias:!1}:{}}}return n}function OR(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 NR(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 FR(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 MR(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=>!ro.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${o}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...ro].join(", ")}`);return}r.push(a.length>0?{table:s,methods:a}:{table:s})}),r.length>0?r:void 0}function _R(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 qR(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(!Rr.test(o)){n.push(`invalid TLA+ action name: ${o}`);continue}if(!q(s)){n.push(`actions.${o} must be an object`);continue}let a=qp(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=oo(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 u=BR(s.waive,s.allowUnknown===!0,c,l,r,o,n);i[o]={code:a,reads:c,writes:l,calls:d,...u?{waive:u}:{}}}return i}function BR(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`),Ip(o,"reads",c,i,s),Ip(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 Ip(e,t,n,r,i){for(let o of n)r.has(o)||i.push(`actions.${e}.waive.${t} references unknown variable: ${o}`)}function VR(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();Rr.test(o)&&t.add(o)}}return[...t].sort()}function HR(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 WR=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function _p(e){if(!e||!Ge(e))return[];let t=pt(e,"utf8").replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,r=!1;for(let i of t.split(/[\s,]+/))if(i){if(WR.has(i)){r=i==="INVARIANT"||i==="INVARIANTS";continue}r&&Rr.test(i)&&n.add(i)}return[...n].sort()}function Ep(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function qp(e){return typeof e=="string"?[e]:J(e)}function GR(e,t){e!==void 0&&(J(e)||t.push("scope must be an array of strings when present"))}function wr(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var UR=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function Bp(e,t){if(!Ge(t))return{status:"none"};let r=pt(t,"utf8").match(UR)?.[1],i=wR(e,t).split($R).join("/"),o=RR(t),s=new Set([r,i,o,o.replace(/\.tla$/i,"")].filter(d=>!!d)),a=jp(t);if(!Ge(a))return{status:"none"};let c=[];for(let d of xR(a)){if(!d.endsWith(".scip-tla.json"))continue;let u=kR(a,d),m;try{m=JSON.parse(pt(u,"utf8"))}catch{continue}q(m)&&typeof m.module=="string"&&s.has(m.module)&&c.push(u)}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 $r(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((u,m)=>u+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((u,m)=>u.startLine-m.startLine);for(let u of d){let m=u.implicitUsageReason?` [implicit usage: ${u.implicitUsageReason}]`:"";console.log(` ${oe(u.startLine,u.endLine)} (${u.loc} LOC) ${u.shortName}${m}`)}}}var co=20,Vp=K("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:B(t,0)||void 0,minLoc:P(n,"minLoc",1),includeTests:b(n,"includeTests"),skipBarrels:b(n,"skipBarrels"),includeMembers:b(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=Ss(e,i),s=o.symbols.filter(N=>N.kind==="dead-code"),a=o.symbols.filter(N=>N.kind==="file-internal"),c=o.symbols.filter(N=>N.kind==="implicit-usage"),l=!b(n,"onlyInternal"),d=!b(n,"onlyDead"),u=!b(n,"onlyDead")&&!b(n,"onlyInternal"),m=l?s:[],f=d?a:[],g=u?c:[],h=m.reduce((N,H)=>N+H.loc,0),y=f.reduce((N,H)=>N+H.loc,0),S=g.reduce((N,H)=>N+H.loc,0),x=b(n,"full"),k=x?m:m.slice(0,co),R=x?f:f.slice(0,co),D=x?g:g.slice(0,co),_=k.reduce((N,H)=>N+H.loc,0),z=R.reduce((N,H)=>N+H.loc,0),T=D.reduce((N,H)=>N+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){E.empty("No matching dead-code symbols found.");return}m.length>0&&($r(k,"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>k.length&&console.log(`
402
402
  Showing top ${k.length} by LOC. Re-run with --full for the remaining ${m.length-k.length}.`)),f.length>0&&(m.length>0&&console.log(""),$r(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
@@ -408,25 +408,25 @@ Language matrix:`);for(let t of e.matrix){console.log(` ${t.language}`);for(let
408
408
  consumer that the static reference graph cannot trace. Investigation
409
409
  signals only \u2014 not deletion candidates and not counted as dead code.`,T,{count:g.length,loc:S}),!x&&g.length>D.length&&console.log(`
410
410
  Showing top ${D.length} by LOC. Re-run with --full for the remaining ${g.length-D.length}.`));let Z=[];l&&Z.push(`${m.length} dead code (${h} LOC)`),d&&Z.push(`${f.length} file-internal (${y} LOC)`),u&&Z.push(`${g.length} implicit usage (${S} LOC)`),console.log(`
411
- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${m.length+f.length+g.length} symbols \u2014 ${Z.join(" + ")}`)}),Vp=ue("unused-imports",{query:({db:e,args:t,budget:n})=>Rs(e,L(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
412
- ${e.length} unused import(s)`)}),Hp=gc("isolated",{query:({db:e,opts:t,budget:n})=>Ls(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${oe(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
413
- ${e.length} isolated symbol(s)`)}),Wp=K("extract-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=zs(e,{scope:w(n,"scope"),minLoc:P(n,"minLoc",10),minCallees:P(n,"minCallees",6),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(b(n,"json")){I("extract-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return E.empty("No extraction candidates found.");Ce("extraction candidates");for(let o of i){console.log(`
411
+ \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${m.length+f.length+g.length} symbols \u2014 ${Z.join(" + ")}`)}),Hp=ue("unused-imports",{query:({db:e,args:t,budget:n})=>ks(e,L(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
412
+ ${e.length} unused import(s)`)}),Wp=hc("isolated",{query:({db:e,opts:t,budget:n})=>As(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${oe(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
413
+ ${e.length} isolated symbol(s)`)}),Gp=K("extract-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Ks(e,{scope:w(n,"scope"),minLoc:P(n,"minLoc",10),minCallees:P(n,"minCallees",6),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic});if(b(n,"json")){I("extract-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return E.empty("No extraction candidates found.");Ce("extraction candidates");for(let o of i){console.log(`
414
414
  ${M(o.relativePath,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC, ${o.totalCallees} callees)`),console.log(` Kind: ${o.extractionKind}; tier: ${o.actionTier}`),console.log(` Recommendation: ${o.recommendation}`);for(let s of o.evidenceReasons)console.log(` - ${s}`);for(let s=0;s<o.clusters.length;s++){let a=o.clusters[s];console.log(` Cluster ${s+1} (${Math.round(a.isolation*100)}% isolated, ${a.callees.length} callees):`);for(let c of a.callees)console.log(` ${c}`)}}console.log(`
415
- ${i.length} extraction candidate(s) found.`)}),Gp=K("locality-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Ks(e,{target:B(t,0)||void 0,scope:w(n,"scope"),minConsumers:P(n,"minConsumers",1),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(b(n,"json")){I("locality-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return E.empty("No locality candidates found.");Ce("locality candidates");for(let o of i){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?M(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
415
+ ${i.length} extraction candidate(s) found.`)}),Up=K("locality-candidates",({db:e,args:t,opts:n,budget:r})=>{let i=Qs(e,{target:B(t,0)||void 0,scope:w(n,"scope"),minConsumers:P(n,"minConsumers",1),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(b(n,"json")){I("locality-candidates",t,n,i,{analysisBudget:r.analysisBudget});return}if(i.length===0)return E.empty("No locality candidates found.");Ce("locality candidates");for(let o of i){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?M(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
416
416
  ${s} ${o.sourceUnit.shortName}`),console.log(` Current directory: ${o.currentDirectory}; tier: ${o.recommendedTier}; action: ${o.actionTier}`),console.log(` Consumer coverage: ${o.consumerCoverage}; consumers: ${o.consumerFiles.length}`),o.nearestCommonOwner&&console.log(` Nearest common owner: ${o.nearestCommonOwner}`),o.suggestedHome&&console.log(` Suggested home: ${o.suggestedHome}`),o.whyNoSuggestedHome&&console.log(` Suggested home withheld: ${o.whyNoSuggestedHome}`),o.boundaryMarkers.length>0&&console.log(` Boundary markers: ${o.boundaryMarkers.join("; ")}`),console.log(` Recommendation: ${o.recommendation}`),o.consumerFiles.length>0){for(let a of o.consumerFiles.slice(0,8))console.log(` - consumer: ${a}`);o.consumerFiles.length>8&&console.log(` - ... ${o.consumerFiles.length-8} more consumer(s)`)}for(let a of o.counterevidence)console.log(` - counterevidence: ${a}`)}console.log(`
417
- ${i.length} locality candidate(s) found.`)}),Up=ue("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>aa(e,{scope:w(t,"scope"),maxLoc:P(t,"maxLoc",15),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
417
+ ${i.length} locality candidate(s) found.`)}),Jp=ue("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>ca(e,{scope:w(t,"scope"),maxLoc:P(t,"maxLoc",15),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
418
418
  Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
419
419
  Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
420
- ${e.length} wrapper candidate(s).`)}),Jp=ue("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>oa(e,{scope:w(t,"scope"),maxLoc:P(t,"maxLoc",15),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
420
+ ${e.length} wrapper candidate(s).`)}),zp=ue("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>sa(e,{scope:w(t,"scope"),maxLoc:P(t,"maxLoc",15),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
421
421
  Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
422
422
  Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
423
423
  Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
424
424
  Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
425
- ${e.length} passthrough candidate(s).`)}),zp=ue("stale-abstractions",{query:({db:e,opts:t,budget:n})=>sa(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",3),limit:A(t,"limit",30),includeLowConfidence:b(t,"includeLowConfidence"),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.consumers===0?"unused":`${e.consumers} consumer`,n=e.barrelConsumers>0?`, +${e.barrelConsumers} barrel`:"";return` [${e.confidence}] ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
425
+ ${e.length} passthrough candidate(s).`)}),Kp=ue("stale-abstractions",{query:({db:e,opts:t,budget:n})=>aa(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",3),limit:A(t,"limit",30),includeLowConfidence:b(t,"includeLowConfidence"),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.consumers===0?"unused":`${e.consumers} consumer`,n=e.barrelConsumers>0?`, +${e.barrelConsumers} barrel`:"";return` [${e.confidence}] ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
426
426
  ${e.reason}
427
427
  Kind: ${e.stalenessKind}; tier: ${e.actionTier}
428
428
  Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
429
- ${e.length} stale abstraction(s).`)}),Kp=Dn("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>ka(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",10),limit:A(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.score.toFixed(1).padStart(5)} ${String(e.loc).padStart(4)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${String(e.calleeCount).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No complexity hotspots found.",heuristicLabel:"complexity hotspot candidates",dashWidths:[5,4,6,7,7,6]}),Qp=Se("similar",{query:({db:e,args:t,opts:n,budget:r})=>{if(b(n,"plan")){let o=B(t,0),s=B(t,1);if(!o||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:Ms(e,o,s,{scanLimit:r.scanLimit,semantic:r.semantic})}}let i=B(t,0);return i?{mode:"target",rows:Fs(e,i,{minSimilarity:P(n,"minSimilarity",.4),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:_s(e,{minSimilarity:P(n,"minSimilarity",.4),limit:A(n,"limit",20),scope:w(n,"scope"),minCallees:P(n,"minCallees",4),crossFileOnly:b(n,"crossFileOnly"),scanLimit:r.scanLimit,semantic:r.semantic})}},emptyMessage:e=>{if(e.mode==="plan")return e.result?void 0:"No similarity evidence found for that pair.";if(!(e.rows.length>0))return e.mode==="target"?"No similar symbols found.":"No similar symbol pairs found."},heuristicLabel:"similarity candidates",render:e=>{if(e.mode==="plan"){let t=e.result;if(!t)return;let n=t.similarityBasis==="source-tokens"?"source-token overlap":"weighted callee overlap";console.log(`
429
+ ${e.length} stale abstraction(s).`)}),Qp=Dn("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>wa(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",10),limit:A(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.score.toFixed(1).padStart(5)} ${String(e.loc).padStart(4)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${String(e.calleeCount).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No complexity hotspots found.",heuristicLabel:"complexity hotspot candidates",dashWidths:[5,4,6,7,7,6]}),Yp=Se("similar",{query:({db:e,args:t,opts:n,budget:r})=>{if(b(n,"plan")){let o=B(t,0),s=B(t,1);if(!o||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:_s(e,o,s,{scanLimit:r.scanLimit,semantic:r.semantic})}}let i=B(t,0);return i?{mode:"target",rows:Ms(e,i,{minSimilarity:P(n,"minSimilarity",.4),limit:A(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:qs(e,{minSimilarity:P(n,"minSimilarity",.4),limit:A(n,"limit",20),scope:w(n,"scope"),minCallees:P(n,"minCallees",4),crossFileOnly:b(n,"crossFileOnly"),scanLimit:r.scanLimit,semantic:r.semantic})}},emptyMessage:e=>{if(e.mode==="plan")return e.result?void 0:"No similarity evidence found for that pair.";if(!(e.rows.length>0))return e.mode==="target"?"No similar symbols found.":"No similar symbol pairs found."},heuristicLabel:"similarity candidates",render:e=>{if(e.mode==="plan"){let t=e.result;if(!t)return;let n=t.similarityBasis==="source-tokens"?"source-token overlap":"weighted callee overlap";console.log(`
430
430
  ${Math.round(t.similarity*100)}% ${n}
431
431
  `),console.log(` A: ${t.symbolA.shortName} (${t.symbolA.file}, ${t.symbolA.loc} LOC)`),console.log(` B: ${t.symbolB.shortName} (${t.symbolB.file}, ${t.symbolB.loc} LOC)`),console.log(` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`),console.log(` Recommendation: ${t.recommendation}
432
432
  `),console.log(` Shared evidence (${t.sharedEvidence.length}):`);for(let r of t.sharedEvidence)console.log(` ${r}`);if(t.uniqueToA.length>0){console.log(`
@@ -442,107 +442,107 @@ ${Math.round(t.similarity*100)}% similar:
442
442
  Recommendation: ${t.recommendation}
443
443
  `+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
444
444
  `:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
445
- ${e.rows.length} similar pair(s) found.`)}}),Yp=it({commandName:"similar-files",query:({db:e,args:t,opts:n})=>qs(e,{minSimilarity:P(n,"minSimilarity",.5),limit:A(n,"limit",20),scope:w(n,"scope"),minDeps:U(n,"minDeps"),filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{E.list(e,t=>{let n=[`
445
+ ${e.rows.length} similar pair(s) found.`)}}),Xp=it({commandName:"similar-files",query:({db:e,args:t,opts:n})=>Bs(e,{minSimilarity:P(n,"minSimilarity",.5),limit:A(n,"limit",20),scope:w(n,"scope"),minDeps:U(n,"minDeps"),filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{E.list(e,t=>{let n=[`
446
446
  ${Math.round(t.similarity*100)}% similar:`,` ${t.fileA}`,` ${t.fileB}`,` Shared deps (${t.sharedDeps.length}): ${t.sharedDeps.join(", ")}`];return t.uniqueToA.length&&n.push(` Only in first: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&n.push(` Only in second: ${t.uniqueToB.join(", ")}`),n.join(`
447
447
  `)}),console.log(`
448
- ${e.length} similar pair(s) found.`)}}),Xp=it({commandName:"similar-chains",query:({db:e,opts:t})=>Js(e,{minSimilarity:P(t,"minSimilarity",.5),limit:A(t,"limit",15),scope:w(t,"scope"),minChainLength:P(t,"minLength",3),maxChainLength:P(t,"maxLength",8)}),emptyMessage:e=>e.length===0?"No similar chains found.":void 0,heuristicLabel:"similar chain candidates",render:e=>{for(let t=0;t<e.length;t++){let n=e[t];console.log(`
448
+ ${e.length} similar pair(s) found.`)}}),Zp=it({commandName:"similar-chains",query:({db:e,opts:t})=>zs(e,{minSimilarity:P(t,"minSimilarity",.5),limit:A(t,"limit",15),scope:w(t,"scope"),minChainLength:P(t,"minLength",3),maxChainLength:P(t,"maxLength",8)}),emptyMessage:e=>e.length===0?"No similar chains found.":void 0,heuristicLabel:"similar chain candidates",render:e=>{for(let t=0;t<e.length;t++){let n=e[t];console.log(`
449
449
  \u2500\u2500 Chain pair ${t+1} (${Math.round(n.similarity*100)}% similar, ${n.divergencePoints.length} divergence point(s)) \u2500\u2500`),console.log(` Chain A: ${n.chainA.join(" \u2192 ")}`),console.log(` Chain B: ${n.chainB.join(" \u2192 ")}`),n.commonPrefix.length&&console.log(` Common prefix: ${n.commonPrefix.join(" \u2192 ")}`),n.commonSuffix.length&&console.log(` Common suffix: ${n.commonSuffix.join(" \u2192 ")}`),console.log(" Divergence points (consolidation targets):");for(let r of n.divergencePoints)console.log(` [${r.index}] ${r.nodeA} \u2194 ${r.nodeB}`)}console.log(`
450
- ${e.length} similar chain pair(s) found.`)}}),Zp=Se("drift",{query:({db:e,args:t,opts:n,budget:r})=>ia(e,{scope:B(t,0),minDeviation:P(n,"minDeviation",5),semantic:r.semantic,includePatternDeviations:b(n,"patterns"),limit:A(n,"limit",50)}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),E.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="layer-violation"?"LAYER":"UNIQUE",r=t.policyBasis?`, policy: ${t.policyBasis}`:"",i=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${r}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&i.push(` ${t.detail}`),i.join(`
450
+ ${e.length} similar chain pair(s) found.`)}}),em=Se("drift",{query:({db:e,args:t,opts:n,budget:r})=>oa(e,{scope:B(t,0),minDeviation:P(n,"minDeviation",5),semantic:r.semantic,includePatternDeviations:b(n,"patterns"),limit:A(n,"limit",50)}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),E.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="layer-violation"?"LAYER":"UNIQUE",r=t.policyBasis?`, policy: ${t.policyBasis}`:"",i=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${r}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&i.push(` ${t.detail}`),i.join(`
451
451
  `)},t=>t.file),console.log(`
452
- ${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)${e.totalResults?` \u2014 showing ${e.results.length} of ${e.totalResults} (use -n to change)`:""}`)}}),em=Se("convergence",{query:({db:e,args:t,budget:n})=>ja(e,L(t,0),L(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols did not resolve, or the pair has no fingerprint evidence (small helpers with few callees fall below the similarity threshold; try --min-callees 1).",render:e=>{if(e){console.log("\nDeprecated: use `similar <symbol1> <symbol2> --plan` for the same weighted similarity basis."),console.log(`
452
+ ${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)${e.totalResults?` \u2014 showing ${e.results.length} of ${e.totalResults} (use -n to change)`:""}`)}}),tm=Se("convergence",{query:({db:e,args:t,budget:n})=>La(e,L(t,0),L(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols did not resolve, or the pair has no fingerprint evidence (small helpers with few callees fall below the similarity threshold; try --min-callees 1).",render:e=>{if(e){console.log("\nDeprecated: use `similar <symbol1> <symbol2> --plan` for the same weighted similarity basis."),console.log(`
453
453
  ${Math.round(e.similarity*100)}% callee overlap
454
454
  `),console.log(` A: ${e.symbolA.shortName} (${e.symbolA.file}, ${e.symbolA.loc} LOC)`),console.log(` B: ${e.symbolB.shortName} (${e.symbolB.file}, ${e.symbolB.loc} LOC)
455
455
  `),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
456
456
  Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
457
457
  Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
458
- Strategy: ${e.consolidationStrategy}`)}}}),tm=ue("similar-signatures",{query:({db:e,opts:t,budget:n})=>Da(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",3),maxShapeFrequency:P(t,"maxShapeFrequency",12),limit:A(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
458
+ Strategy: ${e.consolidationStrategy}`)}}}),nm=ue("similar-signatures",{query:({db:e,opts:t,budget:n})=>Oa(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",3),maxShapeFrequency:P(t,"maxShapeFrequency",12),limit:A(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
459
459
  Signature: ${e.signature} (${e.functions.length} functions, ${e.locBand} LOC${t})`,r=e.functions.map(i=>` ${M(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
460
460
  `);return`${n}
461
461
  ${r}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
462
- ${e.length} group(s) found.`)}),nm=ue("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>na(e,{scope:w(t,"scope"),maxLoc:P(t,"maxLoc",15),minLoc:P(t,"minLoc",3),limit:A(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
462
+ ${e.length} group(s) found.`)}),rm=ue("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>ra(e,{scope:w(t,"scope"),maxLoc:P(t,"maxLoc",15),minLoc:P(t,"minLoc",3),limit:A(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
463
463
  Body hash: ${e.hash} (${e.functions.length} functions)`,n=e.functions.map((r,i)=>` ${(i===0?"canonical":"duplicate").padEnd(9)} ${M(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
464
464
  `);return`${t}
465
465
  ${n}`},emptyMessage:()=>"No exact duplicate function bodies found.",heuristicLabel:"duplicate body candidates",after:e=>console.log(`
466
- ${e.length} group(s) found.`)}),rm=ue("twin-drift",{query:({db:e,opts:t,budget:n})=>ra(e,{scope:w(t,"scope"),minSimilarity:P(t,"minSimilarity",.3),includeHomonyms:b(t,"includeHomonyms"),limit:A(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
466
+ ${e.length} group(s) found.`)}),im=ue("twin-drift",{query:({db:e,opts:t,budget:n})=>ia(e,{scope:w(t,"scope"),minSimilarity:P(t,"minSimilarity",.3),includeHomonyms:b(t,"includeHomonyms"),limit:A(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
467
467
  ${e.leaf} (${e.relationship}, ${e.members.length} functions, ${Math.round(e.maxDivergence*100)}% divergence)`,n=e.members.map(i=>` ${M(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
468
468
  `),r=e.firstDivergentTokens?`
469
469
  first divergent tokens: ${e.firstDivergentTokens}`:"";return`${t}
470
470
  ${n}${r}`},emptyMessage:()=>"No divergent twin groups found.",heuristicLabel:"twin drift candidates",after:e=>console.log(`
471
- ${e.length} group(s) found.`)}),im=ue("not-implemented",{query:({db:e,opts:t,budget:n})=>ga(e,{scope:w(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
471
+ ${e.length} group(s) found.`)}),om=ue("not-implemented",{query:({db:e,opts:t,budget:n})=>ha(e,{scope:w(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
472
472
  ${e.stubText}`,emptyMessage:()=>"No reachable placeholder stubs found.",heuristicLabel:"reachable placeholder stubs",after:e=>console.log(`
473
- ${e.length} reachable placeholder stub(s).`)}),om=ue("decorative-checkers",{query:({db:e,opts:t,budget:n})=>ha(e,{scope:w(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.nameKind}, resolved: ${e.resolvedVia}${e.delegateTarget?` -> ${e.delegateTarget}`:""})`,emptyMessage:()=>"No decorative checker candidates found.",heuristicLabel:"decorative checker candidates",after:e=>console.log(`
474
- ${e.length} decorative checker candidate(s).`)}),sm=K("test-quality",({db:e,args:t,opts:n,budget:r})=>{let i=ya(e,{scope:w(n,"scope"),limit:A(n,"limit",30),scanLimit:r.scanLimit,rotDays:U(n,"rotDays")});if(b(n,"json")){I("test-quality",t,n,i,{analysisBudget:r.analysisBudget});return}if(Ce("test-quality findings"),i.assertionFree.length+i.skipped.length+i.mockEcho.length===0){E.empty("No test-quality findings.");return}i.assertionFree.length>0&&(console.log(`
473
+ ${e.length} reachable placeholder stub(s).`)}),sm=ue("decorative-checkers",{query:({db:e,opts:t,budget:n})=>ya(e,{scope:w(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.nameKind}, resolved: ${e.resolvedVia}${e.delegateTarget?` -> ${e.delegateTarget}`:""})`,emptyMessage:()=>"No decorative checker candidates found.",heuristicLabel:"decorative checker candidates",after:e=>console.log(`
474
+ ${e.length} decorative checker candidate(s).`)}),am=K("test-quality",({db:e,args:t,opts:n,budget:r})=>{let i=ba(e,{scope:w(n,"scope"),limit:A(n,"limit",30),scanLimit:r.scanLimit,rotDays:U(n,"rotDays")});if(b(n,"json")){I("test-quality",t,n,i,{analysisBudget:r.analysisBudget});return}if(Ce("test-quality findings"),i.assertionFree.length+i.skipped.length+i.mockEcho.length===0){E.empty("No test-quality findings.");return}i.assertionFree.length>0&&(console.log(`
475
475
  ASSERTION-FREE (${i.assertionFree.length})`),E.list(i.assertionFree,s=>` ${M(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),i.skipped.length>0&&(console.log(`
476
476
  SKIPPED (${i.skipped.length})`),E.list(i.skipped,s=>` ${s.file}:${s.startLine+1} "${s.title}" (${s.blockKind}.${s.skipKind}, age: ${s.ageDays??"unknown"}d, ${s.rot})`)),i.mockEcho.length>0&&(console.log(`
477
477
  MOCK-ECHO (${i.mockEcho.length})`),E.list(i.mockEcho,s=>` ${M(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
478
- ${i.assertionFree.length} assertion-free, ${i.skipped.length} skipped, ${i.mockEcho.length} mock-echo.`)}),am=it({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let r=L(t,0),i=L(t,1),o=w(n,"out")??ma(r,i),s=pe(e.config.projectRoot,o);if(!s)throw new Error(`twin-ab output path escapes the project root: ${o}`);let a=fa(e,r,i,s);if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=QR(e.config.projectRoot,s);if(!b(n,"force")&&UR(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return JR(KR(s),{recursive:!0}),zR(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
478
+ ${i.assertionFree.length} assertion-free, ${i.skipped.length} skipped, ${i.mockEcho.length} mock-echo.`)}),cm=it({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let r=L(t,0),i=L(t,1),o=w(n,"out")??fa(r,i),s=pe(e.config.projectRoot,o);if(!s)throw new Error(`twin-ab output path escapes the project root: ${o}`);let a=ga(e,r,i,s);if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=YR(e.config.projectRoot,s);if(!b(n,"force")&&JR(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return zR(QR(s),{recursive:!0}),KR(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
479
479
  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(`
480
- Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),cm=K("cleanup-plan",({db:e,args:t,opts:n,budget:r})=>{let i=_r(e,{scope:w(n,"scope"),minLoc:P(n,"minLoc",1),maxDepth:P(n,"maxDepth",5),scanLimit:r.scanLimit}),o=Y(),s=b(n,"patch"),a=b(n,"json"),c=b(n,"verify")||s;if(s&&!b(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(i.batches.length===0){if(a){I("cleanup-plan",t,n,i,{analysisBudget:r.analysisBudget});return}return E.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=Xr(i),d=c?Kr(o,i):void 0;if(a){I("cleanup-plan",t,n,{result:i,verification:d},{analysisBudget:r.analysisBudget});return}if(s){let u=Zr(d,l);if(u.length>0){for(let f of u)console.error(`error: ${f}`);process.exitCode=1;return}let m=Ic(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.
480
+ Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),lm=K("cleanup-plan",({db:e,args:t,opts:n,budget:r})=>{let i=_r(e,{scope:w(n,"scope"),minLoc:P(n,"minLoc",1),maxDepth:P(n,"maxDepth",5),scanLimit:r.scanLimit}),o=Y(),s=b(n,"patch"),a=b(n,"json"),c=b(n,"verify")||s;if(s&&!b(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(i.batches.length===0){if(a){I("cleanup-plan",t,n,i,{analysisBudget:r.analysisBudget});return}return E.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=Xr(i),d=c?Kr(o,i):void 0;if(a){I("cleanup-plan",t,n,{result:i,verification:d},{analysisBudget:r.analysisBudget});return}if(s){let u=Zr(d,l);if(u.length>0){for(let f of u)console.error(`error: ${f}`);process.exitCode=1;return}let m=Ec(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.
481
481
  `);for(let u of i.batches){let m=u.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${u.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${u.depth}: dead once batch ${u.depth-1} lands (cascade, ${u.loc} LOC) \u2500\u2500`;console.log(m);for(let f of u.entries)console.log(` ${f.file}:${f.startLine+1}-${f.endLine+1} ${f.shortName} (${f.loc} LOC)`);u.filesEmptied.length>0&&console.log(` -> empties: ${u.filesEmptied.join(", ")}`),console.log("")}if(i.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let u of i.blocked)console.log(` ${u.shortName} (${u.file}) blocked by ${u.blockingFiles.join(", ")}`)}if(d){if(console.log(`
482
- 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 u=YR(d.checkers),m=XR(d.checkers);for(let f of d.batches)if(f.status==="verified")console.log(` Batch ${f.depth}: VERIFIED (${u})${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}`)}}}),lm=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=_r(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",1),maxDepth:P(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){E.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=Xr(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=Kr(a,o),l=Zr(c,s,{allowDirty:b(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}Yr(a,s);let d=s.reduce((m,f)=>m+f.entries.length,0),u=s.reduce((m,f)=>m+f.loc,0);console.log(`Applied ${s.length} verified cleanup batch(es): ${d} symbol(s), ${u} LOC.`)});function YR(e){return e.join(", ")}function XR(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var dm=K("recent-duplicates",({db:e,args:t,opts:n,budget:r})=>{let i=b(n,"full"),o=ba(e,{windowCommits:P(n,"window",100),minSimilarity:U(n,"minSimilarity"),limit:A(n,"limit",30),scope:w(n,"scope"),scanLimit:r.scanLimit,semantic:r.semantic,historyMode:i?"full":"bounded"});if(b(n,"json")){I("recent-duplicates",t,n,o,{analysisBudget:r.analysisBudget});return}if(!o.available)return E.empty("No git history available (not a repository, or git missing).");if(o.findings.length===0)return E.empty(`No recent re-implementations found (window: last ${o.windowCommits} commits).`);Ce("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${o.windowCommits} commits):
482
+ 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 u=XR(d.checkers),m=ZR(d.checkers);for(let f of d.batches)if(f.status==="verified")console.log(` Batch ${f.depth}: VERIFIED (${u})${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}`)}}}),dm=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=_r(e,{scope:w(t,"scope"),minLoc:P(t,"minLoc",1),maxDepth:P(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){E.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=Xr(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=Kr(a,o),l=Zr(c,s,{allowDirty:b(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}Yr(a,s);let d=s.reduce((m,f)=>m+f.entries.length,0),u=s.reduce((m,f)=>m+f.loc,0);console.log(`Applied ${s.length} verified cleanup batch(es): ${d} symbol(s), ${u} LOC.`)});function XR(e){return e.join(", ")}function ZR(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var um=K("recent-duplicates",({db:e,args:t,opts:n,budget:r})=>{let i=b(n,"full"),o=Sa(e,{windowCommits:P(n,"window",100),minSimilarity:U(n,"minSimilarity"),limit:A(n,"limit",30),scope:w(n,"scope"),scanLimit:r.scanLimit,semantic:r.semantic,historyMode:i?"full":"bounded"});if(b(n,"json")){I("recent-duplicates",t,n,o,{analysisBudget:r.analysisBudget});return}if(!o.available)return E.empty("No git history available (not a repository, or git missing).");if(o.findings.length===0)return E.empty(`No recent re-implementations found (window: last ${o.windowCommits} commits).`);Ce("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${o.windowCommits} commits):
483
483
  `);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(`
484
- ${o.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),um=de(({db:e,args:t,opts:n})=>{let r=b(n,"full"),i=ta(e,{doc:t[0]===void 0?void 0:L(t,0),limit:A(n,"limit",20),minCoupling:P(n,"minCoupling",3),includeSnapshotExcluded:r,historyMode:r?"full":"bounded"});if(b(n,"json")){I("doc-drift",t,n,i);return}if(!i.available)return E.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return E.empty(`No drifting docs found across ${i.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);Ce("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${i.docsScanned} docs scanned, ${i.commitsAnalyzed} commits analyzed):
484
+ ${o.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),pm=de(({db:e,args:t,opts:n})=>{let r=b(n,"full"),i=na(e,{doc:t[0]===void 0?void 0:L(t,0),limit:A(n,"limit",20),minCoupling:P(n,"minCoupling",3),includeSnapshotExcluded:r,historyMode:r?"full":"bounded"});if(b(n,"json")){I("doc-drift",t,n,i);return}if(!i.available)return E.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return E.empty(`No drifting docs found across ${i.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);Ce("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${i.docsScanned} docs scanned, ${i.commitsAnalyzed} commits analyzed):
485
485
  `);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 u=c.citationContexts?.[0];u&&console.log(` cited claim: ${Ln(u)}`)}}console.log(`
486
- Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),pm=ue("unused-params",{query:({db:e,opts:t,budget:n})=>ua(e,{scope:w(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName}
486
+ Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),mm=ue("unused-params",{query:({db:e,opts:t,budget:n})=>pa(e,{scope:w(t,"scope"),limit:A(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${M(e.file,e.startLine,e.endLine)} ${e.shortName}
487
487
  trailing unused: ${e.unusedTrailing.join(", ")} (${e.unusedTrailing.length} of ${e.paramCount} params -- type-safe to remove at the signature; check call sites for side-effectful arguments)`,emptyMessage:()=>"No trailing unused parameters found.",heuristicLabel:"unused trailing parameter candidates",after:e=>console.log(`
488
- ${e.length} function(s) with trailing unused parameters.`)});var mm=Se("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Bs(e,{minSimilarity:P(n,"minSimilarity",.62),minTokens:P(n,"minTokens",8),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{E.list(e,t=>{let n=[`
488
+ ${e.length} function(s) with trailing unused parameters.`)});var fm=Se("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Vs(e,{minSimilarity:P(n,"minSimilarity",.62),minTokens:P(n,"minTokens",8),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{E.list(e,t=>{let n=[`
489
489
  ${Math.round(t.similarity*100)}% similar React structure:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComponents.length&&n.push(` Shared components: ${t.sharedComponents.join(", ")}`),t.sharedNativeTags.length&&n.push(` Shared native tags: ${t.sharedNativeTags.join(", ")}`),t.sharedProps.length&&n.push(` Shared props: ${t.sharedProps.join(", ")}`),t.sharedEvents.length&&n.push(` Shared events: ${t.sharedEvents.join(", ")}`),t.sharedBindings.length&&n.push(` Shared bindings: ${t.sharedBindings.slice(0,20).join(", ")}`),n.join(`
490
490
  `)}),console.log(`
491
- ${e.length} duplicated React component pair(s) found.`)}}),fm=Se("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Vs(e,{minSimilarity:P(n,"minSimilarity",.45),minSharedBehaviors:P(n,"minSharedBehaviors",6),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{E.list(e,t=>{let n=[`
491
+ ${e.length} duplicated React component pair(s) found.`)}}),gm=Se("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Hs(e,{minSimilarity:P(n,"minSimilarity",.45),minSharedBehaviors:P(n,"minSharedBehaviors",6),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{E.list(e,t=>{let n=[`
492
492
  ${Math.round(t.similarity*100)}% similar React behavior:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${t.reason}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedHooks.length&&n.push(` Shared hooks: ${t.sharedHooks.join(", ")}`),t.sharedReactHooks.length&&n.push(` Shared React hooks: ${t.sharedReactHooks.join(", ")}`),t.sharedEffects.length&&n.push(` Shared effects: ${t.sharedEffects.join(", ")}`),t.sharedState.length&&n.push(` Shared state: ${t.sharedState.join(", ")}`),t.sharedRequests.length&&n.push(` Shared requests: ${t.sharedRequests.join(", ")}`),t.sharedHandlers.length&&n.push(` Shared handlers: ${t.sharedHandlers.slice(0,12).join(", ")}`),t.sharedHandlerVerbs.length&&n.push(` Shared action verbs: ${t.sharedHandlerVerbs.slice(0,12).join(", ")}`),n.join(`
493
493
  `)}),console.log(`
494
- ${e.length} React hook candidate pair(s) found.`)}}),gm=Se("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Hs(e,{minComponentLines:P(n,"minComponentLines",300),minFileLines:P(n,"minFileLines",800),minJsxTokens:P(n,"minJsxTokens",80),minBehaviorTokens:P(n,"minBehaviorTokens",40),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{E.list(e,t=>[`
494
+ ${e.length} React hook candidate pair(s) found.`)}}),hm=Se("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Ws(e,{minComponentLines:P(n,"minComponentLines",300),minFileLines:P(n,"minFileLines",800),minJsxTokens:P(n,"minJsxTokens",80),minBehaviorTokens:P(n,"minBehaviorTokens",40),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{E.list(e,t=>[`
495
495
  ${t.componentLines} component line(s): ${t.component} (${t.file})`,` Dominant pressure: ${t.dominantPressure} (context: ${t.contextKind})`,` Pressure kinds: ${t.pressureKinds.join(", ")}`,` File lines: ${t.fileLines}; JSX tokens: ${t.jsxTokens}; behavior tokens: ${t.behaviorTokens}`,` Recommendation: ${t.recommendationKind} - ${t.recommendation}`,` Reasons: ${t.reasons.join("; ")}`].join(`
496
496
  `)),console.log(`
497
- ${e.length} large React component(s) found.`)}}),hm=Se("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Ws(e,{minSimilarity:P(n,"minSimilarity",.62),minTokens:P(n,"minTokens",8),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{E.list(e,t=>{let n=[`
497
+ ${e.length} large React component(s) found.`)}}),ym=Se("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:r})=>Gs(e,{minSimilarity:P(n,"minSimilarity",.62),minTokens:P(n,"minTokens",8),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{E.list(e,t=>{let n=[`
498
498
  ${Math.round(t.similarity*100)}% similar Vue structure:`,` ${t.fileA}`,` ${t.fileB}`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComponents.length&&n.push(` Shared components: ${t.sharedComponents.join(", ")}`),t.sharedProps.length&&n.push(` Shared props: ${t.sharedProps.join(", ")}`),t.sharedEvents.length&&n.push(` Shared events: ${t.sharedEvents.join(", ")}`),t.sharedDirectives.length&&n.push(` Shared directives: ${t.sharedDirectives.join(", ")}`),t.sharedSlots.length&&n.push(` Shared slots: ${t.sharedSlots.join(", ")}`),t.sharedIdentifiers.length&&n.push(` Shared identifiers: ${t.sharedIdentifiers.slice(0,20).join(", ")}`),n.join(`
499
499
  `)}),console.log(`
500
- ${e.length} duplicated Vue component pair(s) found.`)}}),ym=Se("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Gs(e,{minSimilarity:P(n,"minSimilarity",.45),minSharedBehaviors:P(n,"minSharedBehaviors",6),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{E.list(e,t=>{let n=[`
500
+ ${e.length} duplicated Vue component pair(s) found.`)}}),bm=Se("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:r})=>Us(e,{minSimilarity:P(n,"minSimilarity",.45),minSharedBehaviors:P(n,"minSharedBehaviors",6),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{E.list(e,t=>{let n=[`
501
501
  ${Math.round(t.similarity*100)}% similar Vue behavior:`,` ${t.fileA}`,` ${t.fileB}`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${t.reason}`];return t.evidenceClassReasons.length&&n.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.sharedComposables.length&&n.push(` Shared composables: ${t.sharedComposables.join(", ")}`),t.sharedStores.length&&n.push(` Shared stores: ${t.sharedStores.join(", ")}`),t.sharedRequests.length&&n.push(` Shared requests: ${t.sharedRequests.join(", ")}`),t.sharedLifecycle.length&&n.push(` Shared lifecycle: ${t.sharedLifecycle.join(", ")}`),t.sharedFunctions.length&&n.push(` Shared functions: ${t.sharedFunctions.slice(0,12).join(", ")}`),t.sharedFunctionVerbs.length&&n.push(` Shared action verbs: ${t.sharedFunctionVerbs.slice(0,12).join(", ")}`),t.sharedBindings.length&&n.push(` Shared bindings: ${t.sharedBindings.slice(0,20).join(", ")}`),t.sharedTemplateEvents.length&&n.push(` Shared template events: ${t.sharedTemplateEvents.slice(0,20).join(", ")}`),n.join(`
502
502
  `)}),console.log(`
503
- ${e.length} Vue composable candidate pair(s) found.`)}}),bm=Se("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Us(e,{minTotalLines:b(n,"reviewThresholds")&&hc(n,"minTotalLines")==="default"?300:P(n,"minTotalLines",800),minTemplateLines:P(n,"minTemplateLines",300),minScriptLines:P(n,"minScriptLines",300),minStyleLines:P(n,"minStyleLines",500),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{E.list(e,t=>{let n=[`
503
+ ${e.length} Vue composable candidate pair(s) found.`)}}),Sm=Se("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:r})=>Js(e,{minTotalLines:b(n,"reviewThresholds")&&yc(n,"minTotalLines")==="default"?300:P(n,"minTotalLines",800),minTemplateLines:P(n,"minTemplateLines",300),minScriptLines:P(n,"minScriptLines",300),minStyleLines:P(n,"minStyleLines",500),limit:A(n,"limit",20),scope:w(n,"scope"),scanLimit:r.scanLimit,filePattern:B(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{E.list(e,t=>{let n=[`
504
504
  ${t.totalLines} total line(s): ${t.file}`,` Dominant pressure: ${t.dominantPressure} (context: ${t.contextKind})`,` Pressure kinds: ${t.pressureKinds.join(", ")}`,` Blocks: template ${t.templateLines}, script ${t.scriptLines}, style ${t.styleLines}, external script ${t.externalScriptLines}, custom ${t.customBlockLines}`,` Recommendation: ${t.recommendationKind} - ${t.recommendation}`];return t.externalScriptPaths.length&&n.push(` External scripts: ${t.externalScriptPaths.join(", ")}`),n.push(` Reasons: ${t.reasons.join("; ")}`),n.join(`
505
505
  `)}),console.log(`
506
- ${e.length} large Vue view pressure file(s) found.`)}});function ie(e){return{docs:$("Cleanup"),...e}}function X({heuristicLabel:e,...t}){return ie({...t,heuristic:{label:e}})}var Pr=[ie({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:C([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings",v,30),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:$("Cleanup",["scip-query unused-params -s src/services"]),handler:pm}),ie({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",v,1),p("--max-depth <n>","Maximum cascade depth",v,5),p("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),p("--patch","With --verify, print the compiler-verified deletion patch to stdout"),p("--json","Output as JSON for programmatic consumption"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:cm}),ie({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",v,1),p("--max-depth <n>","Maximum cascade depth",v,5),p("--verified","Required: verify the selected cleanup batch before applying it"),p("--batch <n>","Apply one batch depth",v),p("--all","Apply every compiler-verified batch in the plan"),p("--force-dirty","Allow applying when plan files already have working-tree edits"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:lm}),ie({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:C([p("--window <n>",'How many commits back counts as "recent"',v,100),p("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",ge),p("-n, --limit <n>","Maximum findings",v,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded semantic and git-history analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:$("Cleanup",["scip-query recent-duplicates --window 50"]),handler:dm}),ie({id:"doc-drift",command:"doc-drift [doc]",description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:C([p("-n, --limit <n>","Maximum docs to report",v,20),p("--min-coupling <n>","Minimum historical co-changes to track a subject",v,3),p("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:$("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:um}),ie({id:"dead",command:"dead [scope]",description:"Find repository-dead code, file-internal symbols, and implicit-usage signals",options:C([p("--min-loc <n>","Only show symbols >= N lines",v,1),p("--include-tests","Include definitions from test files (test references always count)"),p("--skip-barrels","Ignore refs from barrel re-export files"),p("--include-members","Include class members"),p("--only-dead","Show only [dead code] symbols (skip file-internal and implicit-usage signals)"),p("--only-internal","Show only [file-internal only] symbols (skip dead-code and implicit-usage signals)"),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query dead --min-loc 10"]),handler:Bp}),ie({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:Vp}),ie({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum lines of code",v,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:Hp}),X({id:"similar",command:"similar [symbol] [other]",description:"Find heuristic function similarity candidates from callee fingerprints",options:C([p("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",ge,.4),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-callees <n>","Minimum callees to consider",v,4),p("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),p("--plan","Render a consolidation preview for two symbols"),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:Qp}),X({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:C([p("--min-similarity <n>","Minimum Jaccard similarity (0-1)",ge,.5),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-deps <n>","Minimum dependencies to consider",v),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:Yp}),X({id:"react-component-duplicates",command:"react-component-duplicates [file]",description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:C([p("--min-similarity <n>","Minimum JSX structure similarity (0-1)",ge,.62),p("--min-tokens <n>","Minimum structural tokens to consider",v,8),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:mm}),X({id:"react-hook-candidates",command:"react-hook-candidates [file]",description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:C([p("--min-similarity <n>","Minimum behavior similarity (0-1)",ge,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",v,6),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:fm}),X({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:C([p("--min-component-lines <n>","Minimum component lines",v,300),p("--min-file-lines <n>","Minimum file lines",v,800),p("--min-jsx-tokens <n>","Minimum JSX structure tokens",v,80),p("--min-behavior-tokens <n>","Minimum behavior tokens",v,40),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:gm}),X({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:C([p("--min-similarity <n>","Minimum template similarity (0-1)",ge,.62),p("--min-tokens <n>","Minimum structural tokens to consider",v,8),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:hm}),X({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:C([p("--min-similarity <n>","Minimum behavior similarity (0-1)",ge,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",v,6),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:ym}),X({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:C([p("--min-total-lines <n>","Minimum total component lines",v,800),p("--min-template-lines <n>","Minimum template lines",v,300),p("--min-script-lines <n>","Minimum script lines",v,300),p("--min-style-lines <n>","Minimum style lines",v,500),p("--review-thresholds","Use lower review thresholds without changing health scoring"),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:bm}),X({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:C([p("--min-similarity <n>","Minimum chain similarity (0-1)",ge,.5),p("-n, --limit <n>","Number of results",v,15),p("-s, --scope <path>","Limit to files matching path"),p("--min-length <n>","Minimum chain length",v,3),p("--max-length <n>","Maximum chain length",v,8),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Xp}),X({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum function LOC",v,10),p("--min-callees <n>","Minimum callees to analyze",v,6),p("-n, --limit <n>","Number of results",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Wp}),X({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:C([p("-s, --scope <path>","Limit scan mode to files matching path"),p("--min-consumers <n>","Minimum consumers in scan mode",v,1),p("-n, --limit <n>","Number of results",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:Gp}),X({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports and layer violations by default; pass --patterns for pattern deviations too",options:C([p("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",_e,5),p("--patterns",'Also include pattern-deviation findings ("only sibling importing X") \u2014 off by default: low precision at scale (21.2 calibration)',void 0,!1),p("-n, --limit <n>","Number of results",v,50),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:Zp}),X({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",v,15),p("-n, --limit <n>","Number of results",v,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:Up}),X({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",v,15),p("-n, --limit <n>","Number of results",v,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:Jp}),X({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",v,3),p("-n, --limit <n>","Number of results",v,30),p("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:zp}),X({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",v,10),p("-n, --limit <n>","Number of results",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:Kp}),ie({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Deprecated alias for similar <symbol1> <symbol2> --plan",options:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:em}),Rp({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",v,30),p("--full","Run unbounded analysis on large indexes")],docs:$("Cleanup"),query:({db:e,opts:t})=>La(e,{scope:w(t,"scope"),limit:A(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
506
+ ${e.length} large Vue view pressure file(s) found.`)}});function ie(e){return{docs:$("Cleanup"),...e}}function X({heuristicLabel:e,...t}){return ie({...t,heuristic:{label:e}})}var Pr=[ie({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:C([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings",v,30),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:$("Cleanup",["scip-query unused-params -s src/services"]),handler:mm}),ie({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",v,1),p("--max-depth <n>","Maximum cascade depth",v,5),p("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),p("--patch","With --verify, print the compiler-verified deletion patch to stdout"),p("--json","Output as JSON for programmatic consumption"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:lm}),ie({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",v,1),p("--max-depth <n>","Maximum cascade depth",v,5),p("--verified","Required: verify the selected cleanup batch before applying it"),p("--batch <n>","Apply one batch depth",v),p("--all","Apply every compiler-verified batch in the plan"),p("--force-dirty","Allow applying when plan files already have working-tree edits"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:dm}),ie({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:C([p("--window <n>",'How many commits back counts as "recent"',v,100),p("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",ge),p("-n, --limit <n>","Maximum findings",v,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded semantic and git-history analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:$("Cleanup",["scip-query recent-duplicates --window 50"]),handler:um}),ie({id:"doc-drift",command:"doc-drift [doc]",description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:C([p("-n, --limit <n>","Maximum docs to report",v,20),p("--min-coupling <n>","Minimum historical co-changes to track a subject",v,3),p("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:$("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:pm}),ie({id:"dead",command:"dead [scope]",description:"Find repository-dead code, file-internal symbols, and implicit-usage signals",options:C([p("--min-loc <n>","Only show symbols >= N lines",v,1),p("--include-tests","Include definitions from test files (test references always count)"),p("--skip-barrels","Ignore refs from barrel re-export files"),p("--include-members","Include class members"),p("--only-dead","Show only [dead code] symbols (skip file-internal and implicit-usage signals)"),p("--only-internal","Show only [file-internal only] symbols (skip dead-code and implicit-usage signals)"),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query dead --min-loc 10"]),handler:Vp}),ie({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:Hp}),ie({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum lines of code",v,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:Wp}),X({id:"similar",command:"similar [symbol] [other]",description:"Find heuristic function similarity candidates from callee fingerprints",options:C([p("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",ge,.4),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-callees <n>","Minimum callees to consider",v,4),p("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),p("--plan","Render a consolidation preview for two symbols"),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:Yp}),X({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:C([p("--min-similarity <n>","Minimum Jaccard similarity (0-1)",ge,.5),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-deps <n>","Minimum dependencies to consider",v),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:Xp}),X({id:"react-component-duplicates",command:"react-component-duplicates [file]",description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:C([p("--min-similarity <n>","Minimum JSX structure similarity (0-1)",ge,.62),p("--min-tokens <n>","Minimum structural tokens to consider",v,8),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:fm}),X({id:"react-hook-candidates",command:"react-hook-candidates [file]",description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:C([p("--min-similarity <n>","Minimum behavior similarity (0-1)",ge,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",v,6),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:gm}),X({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:C([p("--min-component-lines <n>","Minimum component lines",v,300),p("--min-file-lines <n>","Minimum file lines",v,800),p("--min-jsx-tokens <n>","Minimum JSX structure tokens",v,80),p("--min-behavior-tokens <n>","Minimum behavior tokens",v,40),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:hm}),X({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:C([p("--min-similarity <n>","Minimum template similarity (0-1)",ge,.62),p("--min-tokens <n>","Minimum structural tokens to consider",v,8),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:ym}),X({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:C([p("--min-similarity <n>","Minimum behavior similarity (0-1)",ge,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",v,6),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:bm}),X({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:C([p("--min-total-lines <n>","Minimum total component lines",v,800),p("--min-template-lines <n>","Minimum template lines",v,300),p("--min-script-lines <n>","Minimum script lines",v,300),p("--min-style-lines <n>","Minimum style lines",v,500),p("--review-thresholds","Use lower review thresholds without changing health scoring"),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Sm}),X({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:C([p("--min-similarity <n>","Minimum chain similarity (0-1)",ge,.5),p("-n, --limit <n>","Number of results",v,15),p("-s, --scope <path>","Limit to files matching path"),p("--min-length <n>","Minimum chain length",v,3),p("--max-length <n>","Maximum chain length",v,8),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Zp}),X({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum function LOC",v,10),p("--min-callees <n>","Minimum callees to analyze",v,6),p("-n, --limit <n>","Number of results",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Gp}),X({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:C([p("-s, --scope <path>","Limit scan mode to files matching path"),p("--min-consumers <n>","Minimum consumers in scan mode",v,1),p("-n, --limit <n>","Number of results",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:$("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:Up}),X({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports and layer violations by default; pass --patterns for pattern deviations too",options:C([p("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",_e,5),p("--patterns",'Also include pattern-deviation findings ("only sibling importing X") \u2014 off by default: low precision at scale (21.2 calibration)',void 0,!1),p("-n, --limit <n>","Number of results",v,50),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:em}),X({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",v,15),p("-n, --limit <n>","Number of results",v,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:Jp}),X({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",v,15),p("-n, --limit <n>","Number of results",v,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:zp}),X({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers (high false-positive rate on codebases with intentional layering/ambient types \u2014 treat as exploration, not findings)",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",v,3),p("-n, --limit <n>","Number of results",v,30),p("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:Kp}),X({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",v,10),p("-n, --limit <n>","Number of results",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:Qp}),ie({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Deprecated alias for similar <symbol1> <symbol2> --plan",options:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:tm}),kp({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",v,30),p("--full","Run unbounded analysis on large indexes")],docs:$("Cleanup"),query:({db:e,opts:t})=>Aa(e,{scope:w(t,"scope"),limit:A(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
507
507
  barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
508
508
  Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
509
509
  Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
510
- ${e.length} redundant re-export(s).`)}),ie({id:"duplicate-bodies",command:"duplicate-bodies",description:"Find exact duplicate small-body candidates across files",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC per function body",v,15),p("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",v,3),p("-n, --limit <n>","Number of groups",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:nm}),ie({id:"twin-drift",command:"twin-drift",description:"Twin drift candidates: same-name (or near-name) functions across files with diverged bodies",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-similarity <n>","Minimum normalized-token Jaccard similarity to report as divergent (0-1)",ge,.3),p("--include-homonyms","Also report same-name pairs below the similarity threshold (likely coincidental)"),p("-n, --limit <n>","Number of groups",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:rm}),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:C([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",v,30),p("--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:im}),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:C([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",v,30),p("--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:om}),ie({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:C([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings per sub-check",v,30),p("--rot-days <n>","Skips older than this many days are reported as rot",v,60),p("--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:sm}),ie({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:C([p("--out <path>","Output path for the generated vitest file (default: tests/generated/twin-ab/<a>-vs-<b>.test.ts)"),p("--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:am}),ie({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC per function",v,3),p("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",v,12),p("-n, --limit <n>","Number of groups",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:tm})];var ZR=de(({db:e,args:t,opts:n})=>{let r=bt(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: ${Ue(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Sm=[{id:"stats",command:"stats",description:"Show index statistics",options:[lc()],renderShape:"custom",docs:$("Core"),handler:ZR}];var ek=Dn("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>js(e,{limit:A(t,"limit",20),scope:w(t,"scope"),minFanIn:P(t,"minFanIn",2),minFanOut:P(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.actionTier.padEnd(6)} ${e.riskKind.padEnd(20)} ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),tk=de(({db:e,args:t,opts:n})=>{let r=B(t,0),i=A(n,"limit",30);if(r){let c=ws(e,r);if(b(n,"json")){I("fan-in",t,n,{mode:"symbol",symbol:r,rows:c});return}if(c.length===0)return E.empty(`No fan-in for ${r}.`);E.list(c,l=>` ${String(l.count).padStart(4)} files ${l.name}`);return}let o=Ps(e,{limit:i,scope:w(n,"scope")});if(b(n,"json")){I("fan-in",t,n,{mode:"top",rows:o});return}let s=new Map;for(let c of o)s.set(c.name,(s.get(c.name)??0)+1);let a=new Set([...s].filter(([,c])=>c>1).map(([c])=>c));E.table(["files","symbol"],o.map(c=>` ${String(c.count).padStart(5)} ${c.name}${a.has(c.name)?` [${c.definedIn}]`:""}`))}),nk=de(({db:e,args:t,opts:n})=>{let r=B(t,0),i=A(n,"limit",30);if(r){let s=$s(e,r);if(b(n,"json")){I("fan-out",t,n,{mode:"file",file:r,rows:s});return}if(s.length===0)return E.empty(`No fan-out for ${r}.`);E.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=Cs(e,{limit:i,scope:w(n,"scope")});if(b(n,"json")){I("fan-out",t,n,{mode:"top",rows:o});return}E.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),rk=de(({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=Ts(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=Is(e,{limit:o,scope:w(n,"scope")});if(b(n,"json")){I("coupling",t,n,{mode:"top",rows:s});return}E.table(["tier","risk","shared","file1 \u2192 file2"],s.map(a=>` ${a.actionTier.padEnd(6)} ${a.couplingKind.padEnd(22)} ${String(a.sharedSymbols).padStart(6)} ${a.file1} \u2192 ${a.file2}`))}),ik=it({commandName:"cycles",query:({db:e,opts:t})=>Es(e,{scope:w(t,"scope"),maxDepth:P(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(`
510
+ ${e.length} redundant re-export(s).`)}),ie({id:"duplicate-bodies",command:"duplicate-bodies",description:"Find exact duplicate small-body candidates across files",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC per function body",v,15),p("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",v,3),p("-n, --limit <n>","Number of groups",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:rm}),ie({id:"twin-drift",command:"twin-drift",description:"Twin drift candidates: same-name (or near-name) functions across files with diverged bodies",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-similarity <n>","Minimum normalized-token Jaccard similarity to report as divergent (0-1)",ge,.3),p("--include-homonyms","Also report same-name pairs below the similarity threshold (likely coincidental)"),p("-n, --limit <n>","Number of groups",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:im}),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:C([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",v,30),p("--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:om}),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:C([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",v,30),p("--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:sm}),ie({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:C([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings per sub-check",v,30),p("--rot-days <n>","Skips older than this many days are reported as rot",v,60),p("--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:am}),ie({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:C([p("--out <path>","Output path for the generated vitest file (default: tests/generated/twin-ab/<a>-vs-<b>.test.ts)"),p("--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:cm}),ie({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC per function",v,3),p("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",v,12),p("-n, --limit <n>","Number of groups",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:nm})];var ek=de(({db:e,args:t,opts:n})=>{let r=bt(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: ${Ue(r.indexSizeBytes)}`),r.lastBuilt&&console.log(`Last built: ${r.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),vm=[{id:"stats",command:"stats",description:"Show index statistics",options:[dc()],renderShape:"custom",docs:$("Core"),handler:ek}];var tk=Dn("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Ls(e,{limit:A(t,"limit",20),scope:w(t,"scope"),minFanIn:P(t,"minFanIn",2),minFanOut:P(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.actionTier.padEnd(6)} ${e.riskKind.padEnd(20)} ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),nk=de(({db:e,args:t,opts:n})=>{let r=B(t,0),i=A(n,"limit",30);if(r){let c=$s(e,r);if(b(n,"json")){I("fan-in",t,n,{mode:"symbol",symbol:r,rows:c});return}if(c.length===0)return E.empty(`No fan-in for ${r}.`);E.list(c,l=>` ${String(l.count).padStart(4)} files ${l.name}`);return}let o=Cs(e,{limit:i,scope:w(n,"scope")});if(b(n,"json")){I("fan-in",t,n,{mode:"top",rows:o});return}let s=new Map;for(let c of o)s.set(c.name,(s.get(c.name)??0)+1);let a=new Set([...s].filter(([,c])=>c>1).map(([c])=>c));E.table(["files","symbol"],o.map(c=>` ${String(c.count).padStart(5)} ${c.name}${a.has(c.name)?` [${c.definedIn}]`:""}`))}),rk=de(({db:e,args:t,opts:n})=>{let r=B(t,0),i=A(n,"limit",30);if(r){let s=Ps(e,r);if(b(n,"json")){I("fan-out",t,n,{mode:"file",file:r,rows:s});return}if(s.length===0)return E.empty(`No fan-out for ${r}.`);E.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=Ts(e,{limit:i,scope:w(n,"scope")});if(b(n,"json")){I("fan-out",t,n,{mode:"top",rows:o});return}E.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),ik=de(({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=Is(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=Es(e,{limit:o,scope:w(n,"scope")});if(b(n,"json")){I("coupling",t,n,{mode:"top",rows:s});return}E.table(["tier","risk","shared","file1 \u2192 file2"],s.map(a=>` ${a.actionTier.padEnd(6)} ${a.couplingKind.padEnd(22)} ${String(a.sharedSymbols).padStart(6)} ${a.file1} \u2192 ${a.file2}`))}),ok=it({commandName:"cycles",query:({db:e,opts:t})=>js(e,{scope:w(t,"scope"),maxDepth:P(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
511
  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(`
512
- ${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.)`)}}),ok=it({commandName:"deep-chains",query:({db:e,opts:t})=>Os(e,{limit:A(t,"limit",10),scope:w(t,"scope"),minDepth:P(t,"minDepth",3)}),emptyMessage:e=>e.length===0?"No deep chains found.":void 0,render:e=>{for(let t=0;t<e.length;t++){console.log(`
513
- 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("; ")}`)}}}),vm=[Sr({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[p("-n, --limit <n>","Number of results",v,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")],docs:$("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>Ss(e,{limit:A(t,"limit",30),scope:w(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"Count files referencing an exact symbol; top JSON rows include exact symbol identity",options:C([p("-n, --limit <n>","Number of results for top mode",v,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:tk},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:C([p("-n, --limit <n>","Number of results for top mode",v,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:nk},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:C([p("-n, --limit <n>","Number of results for top mode",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:rk},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--max-depth <n>","Bound DFS search depth",v,10)]),renderShape:"custom",docs:$("Graph"),handler:ik},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:C([p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-fan-in <n>","Minimum fan-in",v,2),p("--min-fan-out <n>","Minimum fan-out",v,2),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:$("Graph"),handler:ek},{id:"deep-chains",command:"deep-chains",description:"Find the longest condensed dependency-component chains",options:C([p("-n, --limit <n>","Number of chains to show",v,10),p("-s, --scope <path>","Limit to files matching path"),p("--min-depth <n>","Minimum chain depth",v,3),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:ok},vr({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[p("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:$("Graph"),query:({db:e,args:t,budget:n})=>Bt(e,String(t[0]),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e?void 0:ae(t,String(n[0]),"Symbol not found."),before:(e,{db:t,args:n})=>{e&&(se(t,String(n[0])),console.log(`Symbol: ${e.shortName}
514
- `))},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 sk=K("complexity",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=Sa(e,i,{semantic:r.semantic});if(b(n,"json")){I("complexity",t,n,ve(e,i,o,"complexity"),{analysisBudget:r.analysisBudget});return}if(!o)return E.empty(ae(e,i,"Symbol not found."));se(e,i),console.log(`${M(o.relativePath,o.startLine,o.endLine)} ${o.shortName}
515
- `),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}`)}),ak=de(({db:e,args:t,opts:n})=>{let r=Aa(e,{samples:P(n,"samples",50),scope:w(n,"scope")});if(b(n,"json")){I("self-audit",t,n,r);return}if(!r.available)return E.empty("No semantic or source-backed oracle available to audit against.");let i=r.oracleKind==="source"?"source facts":"compiler semantics";console.log(`Sampled ${r.sampleSize} symbols; ${i} oracle answered ${Math.round(r.oracleCoverage*100)}%.
512
+ ${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.)`)}}),sk=it({commandName:"deep-chains",query:({db:e,opts:t})=>Ns(e,{limit:A(t,"limit",10),scope:w(t,"scope"),minDepth:P(t,"minDepth",3)}),emptyMessage:e=>e.length===0?"No deep chains found.":void 0,render:e=>{for(let t=0;t<e.length;t++){console.log(`
513
+ 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("; ")}`)}}}),xm=[Sr({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[p("-n, --limit <n>","Number of results",v,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")],docs:$("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>vs(e,{limit:A(t,"limit",30),scope:w(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"Count files referencing an exact symbol; top JSON rows include exact symbol identity",options:C([p("-n, --limit <n>","Number of results for top mode",v,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:nk},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:C([p("-n, --limit <n>","Number of results for top mode",v,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:rk},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:C([p("-n, --limit <n>","Number of results for top mode",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:ik},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:C([p("-s, --scope <path>","Limit to files matching path"),p("--max-depth <n>","Bound DFS search depth",v,10)]),renderShape:"custom",docs:$("Graph"),handler:ok},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:C([p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-fan-in <n>","Minimum fan-in",v,2),p("--min-fan-out <n>","Minimum fan-out",v,2),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:$("Graph"),handler:tk},{id:"deep-chains",command:"deep-chains",description:"Find the longest condensed dependency-component chains",options:C([p("-n, --limit <n>","Number of chains to show",v,10),p("-s, --scope <path>","Limit to files matching path"),p("--min-depth <n>","Minimum chain depth",v,3),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:$("Graph"),handler:sk},vr({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[p("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:$("Graph"),query:({db:e,args:t,budget:n})=>Bt(e,String(t[0]),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e?void 0:ae(t,String(n[0]),"Symbol not found."),before:(e,{db:t,args:n})=>{e&&(se(t,String(n[0])),console.log(`Symbol: ${e.shortName}
514
+ `))},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 ak=K("complexity",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=va(e,i,{semantic:r.semantic});if(b(n,"json")){I("complexity",t,n,ve(e,i,o,"complexity"),{analysisBudget:r.analysisBudget});return}if(!o)return E.empty(ae(e,i,"Symbol not found."));se(e,i),console.log(`${M(o.relativePath,o.startLine,o.endLine)} ${o.shortName}
515
+ `),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}`)}),ck=de(({db:e,args:t,opts:n})=>{let r=Da(e,{samples:P(n,"samples",50),scope:w(n,"scope")});if(b(n,"json")){I("self-audit",t,n,r);return}if(!r.available)return E.empty("No semantic or source-backed oracle available to audit against.");let i=r.oracleKind==="source"?"source facts":"compiler semantics";console.log(`Sampled ${r.sampleSize} symbols; ${i} oracle answered ${Math.round(r.oracleCoverage*100)}%.
516
516
  `),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(`
517
- 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(", ")}`)}}),xm=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",options:C([p("--samples <n>","Number of symbols to sample",v,50),p("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:$("Health",["scip-query self-audit --samples 100"]),handler:ak},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Health"),handler:sk}];var ck=de(({db:e,args:t,opts:n})=>{let r=L(t,0),i=Qs(e,r,{maxDepth:P(n,"maxDepth",5),scope:w(n,"scope")});if(b(n,"json")){I("affected",t,n,ve(e,r,i,"affected"));return}if(i.length===0)return E.empty(ae(e,r,"No affected symbols found."));se(e,r);let o=-1;for(let s of i)s.depth!==o&&(console.log(`
517
+ 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(", ")}`)}}),Rm=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",options:C([p("--samples <n>","Number of symbols to sample",v,50),p("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:$("Health",["scip-query self-audit --samples 100"]),handler:ck},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Health"),handler:ak}];var lk=de(({db:e,args:t,opts:n})=>{let r=L(t,0),i=Ys(e,r,{maxDepth:P(n,"maxDepth",5),scope:w(n,"scope")});if(b(n,"json")){I("affected",t,n,ve(e,r,i,"affected"));return}if(i.length===0)return E.empty(ae(e,r,"No affected symbols found."));se(e,r);let o=-1;for(let s of i)s.depth!==o&&(console.log(`
518
518
  \u2500\u2500 Depth ${s.depth} \u2500\u2500`),o=s.depth),console.log(` ${s.file} ${s.shortName}`);console.log(`
519
- ${i.length} affected symbol(s) across ${new Set(i.map(s=>s.file)).size} files.`)}),lk=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=Xs(e,i,{minTogether:P(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 E.empty("No git history available (not a repository, or git missing).");if(s.findings.length===0)return E.empty(i?`No co-change partners found for ${i} in ${s.commitsAnalyzed} commits.`:`No hidden coupling found in ${s.commitsAnalyzed} commits.`);Ce("co-change candidates"),console.log(i?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
519
+ ${i.length} affected symbol(s) across ${new Set(i.map(s=>s.file)).size} files.`)}),dk=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=Zs(e,i,{minTogether:P(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 E.empty("No git history available (not a repository, or git missing).");if(s.findings.length===0)return E.empty(i?`No co-change partners found for ${i} in ${s.commitsAnalyzed} commits.`:`No hidden coupling found in ${s.commitsAnalyzed} commits.`);Ce("co-change candidates"),console.log(i?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
520
520
  `:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${s.commitsAnalyzed} commits analyzed):
521
521
  `),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.
522
- `);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 ${dk(a.lastTogetherAt)}`),console.log(` subjects: ${uk(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
523
- ${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function dk(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function uk(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 pk=K("change-surface",({db:e,args:t,opts:n,budget:r})=>{let i=Ys(e,L(t,0),{semantic:r.semantic});if(b(n,"json")){I("change-surface",t,n,i,{analysisBudget:r.analysisBudget});return}if(!i)return E.empty("File not found in index.");console.log(`File: ${i.file}`),console.log(`External consumers: ${i.totalExternalConsumers}
524
- `),E.list(i.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${oe(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),mk=K("incomplete-migration",({db:e,args:t,opts:n,budget:r})=>{let i=da(e,{base:w(n,"base"),minContainment:P(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 E.empty("No git history available (not a repository, or git missing).");if(i.changedFiles.length===0)return E.empty(`No changes vs ${i.base}.`);console.log(`Incomplete migrations vs ${i.base}: ${i.changedFiles.length} changed file(s), ${i.helpersChecked} new helper(s) scored.`),i.note&&console.log(` note: ${i.note}`);for(let o of i.skipped)console.log(` skipped ${o.helperShortName} (${o.helperFile}): ${o.reason}`);if(i.findings.length===0){console.log(`
522
+ `);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 ${uk(a.lastTogetherAt)}`),console.log(` subjects: ${pk(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
523
+ ${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function uk(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function pk(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 mk=K("change-surface",({db:e,args:t,opts:n,budget:r})=>{let i=Xs(e,L(t,0),{semantic:r.semantic});if(b(n,"json")){I("change-surface",t,n,i,{analysisBudget:r.analysisBudget});return}if(!i)return E.empty("File not found in index.");console.log(`File: ${i.file}`),console.log(`External consumers: ${i.totalExternalConsumers}
524
+ `),E.list(i.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${oe(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),fk=K("incomplete-migration",({db:e,args:t,opts:n,budget:r})=>{let i=ua(e,{base:w(n,"base"),minContainment:P(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 E.empty("No git history available (not a repository, or git missing).");if(i.changedFiles.length===0)return E.empty(`No changes vs ${i.base}.`);console.log(`Incomplete migrations vs ${i.base}: ${i.changedFiles.length} changed file(s), ${i.helpersChecked} new helper(s) scored.`),i.note&&console.log(` note: ${i.note}`);for(let o of i.skipped)console.log(` skipped ${o.helperShortName} (${o.helperFile}): ${o.reason}`);if(i.findings.length===0){console.log(`
525
525
  No incomplete migrations detected.`);return}Ce("incomplete migration candidates");for(let o of i.findings){console.log(`
526
526
  ${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(`
527
- ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function fk(e){let t=Array.isArray(e)?e:[],n=t.filter(r=>!Br.includes(r));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${Br.join(", ")}`),process.exit(1)),t}var gk=de(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&Nn(Ht()))return;let r=b(t,"full"),i=ic(e,"diff-gate",r,{quiet:n||b(t,"json")}),o={base:w(t,"base"),minTogether:P(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:fk(t.skip)},s=St(e,o),a=In(s.findings),c=Tn(s),l=Hn(e,s,{replayGate:f=>St(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=wa(f,g,h),S=$a(f,s.checksRun),x=oc(i.analysisBudget),k=[...y?[y]:[],Wt(s),...S,...x?[x]:[]];console.error(k.join(`
527
+ ${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function gk(e){let t=Array.isArray(e)?e:[],n=t.filter(r=>!Br.includes(r));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${Br.join(", ")}`),process.exit(1)),t}var hk=de(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&Nn(Ht()))return;let r=b(t,"full"),i=oc(e,"diff-gate",r,{quiet:n||b(t,"json")}),o={base:w(t,"base"),minTogether:P(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:gk(t.skip)},s=St(e,o),a=In(s.findings),c=Tn(s),l=Hn(e,s,{replayGate:f=>St(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=$a(f,g,h),S=Pa(f,s.checksRun),x=sc(i.analysisBudget),k=[...y?[y]:[],Wt(s),...S,...x?[x]:[]];console.error(k.join(`
528
528
  `)),process.exitCode=2;return}if(c){console.error("FAIL (gate error): could not compute the git diff - zero checks ran; the gate fails closed. Check --base and repository state."),process.exitCode=1;return}if(s.changedFiles.length===0)return E.empty(s.note??`No changes vs ${s.base}.`);console.log(`Diff gate vs ${s.base}: ${s.changedFiles.length} file(s), ${s.changedSymbols} symbol(s) changed.`);let d=s.attributionNotes.filter(f=>f.method==="unattributed");if(d.length>0)for(let f of[...new Set(d.map(g=>g.file))]){let g=d.filter(h=>h.file===f).length;console.log(`note: ${g} changed line-range(s) in ${f} belong to no indexed symbol`)}console.log(`Checks: ${s.checksRun.join(", ")}
529
529
  `);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}Ce("diff gate candidates");let u=s.rootCauseGroups?.filter(f=>f.count>1)??[];if(u.length>0){console.log(`Root-cause groups (${u.length}):`);for(let f of u){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: ${Ln(g)}`);f.declaredCouplingSuggestion&&console.log(` declare coupling: ${f.declaredCouplingSuggestion.name} (${f.declaredCouplingSuggestion.reason})`),console.log(` -> ${f.remediation}`)}if(a.length===0){console.log(`
530
530
  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(`
531
- 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}),Rm=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:C([p("--max-depth <n>","Maximum traversal depth",v,5),p("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:$("Impact"),handler:ck},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:$("Impact"),handler:pk},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: echo candidates, incomplete migrations, missing co-change partners, unedited twin partners (advisory), uncited doc updates, unused params, new dead symbols; exit 1 on blocking findings",options:[p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-together <n>","Minimum historical co-changes for the partner check",v,6),p("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",v),p("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",v),p("--baseline","Also run the full health-baseline ratchet"),p("--full","Run unbounded semantic and git-history analysis on large indexes"),p("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, twin-partner, coverage-contract, doc-reference, unused-params, new-dead, baseline",rt,[]),p("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),p("--json","Output as JSON for programmatic consumption")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:$("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:gk},{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:C([p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",ge,.7),p("--max-helpers <n>","Maximum new helpers to score (default: all)",v),p("-n, --limit <n>","Maximum findings to report",v,20),p("--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:mk},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:C([p("--min-together <n>","Minimum commits where both files changed",v,4),p("-n, --limit <n>","Maximum pairs to report",v,30),p("--all","Include pairs that already have a dependency edge"),p("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:$("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:lk}];function hk(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(`
531
+ 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}),km=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:C([p("--max-depth <n>","Maximum traversal depth",v,5),p("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:$("Impact"),handler:lk},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:$("Impact"),handler:mk},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: echo candidates, incomplete migrations, missing co-change partners, unedited twin partners (advisory), uncited doc updates, unused params, new dead symbols; exit 1 on blocking findings",options:[p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-together <n>","Minimum historical co-changes for the partner check",v,6),p("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",v),p("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",v),p("--baseline","Also run the full health-baseline ratchet"),p("--full","Run unbounded semantic and git-history analysis on large indexes"),p("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, twin-partner, coverage-contract, doc-reference, unused-params, new-dead, baseline",rt,[]),p("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),p("--json","Output as JSON for programmatic consumption")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:$("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:hk},{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:C([p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",ge,.7),p("--max-helpers <n>","Maximum new helpers to score (default: all)",v),p("-n, --limit <n>","Maximum findings to report",v,20),p("--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:fk},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:C([p("--min-together <n>","Minimum commits where both files changed",v,4),p("-n, --limit <n>","Maximum pairs to report",v,30),p("--all","Include pairs that already have a dependency edge"),p("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:$("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:dk}];function yk(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(`
532
532
  `).map((s,a)=>` ${Me(i.startLine+a)} ${s}`).join(`
533
- `))}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 ${Me(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var yk=ue("imports",{query:({db:e,args:t,budget:n})=>vs(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)."}),bk=K("dataflow",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=va(e,i,{semantic:r.semantic});if(b(n,"json")){I("dataflow",t,n,ve(e,i,o,"dataflow"),{analysisBudget:r.analysisBudget});return}if(!o)return E.empty(ae(e,i,"No dataflow found."));if(se(e,i),console.log(`${o.shortName} (${o.relativePath})
533
+ `))}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 ${Me(i.line)} in ${i.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var bk=ue("imports",{query:({db:e,args:t,budget:n})=>xs(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)."}),Sk=K("dataflow",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=xa(e,i,{semantic:r.semantic});if(b(n,"json")){I("dataflow",t,n,ve(e,i,o,"dataflow"),{analysisBudget:r.analysisBudget});return}if(!o)return E.empty(ae(e,i,"No dataflow found."));if(se(e,i),console.log(`${o.shortName} (${o.relativePath})
534
534
  `),o.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of o.definitionSites)console.log(` ${s.file}:${Me(s.line)}`)}if(o.usageSites.length>0){console.log(`
535
535
  \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of o.usageSites)console.log(` ${s.file}:${Me(s.line)} in ${s.enclosingShort}`)}if(o.producers.length>0){console.log(`
536
536
  \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(`
537
- \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of o.consumers)console.log(` ${s.file} ${s.shortName}`)}}),Sk=K("slice",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=b(n,"forward")?"forward":"backward",s=xa(e,i,{direction:o,maxDepth:P(n,"depth",3),semantic:r.semantic});if(b(n,"json")){I("slice",t,n,ve(e,i,s,"slice"),{analysisBudget:r.analysisBudget});return}if(!s)return E.empty(ae(e,i,"No slice found."));if(se(e,i),console.log(`${s.direction} slice of ${s.shortName}
537
+ \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of o.consumers)console.log(` ${s.file} ${s.shortName}`)}}),vk=K("slice",({db:e,args:t,opts:n,budget:r})=>{let i=L(t,0),o=b(n,"forward")?"forward":"backward",s=Ra(e,i,{direction:o,maxDepth:P(n,"depth",3),semantic:r.semantic});if(b(n,"json")){I("slice",t,n,ve(e,i,s,"slice"),{analysisBudget:r.analysisBudget});return}if(!s)return E.empty(ae(e,i,"No slice found."));if(se(e,i),console.log(`${s.direction} slice of ${s.shortName}
538
538
  `),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}E.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
539
539
  ${a.relationship}`),console.log(`
540
- ${s.connectedSymbols.length} connected symbol(s).`)}),km=[...bc,Ie({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:$("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>us(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})=>ps(e,L(t,0)),format:e=>` ${oe(e.startLine,e.endLine)} ${e.name}`}),vr({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[p("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:$("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>ms(e,L(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?ae(t,L(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>se(t,L(n,0)),toJson:(e,{db:t,args:n})=>({...Vt(t,L(n,0)),...e}),sections:hk}),Ie({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:$("Navigation"),query:({db:e,args:t})=>fs(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})=>gs(e,L(t,0)),format:e=>e.relativePath}),kp({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})=>hs(e,L(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${oe(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})=>ys(e,L(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[p("--full","Run unbounded semantic analysis on large indexes"),p("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:$("Navigation"),handler:yk},Ie({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:$("Navigation"),query:({db:e,args:t})=>xs(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})=>ks(e,L(t,0)),format:e=>` ${oe(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>se(t,L(n,0)),emptyMessage:({db:e,args:t})=>ae(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:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",v,100),p("--full","Run unbounded analysis on large indexes")],docs:$("Navigation"),query:({db:e,args:t,opts:n})=>As(e,L(t,0),{scope:w(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(`
541
- ${e.length} symbol(s)`)}),Sr({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[p("-s, --scope <path>","Limit to files matching path")],docs:$("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>Ds(e,{scope:w(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})=>Ns(e,L(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>se(t,L(n,0)),emptyMessage:({db:e,args:t})=>ae(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:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Navigation"),handler:bk},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:C([p("--forward","Forward slice (what does this affect). Default is backward."),p("--depth <n>","Max transitive depth for backward slice",v,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Navigation"),handler:Sk}];var vk=K("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=A(n,"limit",20),o=Fe(e.config.projectRoot).gitContext?.headCommit,s=Ra(e,L(t,0),{semantic:r.semantic,impactDepth:P(n,"impactDepth",3),sliceDepth:P(n,"sliceDepth",3),scope:w(n,"scope"),...o?{gitHead:o}:{}});if(s.warnings.length===1&&s.warnings[0]==="No symbol, file, or module matched target."){if(b(n,"json")){I("plan-context",t,n,{...Vt(e,L(t,0)),...s},{analysisBudget:r.analysisBudget});return}return E.empty(ae(e,L(t,0)))}if(b(n,"json")){I("plan-context",t,n,s.matched.symbol?{...Vt(e,L(t,0)),...s}:s,{analysisBudget:r.analysisBudget});return}s.matched.symbol&&se(e,L(t,0));let a=[{title:"TARGET",rows:xk(s)},{title:"DEFINITIONS",rows:Rk(s,i),skipIfEmpty:!0},{title:"REFERENCES",rows:kk(s,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:wk(s,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:$k(s,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:Pk(s,i),skipIfEmpty:!0},{title:"SURFACE",rows:Ck(s,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:Tk(s,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:Ik(s,i),skipIfEmpty:!0},{title:"HISTORY",rows:Ek(s),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:jk(s),skipIfEmpty:!0}];E.sectionedReport(a)}),wm=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:C([p("--impact-depth <n>","Maximum affected traversal depth",v,3),p("--slice-depth <n>","Maximum backward slice depth",v,3),p("-s, --scope <path>","Limit downstream impact to files matching path"),p("-n, --limit <n>","Rows per section",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Planning",["scip-query plan-context parseSymbol"]),handler:vk}];function xk(e){return[`Target: ${e.target}`,`Matched: symbol=${lo(e.matched.symbol)} file=${lo(e.matched.file)} module=${lo(e.matched.module)}`]}function Rk(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(`
542
- `).map((o,s)=>` ${String(Me(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${oe(r.startLine,r.endLine)} ${r.shortName}`)),Ze(n,t).rows}function kk(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${Me(r.line)} in ${r.enclosingShort}`);return mt(Ze(n,t))}function wk(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 mt(Ze([...n,...r],t))}function $k(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}:${Me(o.line)} in ${o.enclosingShort}`);return mt(Ze([...n,...r,...i],t))}function Pk(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 mt(Ze(n,t))}function Ck(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${oe(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return mt(Ze(n,t))}function Tk(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 mt(Ze(n,t))}function Ik(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` ${oe(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}`)),mt(Ze(n,t))}function Ek(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 jk(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 Ze(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function mt(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function lo(e){return e?"yes":"no"}import{existsSync as ln}from"fs";import{existsSync as qk,mkdtempSync as Bk,rmSync as Vk}from"fs";import{tmpdir as Hk}from"os";import{dirname as po,join as mo}from"path";import{performance as Tm}from"perf_hooks";import{spawnSync as Wk}from"child_process";import{createHash as Lk}from"crypto";import{existsSync as Ak,mkdirSync as Dk,readFileSync as Ok,renameSync as Nk,writeFileSync as Fk}from"fs";import{homedir as Mk}from"os";import{dirname as _k,join as uo}from"path";function $m(e){return Lk("sha256").update(e).digest("hex")}function Pm(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?uo(t.XDG_CACHE_HOME,"scip-query"):uo(Mk(),".cache","scip-query"));return uo(n,e)}async function Cm(e){let{cachePath:t,url:n,expectedSha256:r}=e;if(Ak(t)){let l=$m(Ok(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=$m(s);if(a!==r)throw new Error(`downloaded ${n} checksum mismatch: expected ${r}, got ${a}`);Dk(_k(t),{recursive:!0});let c=`${t}.tmp-${process.pid}`;return Fk(c,s),Nk(c,t),{status:"downloaded",path:t,sha256:a}}var Gk=12e4,jm="v1.8.0",Uk=`https://github.com/tlaplus/tlaplus/releases/download/${jm}/tla2tools.jar`,Jk="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function Tr(e){let t=e.spawn??Wk,n=zk(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??Gk,i=Tm.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??[])Vk(l,{recursive:!0,force:!0})}let s=Math.round(Tm.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:Kk(c,o.stdout??"",o.stderr??""),stdout:o.stdout??"",stderr:o.stderr??""}}function zk(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"&&qe(Im(e),t)){let o=Im(e);return qe(o,t)?{checker:"apalache",command:[o,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:po(e.specPath)}:Cr("apalache",`Apalache binary is not available: ${o}`)}let r=fo(e),i=qe("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!r)return Cr(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!i)return Cr(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:po(e.specPath)};let s=e.metaDir??Bk(mo(Hk(),"scip-tla-tlc-"));return{checker:o,command:["java","-cp",r,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:po(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Cr("none",`unknown checker mode: ${n}`)}function Im(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function fo(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,Lm(t),mo(e.projectRoot,"tla2tools.jar"),mo(e.projectRoot,"tools","tla2tools.jar")].filter(r=>typeof r=="string"&&r.length>0).find(r=>qk(r))??null}function Lm(e=process.env){return Pm("tla2tools.jar",e)}async function Am(e={}){let t=e.cachePath??Lm(e.env),n=e.expectedSha256??Jk,r=e.version??jm,i=e.url??Uk;return{...await Cm({cachePath:t,url:i,expectedSha256:n,fetchImpl:e.fetchImpl}),version:r,url:i}}function Kk(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=[...Em(n),...Em(t)].slice(0,20);return r.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:r.map(i=>({severity:"error",message:i}))}function Em(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Cr(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as Qk}from"crypto";import{readFileSync as Om}from"fs";import{join as Nm}from"path";var Fm=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),Mm=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),_m=new Set(["readFileSync","existsSync","statSync"]),Yk=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,Xk=/^\s*SELECT\b/i;function qm(e){return Yk.test(e)?"write":Xk.test(e)?"read":null}var Zk=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function ew(e,t){let n=e.match(Zk);if(!n)return!1;let r=e.slice(n[0].length);return new RegExp(`^${Le(t)}\\b`).test(r)}function Bm(e,t,n,r=[],i=[]){let o=[],s=rw(e,t,o),a=s.aliases,c=iw(t),l=ow(t),d=sw(t),u=lw(e,t,o),m=uw(e,t,o);n&&pw(t,n,i,o);let f=new Map((n?.actions??[]).map(x=>[x.name,x])),g=new Set(u.flatMap(x=>x.referents.map(k=>k.match?.symbol).filter(Boolean))),h=new Set((m?.referents??[]).map(x=>x.match?.symbol).filter(Boolean)),y=mw(e,t,u,a,c,l,d,g,h,o,f),S=hw(e,u,a,c,l,d,o,f);return bw(e,u,o),Sw(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:ho(u.flatMap(x=>x.referents))+ho(s.referents)+ho(m?.referents??[]),staticWrites:y,staticReads:S,waivers:_w(t),checkedInvariants:[...i],traceStepsChecked:r.length,findings:o,findingGroups:tw(o)}}function tw(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=nw(i.severity,n.severity)}return[...t.values()].sort((n,r)=>r.count-n.count||Ir(r.severity)-Ir(n.severity)||n.groupKey.localeCompare(r.groupKey))}function nw(e,t){return Ir(t)>Ir(e)?t:e}function Ir(e){return e==="error"?2:e==="warning"?1:0}function rw(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=Lr(e,l,n,o);i.push(d);let u=d.match;if(!u){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}Aw(e,o,l,u,n,c),s.aliases.length===0&&a.add(Lo(u.symbol))}for(let l of a)r.push({variable:o,alias:l})}return{aliases:Mw(r),referents:i}}function iw(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 ow(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 sw(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.ormCalls??[]){let{write:o,read:s}=io(i);t.push({variable:n,table:i.table,writeMethods:new Set(o),readMethods:new Set(s)})}return t}function aw(e,t,n,r,i,o){return Vm(e,t,(s,a,c)=>ft(e,s,a,c,n,r,i,o))}function cw(e,t,n,r,i,o){return Vm(e,t,(s,a,c)=>jr(e,s,a,c,n,r,i,o))}function Vm(e,t,n){let r=Bt(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=yn(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 lw(e,t,n){return Object.entries(t.actions).map(([r,i])=>{let o=i.code.map(s=>{let a=oo(s),c="error"in a?s:a.ref,d=Lr(e,c,n,r).match;return d?(Dw(e,r,s,d,n),"error"in a||!a.window?{ref:s,match:d}:dw(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 dw(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function uw(e,t,n){let r=t.init;if(!r)return;let i=!!r.waive,o=r.codeRefs.map(s=>{let a=Lr(e,s,n,"Init"),c=a.match;return c?Ow(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 pw(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&&(Dm({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)}),Dm({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 Dm(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 mw(e,t,n,r,i,o,s,a,c,l,d){let u=[];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=ft(e,h.match.relativePath,y.startLine,y.endLine,r,i,o,s);g.push(...S),u.push(...S);let x=new Set(f.mapping.writes),k=aw(e,h.match.symbol,r,i,o,s).filter(R=>x.has(R.variable));g.push(...k),u.push(...k)}gw(f,g,l,d.get(f.name))}let m=t.unmappedWriteScope==="actions"?[]:Ew(e,t);for(let f of m)for(let g of ft(e,f,0,Number.POSITIVE_INFINITY,r,i,o,s))u.push(g),fw(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 So(u)}function fw(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function gw(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)&&!an(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}${Er(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)&&!an(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}${Er(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)&&!an(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 hw(e,t,n,r,i,o,s,a){let c=[];for(let l of t){let d=[];for(let u of l.referents){if(!u.match)continue;let m=u.window??{startLine:u.match.startLine,endLine:u.match.endLine},f=jr(e,u.match.relativePath,m.startLine,m.endLine,n,r,i,o);d.push(...f),c.push(...f);let g=new Set(l.mapping.reads),h=cw(e,u.match.symbol,n,r,i,o).filter(y=>g.has(y.variable));d.push(...h),c.push(...h)}yw(l,d,s,a.get(l.name))}return vo(c)}function yw(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}${Er(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)&&!an(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}${Er(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)&&!an(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 bw(e,t,n){for(let r of t){if(r.mapping.calls.length===0)continue;let i=r.mapping.calls.map(s=>Lr(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=Bt(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 Sw(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=Fw(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 ft(e,t,n,r,i,o=[],s=[],a=[]){let c=vw(e,t,n,r,i,o,s,a);return c||Tw(e,t,n,r,i,o,s,a)}function jr(e,t,n,r,i,o=[],s=[],a=[]){let c=xw(e,t,n,r,i,o,s,a);return c||Iw(e,t,n,r,i,o,s,a)}function vw(e,t,n,r,i,o=[],s=[],a=[]){let c=Or(e,t);if(!c)return null;let l=[],d=u=>{if(!(u.startPosition.row>r||u.endPosition.row<n)){Rw(e,t,u,i,l),Hm(e,t,u,o,"write",l),Wm(e,t,u,s,"write",l),Gm(e,t,u,a,"write",l);for(let m of u.children)d(m)}};return d(c.rootNode),So(l)}function xw(e,t,n,r,i,o=[],s=[],a=[]){let c=Or(e,t);if(!c)return null;let l=[],d=u=>{if(!(u.startPosition.row>r||u.endPosition.row<n)){$w(e,t,u,i,l),Hm(e,t,u,o,"read",l),Wm(e,t,u,s,"read",l),Gm(e,t,u,a,"read",l);for(let m of u.children)d(m)}};return d(c.rootNode),vo(l)}function Rw(e,t,n,r,i){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let o=n.childForFieldName("left")??n.namedChild(0);o&&sn(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&&sn(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&&sn(e,t,o,"update",r,i);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let o=n.namedChild(0);o&&sn(e,t,o,"delete",r,i);return}if(n.type==="call_expression"){let o=n.childForFieldName("function")??n.namedChild(0);if(!o||!Jm(o))return;sn(e,t,o,"mutation-call",r,i)}}}function Hm(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?yo(s):null;if(!a||!(i==="write"?Mm:_m).has(a))return;let d=n.childForFieldName("arguments")?.namedChild(0);if(!d)return;let u=d.text;for(let m of r){if(!u.includes(m.path))continue;let f=Ee(e,t,n.startPosition.row);o.push({variable:m.variable,alias:m.path,file:t,line:n.startPosition.row,target:`${a}(${u})`,kind:"resource",enclosingSymbol:f?.symbol,enclosingShort:f?Q(f.symbol):void 0})}}function yo(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 Wm(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=kw(a);if(c!==null&&qm(c)===i)for(let l of r){if(!l.regex.test(c))continue;let d=Ee(e,t,n.startPosition.row),u=n.childForFieldName("function")??n.namedChild(0),m=(u&&yo(u))??"call";o.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${m}(${ww(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?Q(d.symbol):void 0})}}}function kw(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function ww(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function Gm(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?yo(s):null;if(!a)return;let l=n.childForFieldName("arguments")?.namedChild(0);if(!l)return;let d=l.text.trim();for(let u of r){if(!Um(u,a,d,i))continue;let m=Ee(e,t,n.startPosition.row);o.push({variable:u.variable,alias:u.table,file:t,line:n.startPosition.row,target:`${a}(${d})`,kind:"orm-call",enclosingSymbol:m?.symbol,enclosingShort:m?Q(m.symbol):void 0})}}function Um(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 $w(e,t,n,r,i){if(!(!Pw(n)||Cw(n)))for(let o of r){if(n.text!==o.alias)continue;let s=Ee(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 Pw(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function Cw(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&&go(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&&go(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&Jm(n)&&go(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 go(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function Jm(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&Fm.has(t.text))}function sn(e,t,n,r,i,o){for(let s of i){if(!Nw(s.alias,n.text))continue;let a=Ee(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 Tw(e,t,n,r,i,o=[],s=[],a=[]){let l=Om(Nm(e.config.projectRoot,t),"utf8").split(/\r?\n/),d=[],u=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=u;m+=1){let f=l[m]??"";for(let g of i){if(ew(f,g.alias))continue;let h=Le(g.alias);if(!new RegExp(`(?:\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${h}\\b\\s*\\.\\s*(?:${[...Fm].join("|")})\\s*\\(|\\b${h}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(f))continue;let S=Ee(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})}zm(e,t,m,f,o,Mm,d),Km(e,t,m,f,s,"write",d),Qm(e,t,m,f,a,"write",d)}return So(d)}function Iw(e,t,n,r,i,o=[],s=[],a=[]){let l=Om(Nm(e.config.projectRoot,t),"utf8").split(/\r?\n/),d=[],u=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=u;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=Ee(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})}zm(e,t,m,f,o,_m,d),Km(e,t,m,f,s,"read",d),Qm(e,t,m,f,a,"read",d)}return vo(d)}function zm(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 u=Ee(e,t,n);s.push({variable:d.variable,alias:d.path,file:t,line:n,target:r.trim(),kind:"resource",enclosingSymbol:u?.symbol,enclosingShort:u?Q(u.symbol):void 0})}}}function Km(e,t,n,r,i,o,s){if(i.length!==0&&qm(r)===o)for(let a of i){if(!a.regex.test(r))continue;let c=Ee(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 Qm(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(!Um(d,c,l,o))continue;let u=Ee(e,t,n);s.push({variable:d.variable,alias:d.table,file:t,line:n,target:r.trim(),kind:"orm-call",enclosingSymbol:u?.symbol,enclosingShort:u?Q(u.symbol):void 0})}}}function Ew(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 Lr(e,t,n,r){let i=yn(e,t),o=i.match??(t.includes("#")?yn(e,t.replace("#","/")).match:null);return i.match&&i.total>1&&!jw(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.`,Lw(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 jw(e){return/[/#:]/.test(e)}function Lw(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function Aw(e,t,n,r,i,o=!1){let s=bo(e,r);if(s===null||qw.has(s)||o)return;let a=xo.has(s);i.push(W("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:a?`TLA+ variable ${t} referent is a type; map the runtime state it describes.`:`TLA+ variable ${t} referent is ${qt(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${Q(r.symbol)} with SCIP kind ${qt(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function Dw(e,t,n,r,i){let o=bo(e,r);o===null||Ym.has(o)||xo.has(o)&&i.push(W("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:`TLA+ action ${t} referent is a type; map the runtime transition code it describes.`,why:[`${n} resolves to ${Q(r.symbol)} with SCIP kind ${qt(o)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function Ow(e,t,n,r,i){let o=bo(e,n);o===null||Ym.has(o)||i||xo.has(o)&&r.push(W("invalid-referent-kind","error","compiler-symbol",{modelElement:"Init",codeRef:t,file:n.relativePath,startLine:n.startLine,endLine:n.endLine,message:"TLA+ Init referent is a type; map the runtime initialization code it describes.",why:[`${t} resolves to ${Q(n.symbol)} with SCIP kind ${qt(o)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function bo(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function Ee(e,t,n){return hn(e,t).filter(i=>i.startLine<=n&&i.endLine>=n).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine))[0]??null}function Nw(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${Le(e)}([^A-Za-z0-9_$]|$)`).test(t)}function Fw(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 So(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 vo(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 Mw(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 ho(e){return e.filter(t=>t.match).length}function Er(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function an(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function _w(e){let t=Object.entries(e.actions).flatMap(([o,s])=>{let a=s.waive;return a?[...(a.reads??[]).map(c=>({action:o,kind:"read",variable:c,reason:a.reason,legacy:a.legacy===!0})),...(a.writes??[]).map(c=>({action:o,kind:"write",variable:c,reason:a.reason,legacy:a.legacy===!0}))]:[]}),n=Object.entries(e.variables).flatMap(([o,s])=>{let a=s.waive;return a?[{kind:"referent",variable:o,reason:a.reason,legacy:!1}]:[]}),r=e.init?.waive,i=r?[{kind:"referent",variable:"Init",reason:r.reason,legacy:!1}]:[];return[...t,...n,...i]}var xo=new Set(ls()),Ym=new Set(cs()),qw=new Set(ds());function W(e,t,n,r){let i=JSON.stringify({category:e,evidence:n,...r});return{id:`TLA${Qk("sha1").update(i).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...r}}import{readFileSync as Bw}from"fs";import{basename as Vw,join as Xm}from"path";var Ro=/^[A-Za-z_][A-Za-z0-9_]*$/;function Zm(e,t,n={}){let r=[],i=hn(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=Bw(Xm(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&&Ro.test(T.leaf)),l=c.map(T=>({variable:T.leaf,alias:T.leaf})),d=l.length>0?ft(e,t,0,Number.POSITIVE_INFINITY,l):[],u=new Set(d.map(T=>T.variable)),m=c.filter(T=>u.has(T.leaf)?!0:Gw(s,T)),f=null,g;if(m.length>0)g=i.filter(T=>a(T)&&T.parentTypeName===null);else{if(f=Hw(e,t,i,a),!f){let T=i.some(O=>!a(O)&&!O.isTypeLike&&O.parentTypeName!==null&&Ro.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=>Uw(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=ft(e,t,T.startLine,T.endLine,y);if(O.length===0)continue;let Z=jr(e,t,T.startLine,T.endLine,y),N=Qw(ef(T.leaf),x);S.push({name:N,leaf:T.leaf,codeRef:Ww(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 k=n.moduleName??Yw(t),R=n.specDir??Xm("specs",k),D=Xw(k,h,S,t),_=Zw(),z=e$(k,R,t,h,S);return{moduleName:k,file:t,variables:h,actions:S,warnings:r,spec:D,cfg:_,map:z}}function Hw(e,t,n,r){let i=new Map;for(let s of n){if(r(s)||s.isTypeLike||s.parentTypeName===null||!Ro.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 ft(e,t,m.startLine,m.endLine,l))d.add(f.variable);let u=a.filter(m=>d.has(m.leaf));u.length!==0&&(!o||u.length>o.fields.length)&&(o={className:s,fields:u,methods:c})}return o}function Ww(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function Gw(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function Uw(e,t,n,r,i){let o=Jw(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=zw(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 Jw(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function zw(e,t){let r=t.match(new RegExp(`\\b${t$(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,o=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(r){let l=Kw(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 Kw(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 ef(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function Qw(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}${r++}`;return t.add(n),n}function Yw(e){let n=Vw(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return ef(n||"Model")}function Xw(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(u=>u.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(`
543
- `)}function Zw(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
544
- `)}function e$(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)}
545
- `}function t$(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tf(e,t){let n=Object.keys(t.variables),r=Object.entries(t.actions).map(([i,o])=>{let s=o.code[0]??"",a=s?Do(e,s):null;return{action:i,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:o.writes}});return{recorderSource:n$(n),wiring:r,variables:n}}function n$(e){return`/**
540
+ ${s.connectedSymbols.length} connected symbol(s).`)}),wm=[...Sc,Ie({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:$("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>ps(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})=>ms(e,L(t,0)),format:e=>` ${oe(e.startLine,e.endLine)} ${e.name}`}),vr({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[p("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:$("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>fs(e,L(t,0),{semantic:n.semantic}),emptyMessage:(e,{db:t,args:n})=>e.definitions.length===0&&e.referencedBy.length===0?ae(t,L(n,0),"No trace rows found."):void 0,before:(e,{db:t,args:n})=>se(t,L(n,0)),toJson:(e,{db:t,args:n})=>({...Vt(t,L(n,0)),...e}),sections:yk}),Ie({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:$("Navigation"),query:({db:e,args:t})=>gs(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})=>hs(e,L(t,0)),format:e=>e.relativePath}),wp({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})=>ys(e,L(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${oe(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})=>bs(e,L(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[p("--full","Run unbounded semantic analysis on large indexes"),p("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:$("Navigation"),handler:bk},Ie({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:$("Navigation"),query:({db:e,args:t})=>Rs(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})=>ws(e,L(t,0)),format:e=>` ${oe(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`,before:(e,{db:t,args:n})=>se(t,L(n,0)),emptyMessage:({db:e,args:t})=>ae(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:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",v,100),p("--full","Run unbounded analysis on large indexes")],docs:$("Navigation"),query:({db:e,args:t,opts:n})=>Ds(e,L(t,0),{scope:w(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(`
541
+ ${e.length} symbol(s)`)}),Sr({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[p("-s, --scope <path>","Limit to files matching path")],docs:$("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>Os(e,{scope:w(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})=>Fs(e,L(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,before:(e,{db:t,args:n})=>se(t,L(n,0)),emptyMessage:({db:e,args:t})=>ae(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:C([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Navigation"),handler:Sk},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:C([p("--forward","Forward slice (what does this affect). Default is backward."),p("--depth <n>","Max transitive depth for backward slice",v,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Navigation"),handler:vk}];var xk=K("plan-context",({db:e,args:t,opts:n,budget:r})=>{let i=A(n,"limit",20),o=Fe(e.config.projectRoot).gitContext?.headCommit,s=ka(e,L(t,0),{semantic:r.semantic,impactDepth:P(n,"impactDepth",3),sliceDepth:P(n,"sliceDepth",3),scope:w(n,"scope"),...o?{gitHead:o}:{}});if(s.warnings.length===1&&s.warnings[0]==="No symbol, file, or module matched target."){if(b(n,"json")){I("plan-context",t,n,{...Vt(e,L(t,0)),...s},{analysisBudget:r.analysisBudget});return}return E.empty(ae(e,L(t,0)))}if(b(n,"json")){I("plan-context",t,n,s.matched.symbol?{...Vt(e,L(t,0)),...s}:s,{analysisBudget:r.analysisBudget});return}s.matched.symbol&&se(e,L(t,0));let a=[{title:"TARGET",rows:Rk(s)},{title:"DEFINITIONS",rows:kk(s,i),skipIfEmpty:!0},{title:"REFERENCES",rows:wk(s,i),skipIfEmpty:!0},{title:"CALL GRAPH",rows:$k(s,i),skipIfEmpty:!0},{title:"DATAFLOW",rows:Pk(s,i),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:Ck(s,i),skipIfEmpty:!0},{title:"SURFACE",rows:Tk(s,i),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:Ik(s,i),skipIfEmpty:!0},{title:"CHANGE RISK",rows:Ek(s,i),skipIfEmpty:!0},{title:"HISTORY",rows:jk(s),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:Lk(s),skipIfEmpty:!0}];E.sectionedReport(a)}),$m=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:C([p("--impact-depth <n>","Maximum affected traversal depth",v,3),p("--slice-depth <n>","Maximum backward slice depth",v,3),p("-s, --scope <path>","Limit downstream impact to files matching path"),p("-n, --limit <n>","Rows per section",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:$("Planning",["scip-query plan-context parseSymbol"]),handler:xk}];function Rk(e){return[`Target: ${e.target}`,`Matched: symbol=${lo(e.matched.symbol)} file=${lo(e.matched.file)} module=${lo(e.matched.module)}`]}function kk(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(`
542
+ `).map((o,s)=>` ${String(Me(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${oe(r.startLine,r.endLine)} ${r.shortName}`)),Ze(n,t).rows}function wk(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${Me(r.line)} in ${r.enclosingShort}`);return mt(Ze(n,t))}function $k(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 mt(Ze([...n,...r],t))}function Pk(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}:${Me(o.line)} in ${o.enclosingShort}`);return mt(Ze([...n,...r,...i],t))}function Ck(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 mt(Ze(n,t))}function Tk(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${oe(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return mt(Ze(n,t))}function Ik(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 mt(Ze(n,t))}function Ek(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` ${oe(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}`)),mt(Ze(n,t))}function jk(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 Lk(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 Ze(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function mt(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function lo(e){return e?"yes":"no"}import{existsSync as ln}from"fs";import{existsSync as Bk,mkdtempSync as Vk,rmSync as Hk}from"fs";import{tmpdir as Wk}from"os";import{dirname as po,join as mo}from"path";import{performance as Im}from"perf_hooks";import{spawnSync as Gk}from"child_process";import{createHash as Ak}from"crypto";import{existsSync as Dk,mkdirSync as Ok,readFileSync as Nk,renameSync as Fk,writeFileSync as Mk}from"fs";import{homedir as _k}from"os";import{dirname as qk,join as uo}from"path";function Pm(e){return Ak("sha256").update(e).digest("hex")}function Cm(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?uo(t.XDG_CACHE_HOME,"scip-query"):uo(_k(),".cache","scip-query"));return uo(n,e)}async function Tm(e){let{cachePath:t,url:n,expectedSha256:r}=e;if(Dk(t)){let l=Pm(Nk(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=Pm(s);if(a!==r)throw new Error(`downloaded ${n} checksum mismatch: expected ${r}, got ${a}`);Ok(qk(t),{recursive:!0});let c=`${t}.tmp-${process.pid}`;return Mk(c,s),Fk(c,t),{status:"downloaded",path:t,sha256:a}}var Uk=12e4,Lm="v1.8.0",Jk=`https://github.com/tlaplus/tlaplus/releases/download/${Lm}/tla2tools.jar`,zk="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function Tr(e){let t=e.spawn??Gk,n=Kk(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??Uk,i=Im.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??[])Hk(l,{recursive:!0,force:!0})}let s=Math.round(Im.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:Qk(c,o.stdout??"",o.stderr??""),stdout:o.stdout??"",stderr:o.stderr??""}}function Kk(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"&&qe(Em(e),t)){let o=Em(e);return qe(o,t)?{checker:"apalache",command:[o,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:po(e.specPath)}:Cr("apalache",`Apalache binary is not available: ${o}`)}let r=fo(e),i=qe("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!r)return Cr(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!i)return Cr(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:po(e.specPath)};let s=e.metaDir??Vk(mo(Wk(),"scip-tla-tlc-"));return{checker:o,command:["java","-cp",r,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:po(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Cr("none",`unknown checker mode: ${n}`)}function Em(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function fo(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,Am(t),mo(e.projectRoot,"tla2tools.jar"),mo(e.projectRoot,"tools","tla2tools.jar")].filter(r=>typeof r=="string"&&r.length>0).find(r=>Bk(r))??null}function Am(e=process.env){return Cm("tla2tools.jar",e)}async function Dm(e={}){let t=e.cachePath??Am(e.env),n=e.expectedSha256??zk,r=e.version??Lm,i=e.url??Jk;return{...await Tm({cachePath:t,url:i,expectedSha256:n,fetchImpl:e.fetchImpl}),version:r,url:i}}function Qk(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=[...jm(n),...jm(t)].slice(0,20);return r.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:r.map(i=>({severity:"error",message:i}))}function jm(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Cr(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as Yk}from"crypto";import{readFileSync as Nm}from"fs";import{join as Fm}from"path";var Mm=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),_m=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),qm=new Set(["readFileSync","existsSync","statSync"]),Xk=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,Zk=/^\s*SELECT\b/i;function Bm(e){return Xk.test(e)?"write":Zk.test(e)?"read":null}var ew=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function tw(e,t){let n=e.match(ew);if(!n)return!1;let r=e.slice(n[0].length);return new RegExp(`^${Le(t)}\\b`).test(r)}function Vm(e,t,n,r=[],i=[]){let o=[],s=iw(e,t,o),a=s.aliases,c=ow(t),l=sw(t),d=aw(t),u=dw(e,t,o),m=pw(e,t,o);n&&mw(t,n,i,o);let f=new Map((n?.actions??[]).map(x=>[x.name,x])),g=new Set(u.flatMap(x=>x.referents.map(k=>k.match?.symbol).filter(Boolean))),h=new Set((m?.referents??[]).map(x=>x.match?.symbol).filter(Boolean)),y=fw(e,t,u,a,c,l,d,g,h,o,f),S=yw(e,u,a,c,l,d,o,f);return Sw(e,u,o),vw(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:ho(u.flatMap(x=>x.referents))+ho(s.referents)+ho(m?.referents??[]),staticWrites:y,staticReads:S,waivers:qw(t),checkedInvariants:[...i],traceStepsChecked:r.length,findings:o,findingGroups:nw(o)}}function nw(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=rw(i.severity,n.severity)}return[...t.values()].sort((n,r)=>r.count-n.count||Ir(r.severity)-Ir(n.severity)||n.groupKey.localeCompare(r.groupKey))}function rw(e,t){return Ir(t)>Ir(e)?t:e}function Ir(e){return e==="error"?2:e==="warning"?1:0}function iw(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=Lr(e,l,n,o);i.push(d);let u=d.match;if(!u){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}Dw(e,o,l,u,n,c),s.aliases.length===0&&a.add(Lo(u.symbol))}for(let l of a)r.push({variable:o,alias:l})}return{aliases:_w(r),referents:i}}function ow(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 sw(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 aw(e){let t=[];for(let[n,r]of Object.entries(e.variables))for(let i of r.ormCalls??[]){let{write:o,read:s}=io(i);t.push({variable:n,table:i.table,writeMethods:new Set(o),readMethods:new Set(s)})}return t}function cw(e,t,n,r,i,o){return Hm(e,t,(s,a,c)=>ft(e,s,a,c,n,r,i,o))}function lw(e,t,n,r,i,o){return Hm(e,t,(s,a,c)=>jr(e,s,a,c,n,r,i,o))}function Hm(e,t,n){let r=Bt(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=yn(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 dw(e,t,n){return Object.entries(t.actions).map(([r,i])=>{let o=i.code.map(s=>{let a=oo(s),c="error"in a?s:a.ref,d=Lr(e,c,n,r).match;return d?(Ow(e,r,s,d,n),"error"in a||!a.window?{ref:s,match:d}:uw(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 uw(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function pw(e,t,n){let r=t.init;if(!r)return;let i=!!r.waive,o=r.codeRefs.map(s=>{let a=Lr(e,s,n,"Init"),c=a.match;return c?Nw(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 mw(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&&(Om({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)}),Om({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 Om(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 fw(e,t,n,r,i,o,s,a,c,l,d){let u=[];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=ft(e,h.match.relativePath,y.startLine,y.endLine,r,i,o,s);g.push(...S),u.push(...S);let x=new Set(f.mapping.writes),k=cw(e,h.match.symbol,r,i,o,s).filter(R=>x.has(R.variable));g.push(...k),u.push(...k)}hw(f,g,l,d.get(f.name))}let m=t.unmappedWriteScope==="actions"?[]:jw(e,t);for(let f of m)for(let g of ft(e,f,0,Number.POSITIVE_INFINITY,r,i,o,s))u.push(g),gw(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 So(u)}function gw(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function hw(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)&&!an(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}${Er(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)&&!an(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}${Er(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)&&!an(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 yw(e,t,n,r,i,o,s,a){let c=[];for(let l of t){let d=[];for(let u of l.referents){if(!u.match)continue;let m=u.window??{startLine:u.match.startLine,endLine:u.match.endLine},f=jr(e,u.match.relativePath,m.startLine,m.endLine,n,r,i,o);d.push(...f),c.push(...f);let g=new Set(l.mapping.reads),h=lw(e,u.match.symbol,n,r,i,o).filter(y=>g.has(y.variable));d.push(...h),c.push(...h)}bw(l,d,s,a.get(l.name))}return vo(c)}function bw(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}${Er(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)&&!an(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}${Er(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)&&!an(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 Sw(e,t,n){for(let r of t){if(r.mapping.calls.length===0)continue;let i=r.mapping.calls.map(s=>Lr(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=Bt(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 vw(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=Mw(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 ft(e,t,n,r,i,o=[],s=[],a=[]){let c=xw(e,t,n,r,i,o,s,a);return c||Iw(e,t,n,r,i,o,s,a)}function jr(e,t,n,r,i,o=[],s=[],a=[]){let c=Rw(e,t,n,r,i,o,s,a);return c||Ew(e,t,n,r,i,o,s,a)}function xw(e,t,n,r,i,o=[],s=[],a=[]){let c=Or(e,t);if(!c)return null;let l=[],d=u=>{if(!(u.startPosition.row>r||u.endPosition.row<n)){kw(e,t,u,i,l),Wm(e,t,u,o,"write",l),Gm(e,t,u,s,"write",l),Um(e,t,u,a,"write",l);for(let m of u.children)d(m)}};return d(c.rootNode),So(l)}function Rw(e,t,n,r,i,o=[],s=[],a=[]){let c=Or(e,t);if(!c)return null;let l=[],d=u=>{if(!(u.startPosition.row>r||u.endPosition.row<n)){Pw(e,t,u,i,l),Wm(e,t,u,o,"read",l),Gm(e,t,u,s,"read",l),Um(e,t,u,a,"read",l);for(let m of u.children)d(m)}};return d(c.rootNode),vo(l)}function kw(e,t,n,r,i){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let o=n.childForFieldName("left")??n.namedChild(0);o&&sn(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&&sn(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&&sn(e,t,o,"update",r,i);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let o=n.namedChild(0);o&&sn(e,t,o,"delete",r,i);return}if(n.type==="call_expression"){let o=n.childForFieldName("function")??n.namedChild(0);if(!o||!zm(o))return;sn(e,t,o,"mutation-call",r,i)}}}function Wm(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?yo(s):null;if(!a||!(i==="write"?_m:qm).has(a))return;let d=n.childForFieldName("arguments")?.namedChild(0);if(!d)return;let u=d.text;for(let m of r){if(!u.includes(m.path))continue;let f=Ee(e,t,n.startPosition.row);o.push({variable:m.variable,alias:m.path,file:t,line:n.startPosition.row,target:`${a}(${u})`,kind:"resource",enclosingSymbol:f?.symbol,enclosingShort:f?Q(f.symbol):void 0})}}function yo(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 Gm(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=ww(a);if(c!==null&&Bm(c)===i)for(let l of r){if(!l.regex.test(c))continue;let d=Ee(e,t,n.startPosition.row),u=n.childForFieldName("function")??n.namedChild(0),m=(u&&yo(u))??"call";o.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${m}(${$w(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?Q(d.symbol):void 0})}}}function ww(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function $w(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}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?yo(s):null;if(!a)return;let l=n.childForFieldName("arguments")?.namedChild(0);if(!l)return;let d=l.text.trim();for(let u of r){if(!Jm(u,a,d,i))continue;let m=Ee(e,t,n.startPosition.row);o.push({variable:u.variable,alias:u.table,file:t,line:n.startPosition.row,target:`${a}(${d})`,kind:"orm-call",enclosingSymbol:m?.symbol,enclosingShort:m?Q(m.symbol):void 0})}}function Jm(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 Pw(e,t,n,r,i){if(!(!Cw(n)||Tw(n)))for(let o of r){if(n.text!==o.alias)continue;let s=Ee(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 Cw(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function Tw(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&&go(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&&go(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&zm(n)&&go(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 go(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function zm(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&Mm.has(t.text))}function sn(e,t,n,r,i,o){for(let s of i){if(!Fw(s.alias,n.text))continue;let a=Ee(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 Iw(e,t,n,r,i,o=[],s=[],a=[]){let l=Nm(Fm(e.config.projectRoot,t),"utf8").split(/\r?\n/),d=[],u=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=u;m+=1){let f=l[m]??"";for(let g of i){if(tw(f,g.alias))continue;let h=Le(g.alias);if(!new RegExp(`(?:\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${h}\\b\\s*\\.\\s*(?:${[...Mm].join("|")})\\s*\\(|\\b${h}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(f))continue;let S=Ee(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})}Km(e,t,m,f,o,_m,d),Qm(e,t,m,f,s,"write",d),Ym(e,t,m,f,a,"write",d)}return So(d)}function Ew(e,t,n,r,i,o=[],s=[],a=[]){let l=Nm(Fm(e.config.projectRoot,t),"utf8").split(/\r?\n/),d=[],u=Number.isFinite(r)?Math.min(l.length-1,r):l.length-1;for(let m=Math.max(0,n);m<=u;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=Ee(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})}Km(e,t,m,f,o,qm,d),Qm(e,t,m,f,s,"read",d),Ym(e,t,m,f,a,"read",d)}return vo(d)}function Km(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 u=Ee(e,t,n);s.push({variable:d.variable,alias:d.path,file:t,line:n,target:r.trim(),kind:"resource",enclosingSymbol:u?.symbol,enclosingShort:u?Q(u.symbol):void 0})}}}function Qm(e,t,n,r,i,o,s){if(i.length!==0&&Bm(r)===o)for(let a of i){if(!a.regex.test(r))continue;let c=Ee(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 Ym(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(!Jm(d,c,l,o))continue;let u=Ee(e,t,n);s.push({variable:d.variable,alias:d.table,file:t,line:n,target:r.trim(),kind:"orm-call",enclosingSymbol:u?.symbol,enclosingShort:u?Q(u.symbol):void 0})}}}function jw(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 Lr(e,t,n,r){let i=yn(e,t),o=i.match??(t.includes("#")?yn(e,t.replace("#","/")).match:null);return i.match&&i.total>1&&!Lw(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.`,Aw(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 Lw(e){return/[/#:]/.test(e)}function Aw(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function Dw(e,t,n,r,i,o=!1){let s=bo(e,r);if(s===null||Bw.has(s)||o)return;let a=xo.has(s);i.push(W("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:a?`TLA+ variable ${t} referent is a type; map the runtime state it describes.`:`TLA+ variable ${t} referent is ${qt(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${Q(r.symbol)} with SCIP kind ${qt(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function Ow(e,t,n,r,i){let o=bo(e,r);o===null||Xm.has(o)||xo.has(o)&&i.push(W("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:r.relativePath,startLine:r.startLine,endLine:r.endLine,message:`TLA+ action ${t} referent is a type; map the runtime transition code it describes.`,why:[`${n} resolves to ${Q(r.symbol)} with SCIP kind ${qt(o)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function Nw(e,t,n,r,i){let o=bo(e,n);o===null||Xm.has(o)||i||xo.has(o)&&r.push(W("invalid-referent-kind","error","compiler-symbol",{modelElement:"Init",codeRef:t,file:n.relativePath,startLine:n.startLine,endLine:n.endLine,message:"TLA+ Init referent is a type; map the runtime initialization code it describes.",why:[`${t} resolves to ${Q(n.symbol)} with SCIP kind ${qt(o)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function bo(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function Ee(e,t,n){return hn(e,t).filter(i=>i.startLine<=n&&i.endLine>=n).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine))[0]??null}function Fw(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${Le(e)}([^A-Za-z0-9_$]|$)`).test(t)}function Mw(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 So(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 vo(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 _w(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 ho(e){return e.filter(t=>t.match).length}function Er(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function an(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 xo=new Set(ds()),Xm=new Set(ls()),Bw=new Set(us());function W(e,t,n,r){let i=JSON.stringify({category:e,evidence:n,...r});return{id:`TLA${Yk("sha1").update(i).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...r}}import{readFileSync as Vw}from"fs";import{basename as Hw,join as Zm}from"path";var Ro=/^[A-Za-z_][A-Za-z0-9_]*$/;function ef(e,t,n={}){let r=[],i=hn(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=Vw(Zm(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&&Ro.test(T.leaf)),l=c.map(T=>({variable:T.leaf,alias:T.leaf})),d=l.length>0?ft(e,t,0,Number.POSITIVE_INFINITY,l):[],u=new Set(d.map(T=>T.variable)),m=c.filter(T=>u.has(T.leaf)?!0:Uw(s,T)),f=null,g;if(m.length>0)g=i.filter(T=>a(T)&&T.parentTypeName===null);else{if(f=Ww(e,t,i,a),!f){let T=i.some(O=>!a(O)&&!O.isTypeLike&&O.parentTypeName!==null&&Ro.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=>Jw(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=ft(e,t,T.startLine,T.endLine,y);if(O.length===0)continue;let Z=jr(e,t,T.startLine,T.endLine,y),N=Yw(tf(T.leaf),x);S.push({name:N,leaf:T.leaf,codeRef:Gw(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 k=n.moduleName??Xw(t),R=n.specDir??Zm("specs",k),D=Zw(k,h,S,t),_=e$(),z=t$(k,R,t,h,S);return{moduleName:k,file:t,variables:h,actions:S,warnings:r,spec:D,cfg:_,map:z}}function Ww(e,t,n,r){let i=new Map;for(let s of n){if(r(s)||s.isTypeLike||s.parentTypeName===null||!Ro.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 ft(e,t,m.startLine,m.endLine,l))d.add(f.variable);let u=a.filter(m=>d.has(m.leaf));u.length!==0&&(!o||u.length>o.fields.length)&&(o={className:s,fields:u,methods:c})}return o}function Gw(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function Uw(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function Jw(e,t,n,r,i){let o=zw(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=Kw(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 zw(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function Kw(e,t){let r=t.match(new RegExp(`\\b${n$(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,o=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(r){let l=Qw(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 Qw(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 tf(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function Yw(e,t){let n=e,r=2;for(;t.has(n);)n=`${e}${r++}`;return t.add(n),n}function Xw(e){let n=Hw(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return tf(n||"Model")}function Zw(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(u=>u.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(`
543
+ `)}function e$(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
544
+ `)}function t$(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)}
545
+ `}function n$(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nf(e,t){let n=Object.keys(t.variables),r=Object.entries(t.actions).map(([i,o])=>{let s=o.code[0]??"",a=s?Do(e,s):null;return{action:i,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:o.writes}});return{recorderSource:r$(n),wiring:r,variables:n}}function r$(e){return`/**
546
546
  * Generated by 'scip-query tla instrument'. Dependency-free trace recorder.
547
547
  *
548
548
  * Usage inside a mapped action (record the model-visible slice around the
@@ -585,15 +585,15 @@ export function tlaRecord(action: string, before: Record<string, unknown>, after
585
585
  steps.push({ action, before, after });
586
586
  writeFileSync(tracePath, JSON.stringify(steps, null, 2));
587
587
  }
588
- `}import{copyFileSync as r$,mkdtempSync as i$,readdirSync as o$,rmSync as s$,writeFileSync as nf}from"fs";import{tmpdir as a$}from"os";import{basename as c$,dirname as l$,join as cn}from"path";function Ar(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 d$(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 k=p$(x);k!==void 0&&(y[S]=k)}return y};s.push(c(a));for(let h of n){if(h.before)for(let[y,S]of Object.entries(h.before))y in a||(a[y]=S);Object.assign(a,h.after??{}),s.push(c(a))}let l=t.filter(h=>s.every(y=>h in y)),d=t.filter(h=>!l.includes(h));if(l.length===0)return{error:"no mapped variable had a scalar-encodable value in every trace state"};d.length>0&&i.push(`variables not pinned by the trace (missing or non-scalar values): ${d.join(", ")} \u2014 divergence in these variables is NOT checked.`);let u=`${e}Trace`,m=s.map(h=>` [${l.map(y=>`${y} |-> ${of(h[y])}`).join(", ")}]`).join(`,
588
+ `}import{copyFileSync as i$,mkdtempSync as o$,readdirSync as s$,rmSync as a$,writeFileSync as rf}from"fs";import{tmpdir as c$}from"os";import{basename as l$,dirname as d$,join as cn}from"path";function Ar(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 u$(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 k=m$(x);k!==void 0&&(y[S]=k)}return y};s.push(c(a));for(let h of n){if(h.before)for(let[y,S]of Object.entries(h.before))y in a||(a[y]=S);Object.assign(a,h.after??{}),s.push(c(a))}let l=t.filter(h=>s.every(y=>h in y)),d=t.filter(h=>!l.includes(h));if(l.length===0)return{error:"no mapped variable had a scalar-encodable value in every trace state"};d.length>0&&i.push(`variables not pinned by the trace (missing or non-scalar values): ${d.join(", ")} \u2014 divergence in these variables is NOT checked.`);let u=`${e}Trace`,m=s.map(h=>` [${l.map(y=>`${y} |-> ${sf(h[y])}`).join(", ")}]`).join(`,
589
589
  `),f=[`---- MODULE ${u} ----`,"\\* 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(`
590
590
  `),g=["SPECIFICATION TraceSpec","INVARIANT TraceProgress",""].join(`
591
- `);return{moduleName:u,moduleText:f,cfgText:g,variables:l,skippedVariables:d,states:s.length,warnings:i}}function rf(e){let t=e.mappedActions??[],n=d$(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:Ar(t,[])};let r=i$(cn(a$(),"scip-tla-trace-"));try{let i=l$(e.specPath);for(let d of o$(i))d.endsWith(".tla")&&r$(cn(i,d),cn(r,d));let o=cn(r,`${n.moduleName}.tla`),s=cn(r,`${n.moduleName}.cfg`);nf(o,n.moduleText),nf(s,n.cfgText);let a=Tr({...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:Ar(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:Ar(t,e.steps)};let c=u$(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:Ar(t,l)}}finally{s$(r,{recursive:!0,force:!0})}}function u$(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 p$(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 of(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>of(t)).join(", ")}>>`}function sf(e){return c$(e).replace(/\.tla$/i,"")}import{mkdirSync as cf,writeFileSync as lf}from"fs";import{dirname as m$,join as Dt}from"path";var f$=async(...e)=>{let{args:t,opts:n}=yc(e),r=L(t,0);if(r==="fetch-tools"){let o=await Am();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");le(s=>g$(s,t,n,o));return}if(r==="instrument"){let o=B(t,1);le(s=>h$(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");le(s=>y$(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");le(o=>v$(o,t,n,i))};function g$(e,t,n,r){let i=e.config.projectRoot,o=Zm(e,r,{moduleName:w(n,"moduleName"),specDir:w(n,"out")}),s=w(n,"out")??Dt("specs",o.moduleName),a=pe(i,s);if(!a)throw new Error(`scaffold output dir escapes the project root: ${s}`);let c=b(n,"force"),l=[{path:Dt(a,`${o.moduleName}.tla`),body:o.spec},{path:Dt(a,`${o.moduleName}.cfg`),body:o.cfg},{path:Dt(a,`${o.moduleName}.scip-tla.json`),body:o.map}];for(let d of l)if(!c&&ln(d.path))throw new Error(`refusing to overwrite ${d.path} (pass --force to replace scaffold output)`);cf(a,{recursive:!0});for(let d of l)lf(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 ${Dt(s,`${o.moduleName}.tla`)}'.`)}function h$(e,t,n,r){let i=e.config.projectRoot,o=w(n,"map")??(r?wr(r):void 0);if(!o)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=kr(i,o);if(!s.loaded)throw new Error(s.errors.join(`
592
- `));let{contract:a,mapDir:c}=s.loaded,l=tf(e,a),d=w(n,"out")??Dt(c,"scip-tla-recorder.ts"),u=pe(i,d);if(!u)throw new Error(`instrument output escapes the project root: ${d}`);if(!b(n,"force")&&ln(u))throw new Error(`refusing to overwrite ${u} (pass --force to replace the recorder)`);if(cf(m$(u),{recursive:!0}),lf(u,l.recorderSource),b(n,"json")){I("tla",t,n,{operation:"instrument",recorder:u,variables:l.variables,wiring:l.wiring});return}console.log(`Wrote trace recorder: ${u}`),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 y$(e,t,n,r){let i=e.config.projectRoot,o=pe(i,r);if(!o||!ln(o))throw new Error(`TLA+ spec not found: ${r}`);let s=w(n,"map")??wr(r),a=kr(i,s);if(!a.loaded)throw new Error(a.errors.join(`
593
- `));let{contract:c}=a.loaded,l=wt(n,"trace"),u=ao(i,[...c.traces,...l]).flatMap(g=>so(i,g).steps);if(u.length===0)throw new Error("no trace steps found: pass --trace <file> (repeatable) or list traces in the mapping contract");let m=rf({specPath:o,baseModuleName:sf(o),mappedVariables:Object.keys(c.variables),mappedActions:Object.keys(c.actions),steps:u,nextOperator:w(n,"next"),toolOptions:{projectRoot:i,tlaToolsJar:w(n,"tlaTools"),timeoutMs:U(n,"timeoutMs")}}),f=m.status==="accepted"||m.status==="unavailable"&&b(n,"allowUnknown")?0:1;if(b(n,"json")){I("tla",t,n,{operation:"trace-check",...m,exitCode:f}),process.exitCode=f;return}if(console.log(`TLA+ trace-check: ${o}`),console.log(`Trace: ${u.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")&&b$(m.actionCoverage),process.exitCode=f}function b$(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 S$(e,t,n,r){let i=w(r,"map");if(i)return{mapArg:i};let o=wr(t),s=pe(e,o);if(s&&ln(s))return{mapArg:o};let a=qp(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 v$(e,t,n,r){let i=e.config.projectRoot,o=pe(i,r);if(!o||!ln(o))throw new Error(`TLA+ spec not found: ${r}`);let{mapArg:s,mappingDiscoveredBy:a}=S$(i,r,o,n),c=kr(i,s);if(!c.loaded)throw new Error(c.errors.join(`
594
- `));let{contract:l,mapPath:d,mapDir:u}=c.loaded,m=w(n,"config")??l.config,f=Op(i,u,m),g=R$(w(n,"checker")??"auto"),h=w(n,"tlaTools"),y=x$(i,r,o,h)??Np(i,r),S=Mp(f),x=wt(n,"trace"),R=ao(i,[...l.traces,...x]).map(N=>({tracePath:N,...so(i,N)})),D=R.flatMap(N=>N.steps),_=new Set(x),z=R.filter(N=>_.has(N.tracePath)).flatMap(N=>N.errors),T=Bm(e,l,y,D,S);for(let N of[...c.errors,...z])T.findings.push({id:`TLA-CONTRACT-${T.findings.length+1}`,severity:"error",evidence:"contract",category:"contract",message:N,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=Tr({projectRoot:i,specPath:o,configPath:f??void 0,checker:g,tlaToolsJar:h,apalacheBin:w(n,"apalache"),length:P(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(N=>N.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:k$(O,T,b(n,"allowUnknown"))};if(b(n,"json")){I("tla",t,n,Z),process.exitCode=Z.exitCode;return}w$(Z,b(n,"full")),process.exitCode=Z.exitCode}function x$(e,t,n,r){let i=fo({projectRoot:e,specPath:n,tlaToolsJar:r,checker:"sany"});if(!i)return null;let o=$p({specPath:n,jarPath:i});return o?Fp(e,t,o):null}var df=[{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:C([p("--map <file>","scip-query TLA mapping JSON file"),p("--config <file>","TLA+ checker config file"),p("--checker <mode>","Checker mode: auto, sany, tlc, apalache, none",void 0,"auto"),p("--tla-tools <jar>","Path to tla2tools.jar"),p("--apalache <binary>","Path to apalache-mc binary"),p("--length <n>","Bounded checker length for Apalache",v,10),p("--timeout-ms <n>","Model checker subprocess timeout in milliseconds (verify and trace-check; default 120000)",_e),p("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",rt,[]),p("--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"),p("--coverage","trace-check: print the per-action coverage table (steps exercised per mapped action, counted from accepted trace steps only); --json always includes it"),p("--allow-unknown","Exit zero when only unknown findings remain"),p("--out <path>","Output directory (scaffold) or file (instrument)"),p("--module-name <name>","Module name for scaffolded specs"),p("--force","Overwrite existing scaffold/instrument output"),p("--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:f$}];function R$(e){if(!Dp(e))throw new Error(`unknown checker mode: ${e}`);return e}function k$(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 af=3;function w$(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=P$(e);console.log(`
595
- 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 C$(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)uf(o);return}$$(e.conformance)}function $$(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
591
+ `);return{moduleName:u,moduleText:f,cfgText:g,variables:l,skippedVariables:d,states:s.length,warnings:i}}function of(e){let t=e.mappedActions??[],n=u$(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:Ar(t,[])};let r=o$(cn(c$(),"scip-tla-trace-"));try{let i=d$(e.specPath);for(let d of s$(i))d.endsWith(".tla")&&i$(cn(i,d),cn(r,d));let o=cn(r,`${n.moduleName}.tla`),s=cn(r,`${n.moduleName}.cfg`);rf(o,n.moduleText),rf(s,n.cfgText);let a=Tr({...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:Ar(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:Ar(t,e.steps)};let c=p$(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:Ar(t,l)}}finally{a$(r,{recursive:!0,force:!0})}}function p$(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 m$(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 sf(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>sf(t)).join(", ")}>>`}function af(e){return l$(e).replace(/\.tla$/i,"")}import{mkdirSync as lf,writeFileSync as df}from"fs";import{dirname as f$,join as Dt}from"path";var g$=async(...e)=>{let{args:t,opts:n}=bc(e),r=L(t,0);if(r==="fetch-tools"){let o=await Dm();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");le(s=>h$(s,t,n,o));return}if(r==="instrument"){let o=B(t,1);le(s=>y$(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");le(s=>b$(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");le(o=>x$(o,t,n,i))};function h$(e,t,n,r){let i=e.config.projectRoot,o=ef(e,r,{moduleName:w(n,"moduleName"),specDir:w(n,"out")}),s=w(n,"out")??Dt("specs",o.moduleName),a=pe(i,s);if(!a)throw new Error(`scaffold output dir escapes the project root: ${s}`);let c=b(n,"force"),l=[{path:Dt(a,`${o.moduleName}.tla`),body:o.spec},{path:Dt(a,`${o.moduleName}.cfg`),body:o.cfg},{path:Dt(a,`${o.moduleName}.scip-tla.json`),body:o.map}];for(let d of l)if(!c&&ln(d.path))throw new Error(`refusing to overwrite ${d.path} (pass --force to replace scaffold output)`);lf(a,{recursive:!0});for(let d of l)df(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 ${Dt(s,`${o.moduleName}.tla`)}'.`)}function y$(e,t,n,r){let i=e.config.projectRoot,o=w(n,"map")??(r?wr(r):void 0);if(!o)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=kr(i,o);if(!s.loaded)throw new Error(s.errors.join(`
592
+ `));let{contract:a,mapDir:c}=s.loaded,l=nf(e,a),d=w(n,"out")??Dt(c,"scip-tla-recorder.ts"),u=pe(i,d);if(!u)throw new Error(`instrument output escapes the project root: ${d}`);if(!b(n,"force")&&ln(u))throw new Error(`refusing to overwrite ${u} (pass --force to replace the recorder)`);if(lf(f$(u),{recursive:!0}),df(u,l.recorderSource),b(n,"json")){I("tla",t,n,{operation:"instrument",recorder:u,variables:l.variables,wiring:l.wiring});return}console.log(`Wrote trace recorder: ${u}`),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 b$(e,t,n,r){let i=e.config.projectRoot,o=pe(i,r);if(!o||!ln(o))throw new Error(`TLA+ spec not found: ${r}`);let s=w(n,"map")??wr(r),a=kr(i,s);if(!a.loaded)throw new Error(a.errors.join(`
593
+ `));let{contract:c}=a.loaded,l=wt(n,"trace"),u=ao(i,[...c.traces,...l]).flatMap(g=>so(i,g).steps);if(u.length===0)throw new Error("no trace steps found: pass --trace <file> (repeatable) or list traces in the mapping contract");let m=of({specPath:o,baseModuleName:af(o),mappedVariables:Object.keys(c.variables),mappedActions:Object.keys(c.actions),steps:u,nextOperator:w(n,"next"),toolOptions:{projectRoot:i,tlaToolsJar:w(n,"tlaTools"),timeoutMs:U(n,"timeoutMs")}}),f=m.status==="accepted"||m.status==="unavailable"&&b(n,"allowUnknown")?0:1;if(b(n,"json")){I("tla",t,n,{operation:"trace-check",...m,exitCode:f}),process.exitCode=f;return}if(console.log(`TLA+ trace-check: ${o}`),console.log(`Trace: ${u.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")&&S$(m.actionCoverage),process.exitCode=f}function S$(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 v$(e,t,n,r){let i=w(r,"map");if(i)return{mapArg:i};let o=wr(t),s=pe(e,o);if(s&&ln(s))return{mapArg:o};let a=Bp(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 x$(e,t,n,r){let i=e.config.projectRoot,o=pe(i,r);if(!o||!ln(o))throw new Error(`TLA+ spec not found: ${r}`);let{mapArg:s,mappingDiscoveredBy:a}=v$(i,r,o,n),c=kr(i,s);if(!c.loaded)throw new Error(c.errors.join(`
594
+ `));let{contract:l,mapPath:d,mapDir:u}=c.loaded,m=w(n,"config")??l.config,f=Np(i,u,m),g=k$(w(n,"checker")??"auto"),h=w(n,"tlaTools"),y=R$(i,r,o,h)??Fp(i,r),S=_p(f),x=wt(n,"trace"),R=ao(i,[...l.traces,...x]).map(N=>({tracePath:N,...so(i,N)})),D=R.flatMap(N=>N.steps),_=new Set(x),z=R.filter(N=>_.has(N.tracePath)).flatMap(N=>N.errors),T=Vm(e,l,y,D,S);for(let N of[...c.errors,...z])T.findings.push({id:`TLA-CONTRACT-${T.findings.length+1}`,severity:"error",evidence:"contract",category:"contract",message:N,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=Tr({projectRoot:i,specPath:o,configPath:f??void 0,checker:g,tlaToolsJar:h,apalacheBin:w(n,"apalache"),length:P(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(N=>N.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:w$(O,T,b(n,"allowUnknown"))};if(b(n,"json")){I("tla",t,n,Z),process.exitCode=Z.exitCode;return}$$(Z,b(n,"full")),process.exitCode=Z.exitCode}function R$(e,t,n,r){let i=fo({projectRoot:e,specPath:n,tlaToolsJar:r,checker:"sany"});if(!i)return null;let o=Pp({specPath:n,jarPath:i});return o?Mp(e,t,o):null}var uf=[{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:C([p("--map <file>","scip-query TLA mapping JSON file"),p("--config <file>","TLA+ checker config file"),p("--checker <mode>","Checker mode: auto, sany, tlc, apalache, none",void 0,"auto"),p("--tla-tools <jar>","Path to tla2tools.jar"),p("--apalache <binary>","Path to apalache-mc binary"),p("--length <n>","Bounded checker length for Apalache",v,10),p("--timeout-ms <n>","Model checker subprocess timeout in milliseconds (verify and trace-check; default 120000)",_e),p("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",rt,[]),p("--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"),p("--coverage","trace-check: print the per-action coverage table (steps exercised per mapped action, counted from accepted trace steps only); --json always includes it"),p("--allow-unknown","Exit zero when only unknown findings remain"),p("--out <path>","Output directory (scaffold) or file (instrument)"),p("--module-name <name>","Module name for scaffolded specs"),p("--force","Overwrite existing scaffold/instrument output"),p("--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:g$}];function k$(e){if(!Op(e))throw new Error(`unknown checker mode: ${e}`);return e}function w$(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 cf=3;function $$(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=C$(e);console.log(`
595
+ 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 T$(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)pf(o);return}P$(e.conformance)}function P$(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
596
596
  Finding groups (${e.findingGroups.length}) \u2014 pass --full for every finding ungrouped:`);for(let n of e.findingGroups){console.log(`
597
- [${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let i of n.findingIds.slice(0,af)){let o=t.get(i);o&&uf(o)}let r=n.count-af;r>0&&console.log(` ... and ${r} more in this group (use --full to show all)`)}}function P$(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 C$(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 uf(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(`
598
- [${e.severity}] ${e.category} (${e.evidence})${t}`),console.log(` ${e.message}`);for(let n of e.why)console.log(` why: ${n}`);console.log(` fix: ${e.remediation}`)}var pf=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","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"],T$=[Sm,km,vm,Pr,Rm,wm,df,xm],mf=T$.flat(),I$=new Map(mf.map(e=>[e.id,e]));for(let e of mf)if(!pf.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Ot=pf.map(e=>E$(e));function E$(e){let t=I$.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var j$=Ot.slice(0,ko("plan-context")),L$=Ot.slice(Dr("drift"),ko("self-audit")),A$=Ot.slice(Dr("convergence"),ko("slice")),D$=Ot.slice(Dr("redundant-reexports")),UA=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[p("-l, --language <lang>","Index only this language (can be repeated)",rt,[]),p("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),p("--force","Rebuild even if source inputs are unchanged"),p("--allow-partial","Write an incomplete index when one or more detected languages fail"),p("--indexer-concurrency <n>","Number of language indexers to run at once",_e),p("--json","Output as JSON, including per-shard reuse diagnostics")],renderShape:"custom",docs:$("Indexing",["scip-query reindex"]),handler:Vu},{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:Hu},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[p("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:$("Indexing"),handler:Wu},...j$,{id:Ur,command:Ur,description:"Internal diff-impact batch worker",hidden:!0,options:[p("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:Gu},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:C([p("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:$("Impact"),handler:Uu},...L$,{id:Gr,command:Gr,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:Ju},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded candidate analyses on large indexes"),p("--json","Output as JSON for programmatic consumption"),p("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),p("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:$("Health",["scip-query health --json","scip-query health --baseline"]),handler:zu},{id:"bench",command:"bench",description:"Benchmark indexing and command runtimes for this repository",options:[p("--json","Output as JSON for programmatic consumption"),p("--cold-index","Temporarily clear this project index cache and measure a cold rebuild"),p("--include-heavy","Include expensive full-detector commands in the command matrix"),p("--command <cmd>","Benchmark a specific scip-query command (can be repeated)",rt,[]),p("--timeout-ms <n>","Per-command timeout in milliseconds",_e,18e4),p("--progress","Print benchmark command start/finish progress to stderr"),p("--profile","Enable low-overhead phase profiling in benchmarked commands"),p("--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:Ku},{id:"work-audit",command:"work-audit <profile>",description:"Rank exact repeated computations in a profiling JSONL file by measured avoidable time",options:[p("--top <n>","Maximum repeated-work groups to show",_e,20),p("--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:Qu},{id:"typescript-semantic-compare",command:"typescript-semantic-compare",description:"Compare tsserver reference answers against the ts-morph baseline",hidden:!0,options:[p("-s, --scope <path>","Limit compared definitions to files matching path"),p("--limit <n>","Maximum definitions to compare unless --full is set",_e),p("--max-mismatches <n>","Maximum mismatch details to include in output",kt),p("--full","Compare every indexed TypeScript-like definition"),p("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",handler:Yu},...A$,{id:"install-skills",command:"install-skills",description:`Install skills (${Kn.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:$("Maintenance"),handler:ep},{id:"setup-hooks",command:"setup-hooks",description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[p("--shared","Deprecated compatibility flag; hooks remain checkout-local and untracked"),p("--remove","Remove managed project hooks and remember the opt-out"),p("--force","Reinstall hooks even after a previous --remove opt-out"),p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:tp},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:al},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:cl},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:$("Maintenance"),handler:np},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[p("--matrix","Render the project capability matrix (default output)"),p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:rp},{id:"capability-matrix",command:"capability-matrix",description:"Deprecated alias for capabilities --matrix",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:ip},...D$,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:$("Maintenance"),handler:sp},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance",["scip-query config-validate"]),handler:ap},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding as a file under .scipquery/suppressions/ with a required reason",options:C([p("--reason <text>","Required human reason for accepting the finding"),p("--check <check>","Optional detector/check name to narrow the suppression"),p("--file <path>","Optional file path to narrow the suppression"),p("--expires-at <iso>","Optional ISO date after which the suppression expires")]),renderShape:"custom",docs:$("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:cp},{id:"effectiveness",command:"effectiveness",description:"Per-check effectiveness from the committed outcome ledger: caught, comparison-verified fixes, suppressed, unverified disappearances, and precision",options:C([p("--since <window>","Only count findings first caught in this window (30d, 12w, or an ISO date)"),p("--check <check>","Restrict to one diff-gate check")]),renderShape:"custom",docs:$("Maintenance",["scip-query effectiveness --since 30d","scip-query effectiveness --check echo --json"]),handler:lp},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:dp},{id:"setup",command:"setup",description:"Bootstrap this project: enable automatic indexing, install agent skills, refresh the index, verify capabilities, and report health",options:C([p("--guided","Open the interactive checklist (the default in a terminal)"),p("--yes","Accept recommended setup defaults without prompting"),p("--git-hook","Also install a git pre-commit hook that runs diff-gate"),p("--no-hooks","Skip Codex and Claude Code lifecycle hook installation"),p("--no-skills","Skip user-level agent skill installation"),p("--no-parsers","Skip Tree-sitter AST parser installation and repair"),p("--no-health","Skip the optional full health audit and dossier"),p("--dossier-dir <path>","Directory for generated setup health dossier files")]),renderShape:"custom",docs:$("Maintenance",["scip-query setup","scip-query setup --json"]),handler:mp},{id:"setup-agent",command:"setup-agent",description:"Seed agent guidance for this project: AGENTS.md/CLAUDE.md block pointing agents at the scip-query skills and diff gate, plus an optional git pre-commit backstop",options:[p("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:pp},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[p("--force","Overwrite an existing workflow"),p("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-ci"]),handler:fp},{id:"uninstall",command:"uninstall",description:"Remove scip-query-owned skill links, project hooks, and managed agent setup blocks",options:C([p("--global","Remove scip-query-owned skill symlinks from user-level agent skill roots"),p("--project","Remove project-local hooks and managed AGENTS.md/CLAUDE.md blocks"),p("--dry-run","List what would be removed without changing files")]),renderShape:"custom",docs:$("Maintenance",["scip-query uninstall --dry-run","scip-query uninstall --project"]),handler:gp},{id:"watch",command:"watch",description:"Watch in the foreground or manage the per-project background refresh service",options:C([p("--daemon","Ensure the demand-started background service is running"),p("--status","Show background/foreground watcher state"),p("--stop","Stop the watcher or background service for this project"),p("--debounce <ms>","Ms to wait after last change (default: 250)",kt),p("--cooldown <ms>","Min ms between reindexes; 0 disables spacing (default: 0)",kt),p("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",kt),p("--idle-timeout <ms>","Ms before clean-idle daemon exit; 0 keeps it running (default: 600000)",kt)]),renderShape:"custom",docs:$("Maintenance",["scip-query watch","scip-query watch --daemon","scip-query watch --status --json","scip-query watch --stop"]),handler:hp},{id:"status",command:"status",description:"Show index status for this project",options:[p("--json","Output as JSON for programmatic consumption"),p("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:$("Maintenance"),handler:Sp}];function Dr(e){let t=Ot.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function ko(e){return Dr(e)+1}export{UA as commandDescriptors};
599
- //# sourceMappingURL=command-descriptors-7UUURHWT.js.map
597
+ [${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let i of n.findingIds.slice(0,cf)){let o=t.get(i);o&&pf(o)}let r=n.count-cf;r>0&&console.log(` ... and ${r} more in this group (use --full to show all)`)}}function C$(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 T$(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 pf(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(`
598
+ [${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 mf=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","bottlenecks","isolated","by-kind","kind-counts","deep-chains","hierarchy","call-graph","similar","similar-files","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","similar-chains","extract-candidates","locality-candidates","affected","change-surface","cleanup-plan","cleanup-apply","co-change","recent-duplicates","doc-drift","unused-params","diff-gate","incomplete-migration","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"],I$=[vm,wm,xm,Pr,km,$m,uf,Rm],ff=I$.flat(),E$=new Map(ff.map(e=>[e.id,e]));for(let e of ff)if(!mf.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Ot=mf.map(e=>j$(e));function j$(e){let t=E$.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var L$=Ot.slice(0,ko("plan-context")),A$=Ot.slice(Dr("drift"),ko("self-audit")),D$=Ot.slice(Dr("convergence"),ko("slice")),O$=Ot.slice(Dr("redundant-reexports")),zA=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[p("-l, --language <lang>","Index only this language (can be repeated)",rt,[]),p("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),p("--force","Rebuild even if source inputs are unchanged"),p("--allow-partial","Write an incomplete index when one or more detected languages fail"),p("--indexer-concurrency <n>","Number of language indexers to run at once",_e),p("--json","Output as JSON, including per-shard reuse diagnostics")],renderShape:"custom",docs:$("Indexing",["scip-query reindex"]),handler:Hu},{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:Wu},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[p("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:$("Indexing"),handler:Gu},...L$,{id:Ur,command:Ur,description:"Internal diff-impact batch worker",hidden:!0,options:[p("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:Uu},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:C([p("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:$("Impact"),handler:Ju},...A$,{id:Gr,command:Gr,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:zu},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded candidate analyses on large indexes"),p("--json","Output as JSON for programmatic consumption"),p("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),p("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:$("Health",["scip-query health --json","scip-query health --baseline"]),handler:Ku},{id:"bench",command:"bench",description:"Benchmark indexing and command runtimes for this repository",options:[p("--json","Output as JSON for programmatic consumption"),p("--cold-index","Temporarily clear this project index cache and measure a cold rebuild"),p("--include-heavy","Include expensive full-detector commands in the command matrix"),p("--command <cmd>","Benchmark a specific scip-query command (can be repeated)",rt,[]),p("--timeout-ms <n>","Per-command timeout in milliseconds",_e,18e4),p("--progress","Print benchmark command start/finish progress to stderr"),p("--profile","Enable low-overhead phase profiling in benchmarked commands"),p("--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:Qu},{id:"work-audit",command:"work-audit <profile>",description:"Rank exact repeated computations in a profiling JSONL file by measured avoidable time",options:[p("--top <n>","Maximum repeated-work groups to show",_e,20),p("--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:Yu},{id:"typescript-semantic-compare",command:"typescript-semantic-compare",description:"Compare tsserver reference answers against the ts-morph baseline",hidden:!0,options:[p("-s, --scope <path>","Limit compared definitions to files matching path"),p("--limit <n>","Maximum definitions to compare unless --full is set",_e),p("--max-mismatches <n>","Maximum mismatch details to include in output",kt),p("--full","Compare every indexed TypeScript-like definition"),p("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",handler:Xu},...D$,{id:"install-skills",command:"install-skills",description:`Install skills (${Kn.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:$("Maintenance"),handler:tp},{id:"setup-hooks",command:"setup-hooks",description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[p("--shared","Deprecated compatibility flag; hooks remain checkout-local and untracked"),p("--remove","Remove managed project hooks and remember the opt-out"),p("--force","Reinstall hooks even after a previous --remove opt-out"),p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:np},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:cl},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:ll},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:$("Maintenance"),handler:rp},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[p("--matrix","Render the project capability matrix (default output)"),p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:ip},{id:"capability-matrix",command:"capability-matrix",description:"Deprecated alias for capabilities --matrix",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:op},...O$,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:$("Maintenance"),handler:ap},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance",["scip-query config-validate"]),handler:cp},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding as a file under .scipquery/suppressions/ with a required reason",options:C([p("--reason <text>","Required human reason for accepting the finding"),p("--check <check>","Optional detector/check name to narrow the suppression"),p("--file <path>","Optional file path to narrow the suppression"),p("--expires-at <iso>","Optional ISO date after which the suppression expires")]),renderShape:"custom",docs:$("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:lp},{id:"effectiveness",command:"effectiveness",description:"Per-check effectiveness from the committed outcome ledger: caught, comparison-verified fixes, suppressed, unverified disappearances, and precision",options:C([p("--since <window>","Only count findings first caught in this window (30d, 12w, or an ISO date)"),p("--check <check>","Restrict to one diff-gate check")]),renderShape:"custom",docs:$("Maintenance",["scip-query effectiveness --since 30d","scip-query effectiveness --check echo --json"]),handler:dp},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:$("Maintenance"),handler:up},{id:"setup",command:"setup",description:"Bootstrap this project: enable automatic indexing, install agent skills, refresh the index, verify capabilities, and report health",options:C([p("--guided","Open the interactive checklist (the default in a terminal)"),p("--yes","Accept recommended setup defaults without prompting"),p("--git-hook","Also install a git pre-commit hook that runs diff-gate"),p("--no-hooks","Skip Codex and Claude Code lifecycle hook installation"),p("--no-skills","Skip user-level agent skill installation"),p("--no-parsers","Skip Tree-sitter AST parser installation and repair"),p("--no-health","Skip the optional full health audit and dossier"),p("--dossier-dir <path>","Directory for generated setup health dossier files")]),renderShape:"custom",docs:$("Maintenance",["scip-query setup","scip-query setup --json"]),handler:fp},{id:"setup-agent",command:"setup-agent",description:"Seed agent guidance for this project: AGENTS.md/CLAUDE.md block pointing agents at the scip-query skills and diff gate, plus an optional git pre-commit backstop",options:[p("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:mp},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[p("--force","Overwrite an existing workflow"),p("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:$("Maintenance",["scip-query setup-ci"]),handler:gp},{id:"uninstall",command:"uninstall",description:"Remove scip-query-owned skill links, project hooks, and managed agent setup blocks",options:C([p("--global","Remove scip-query-owned skill symlinks from user-level agent skill roots"),p("--project","Remove project-local hooks and managed AGENTS.md/CLAUDE.md blocks"),p("--dry-run","List what would be removed without changing files")]),renderShape:"custom",docs:$("Maintenance",["scip-query uninstall --dry-run","scip-query uninstall --project"]),handler:hp},{id:"watch",command:"watch",description:"Watch in the foreground or manage the per-project background refresh service",options:C([p("--daemon","Ensure the demand-started background service is running"),p("--status","Show background/foreground watcher state"),p("--stop","Stop the watcher or background service for this project"),p("--debounce <ms>","Ms to wait after last change (default: 250)",kt),p("--cooldown <ms>","Min ms between reindexes; 0 disables spacing (default: 0)",kt),p("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",kt),p("--idle-timeout <ms>","Ms before clean-idle daemon exit; 0 keeps it running (default: 600000)",kt)]),renderShape:"custom",docs:$("Maintenance",["scip-query watch","scip-query watch --daemon","scip-query watch --status --json","scip-query watch --stop"]),handler:yp},{id:"status",command:"status",description:"Show index status for this project",options:[p("--json","Output as JSON for programmatic consumption"),p("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:$("Maintenance"),handler:vp}];function Dr(e){let t=Ot.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function ko(e){return Dr(e)+1}export{zA as commandDescriptors};
599
+ //# sourceMappingURL=command-descriptors-AQWWJNTT.js.map