scip-query 0.19.4 → 0.19.5
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.
- package/CHANGELOG.md +27 -0
- package/README.md +1 -1
- package/dist/{chunk-SVLTAG5O.js → chunk-7UY7SD7D.js} +119 -119
- package/dist/{chunk-VMNZB6WI.js → chunk-TW4OG5FC.js} +2 -2
- package/dist/chunk-XAGAZSFE.js +6 -0
- package/dist/cli.js +3 -3
- package/dist/command-descriptors-N2TL4XM2.js +613 -0
- package/dist/direct-navigation-DUCZCTOE.js +3 -0
- package/docs/AI_FAILURE_MODES.md +1 -1
- package/docs/COMMAND_REFERENCE.md +5 -5
- package/docs/DETECTOR_GUIDE.md +1 -1
- package/package.json +1 -1
- package/skills/_shared/SKILL.md +6 -16
- package/skills/scip-api-impact/SKILL.md +22 -21
- package/skills/scip-claim-audit/SKILL.md +18 -17
- package/skills/scip-cleanup-audit/SKILL.md +24 -20
- package/skills/scip-cleanup-improve/SKILL.md +19 -18
- package/skills/scip-concrete-plan/HIGH_ASSURANCE.md +317 -0
- package/skills/scip-concrete-plan/SKILL.md +70 -227
- package/skills/scip-conductor/SKILL.md +14 -14
- package/skills/scip-debug/SKILL.md +21 -21
- package/skills/scip-diagram/SKILL.md +27 -27
- package/skills/scip-directory-architecture/SKILL.md +44 -32
- package/skills/scip-doc-reconcile/SKILL.md +17 -17
- package/skills/scip-explore/SKILL.md +23 -23
- package/skills/scip-hyper-optimization/SKILL.md +23 -23
- package/skills/scip-language-playbook/SKILL.md +34 -34
- package/skills/scip-maintainability/SKILL.md +21 -21
- package/skills/scip-probe-reachability/SKILL.md +10 -9
- package/skills/scip-query/SKILL.md +39 -39
- package/skills/scip-react-maintainability/SKILL.md +21 -21
- package/skills/scip-root-cause/SKILL.md +21 -20
- package/skills/scip-setup/SKILL.md +25 -24
- package/skills/scip-tla-model-system/SKILL.md +7 -7
- package/skills/scip-triage-issue/SKILL.md +27 -20
- package/skills/scip-twin-drift/SKILL.md +18 -16
- package/skills/scip-verify/SKILL.md +25 -9
- package/skills/scip-vue-maintainability/SKILL.md +21 -21
- package/dist/chunk-ZAIILQNP.js +0 -5
- package/dist/command-descriptors-MFU4BCJ7.js +0 -612
- package/dist/direct-navigation-MRMQFIRB.js +0 -3
|
@@ -0,0 +1,613 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{c as Tc,d as Zi,e as Bn,f as Ic,g as Ec,h as jc,j as Ac}from"./chunk-TW4OG5FC.js";import{a as at,b as x,c as Ve,d as ge,e as Ct,f as p,g as yc,h as Xi,i as bc,j as T,k as C,l as R,m as se,n as ae,o as xe,p as Kt,q as Pc}from"./chunk-XAGAZSFE.js";import{$ as In,$a as Vs,$b as Da,$c as $t,A as Ho,Aa as ys,Ab as ma,Ac as Te,Ad as xc,B as kn,Ba as bs,Bb as fa,Bc as Me,Bd as Ye,C as Uo,Cb as ga,Cd as Rc,D as Go,Da as Ss,Db as ha,Dc as Ka,Dd as ve,E as wn,Ea as vs,Eb as ya,Ec as Qa,Ed as kc,Fa as xs,Fb as ba,Fc as Ya,Fd as ue,G as Ht,Ga as Rs,Gb as Sa,Gc as Xa,Gd as _n,H as Jo,Ha as ks,Hb as Gi,Hc as Za,Hd as wc,I as zo,Ia as ws,Ib as Rt,Ic as ec,Id as L,J as Ko,Ja as $s,Jb as Ln,Jc as tc,Jd as W,K as Oe,Ka as Cs,Kb as Dn,Kc as nc,Kd as $,L as Qe,La as Ps,Lb as va,Lc as ic,Ld as J,M as Qo,Ma as Ts,Mb as xa,Mc as rc,Md as b,N as bt,Nb as Ra,Nc as oc,Nd as Pt,O as $n,Oa as Is,Ob as ka,Oc as sc,Od as P,P as Cn,Pa as Es,Pb as wa,Pc as On,Pd as D,Q as Yo,Qa as js,Qb as $a,Qc as ac,Qd as $c,R as Xo,Ra as As,Rb as Ca,Rc as cc,Rd as E,S as Zo,Sa as Ls,Sb as Pa,Sc as Fn,Sd as Cc,T as Pn,Ta as Ds,Tb as Ta,Tc as lc,Td as G,U as es,Ua as Os,Ub as Ia,Uc as Ji,V as St,Va as Fs,Vb as Ea,Vc as dc,W as vt,Wa as Ns,Wb as Se,Wc as zi,X as ts,Xa as Ms,Xb as ja,Y as ns,Ya as _s,Yb as zt,Yc as X,Z as Tn,Za as Bs,Zb as Aa,_ as is,_a as qs,_b as La,_c as _e,aa as rs,ab as Ws,ac as Oa,ad as uc,ba as En,bb as Jt,bc as Fa,c as Sn,cb as Hs,cc as Na,cd as le,d as me,da as os,db as Us,dc as Ma,e as vn,ea as ss,eb as Gs,ec as _a,ed as Be,f as V,fa as jn,fb as Js,fd as Ki,g as z,ga as Hi,gb as zs,gc as Ba,gd as qe,hb as Ks,hc as qa,hd as oe,ia as as,ib as Qs,ic as Va,id as _,ja as rt,jb as Ys,jd as Nn,kb as Xs,kd as j,lb as Zs,ld as Qi,m as qt,ma as Ut,mb as ea,mc as Fe,md as Yi,n as Vt,na as cs,nb as ta,nc as Ne,nd as Ie,o as Wt,oa as ls,ob as na,oc as kt,od as pc,p as De,pa as ds,pb as ia,pc as Wa,pd as mc,q as Mo,qa as us,qb as ra,qc as fe,qd as Mn,r as xn,ra as Gt,rb as Ui,rc as wt,rd as fc,s as _o,sa as ps,sb as oa,sc as Pe,sd as gc,t as Wi,ta as ms,tb as sa,tc as Ha,td as hc,u as Bo,ua as An,ub as aa,uc as Ua,v as qo,va as fs,vb as ca,vc as Ga,w as Vo,wb as la,wc as ot,wd as de,x as Wo,xa as gs,xb as da,xc as Ja,xd as Q,y as Rn,ya as hs,yb as ua,yc as za,yd as Sc,z as Y,za as xt,zb as pa,zc as st,zd as vc}from"./chunk-7UY7SD7D.js";import{execFileSync as fl,spawn as Zg}from"child_process";import{createHash as eh}from"crypto";import{existsSync as He,mkdirSync as Qn,readFileSync as gl,rmSync as hl,writeFileSync as Xt}from"fs";import{homedir as th}from"os";import{dirname as Zt,isAbsolute as nh,join as At,resolve as ih}from"path";import{execFileSync as Rg}from"child_process";import{existsSync as Lc,readdirSync as Mf}from"fs";import{isAbsolute as _f,join as er,resolve as Bf}from"path";var qf={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:i})=>{let r=i?["index","--output",e,"--no-progress-bar",i]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!i&&r.splice(1,0,"--pnpm-workspaces"),{binary:n,args:r}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:bt.language,indexerBinary:bt.indexerBinary,checkCommand:`${bt.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:bt.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:bt.installUrl},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:i})=>{let r=["-root",e,"-output",t];return i&&r.push("-config",_f(i)?i:Bf(e,i)),{binary:n,args:r}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Dc(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Dc(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({projectRoot:e,indexerBinary:t})=>{let n=er(e,"vendor","bin","scip-php"),i=er(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",Lc(i)?i:Lc(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function ct(e){return qf[e]}function Dc(e,t){let n;try{n=Mf(e)}catch{return null}for(let i of t)for(let r of n)if(r.endsWith(i))return er(e,r);return null}import{createRequire as Vf}from"module";var Wf=Vf(import.meta.url);function Oc(e,t=[]){let n=Hf(),i=ms(e,t),r=i[0];return n?i.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:r,tsconfigPaths:i}:{available:!1,dependencyAvailable:n,tsconfigPath:r,tsconfigPaths:i,reason:"ts-morph is not installed"}}function Hf(){try{return Wf.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as Tt,spawnSync as Uf}from"child_process";import{existsSync as Re,mkdtempSync as _c,readFileSync as Gf,readdirSync as Jf,rmSync as Bc,symlinkSync as zf,writeFileSync as Kf}from"fs";import{tmpdir as qc}from"os";import{join as ce}from"path";var Qf=3e5,Yf=12;function ir(e,t,n={}){let i=rr(e);if(i.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],dirtyWorkingTree:tr(e),batches:[]};let r=tg(t,i),o=n.timeoutMs??Qf,s=sg(e,t),a=tr(e),c=_c(ce(qc(),"scip-cleanup-verify-")),l=[],d=new Map;try{Tt("git",["-C",e,"worktree","add","--detach","--force",c,"HEAD"],{stdio:"ignore"}),ag(e,c);for(let u of i)d.set(u.label,Nc(u,c,o).rawErrors);for(let u of t.batches){Wc(c,u);let m=null;for(let f of i){let g=Nc(f,c,o),h=Xf(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,Yf)};break}}if(!m)l.push({depth:u.depth,status:"verified"});else{l.push(m);break}}}finally{try{Tt("git",["-C",e,"worktree","remove","--force",c],{stdio:"ignore"})}catch{Bc(c,{recursive:!0,force:!0})}}return{checkers:i.map(u=>u.label),uncoveredFiles:r,baselineErrors:[...d.values()].reduce((u,m)=>u+m.length,0),dirtyOverlap:s,dirtyWorkingTree:a,batches:l}}function Xf(e,t,n){let i=Zf(t,n);return i.length>0?{status:"failed",reason:"checker reported new errors",errors:i}: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 Zf(e,t){let n=eg(e),i=new Map,r=[];for(let o of t){let s=Vc(o),a=(i.get(s)??0)+1;i.set(s,a),a>(n.get(s)??0)&&r.push(o)}return r}function eg(e){let t=new Map;for(let n of e){let i=Vc(n);t.set(i,(t.get(i)??0)+1)}return t}function tg(e,t){let n=new Set(t.flatMap(r=>r.coversExtensions));return[...new Set(e.batches.flatMap(r=>r.entries.map(o=>o.file)))].filter(r=>{let o=r.slice(r.lastIndexOf("."));return!n.has(o)}).sort()}function Vc(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var Fc=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"],ng=["deps.edn","project.clj","bb.edn","shadow-cljs.edn"];function rr(e){let t=[];if(Re(ce(e,"tsconfig.json"))){let n=ce(e,"node_modules",".bin","tsc");t.push(Re(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:Fc,strength:"reference-aware"}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:Fc,strength:"reference-aware"})}if(Re(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=>Re(ce(e,n)))){let n=ig();n&&t.push(n)}if(ng.some(n=>Re(ce(e,n)))){let n=rg(e);n&&t.push(n)}for(let n of og(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 ig(){return Oe("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"}:Oe("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"],strength:"syntax-only"}:null}function rg(e){let t=ce(e,"node_modules",".bin","clj-kondo");return Re(t)?{label:"clj-kondo --lint .",binary:t,args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...vn],strength:"reference-aware"}:Oe("clj-kondo")?{label:"clj-kondo --lint .",binary:"clj-kondo",args:["--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...vn],strength:"reference-aware"}:Oe("npx")?{label:"npx clj-kondo --lint .",binary:"npx",args:["--yes","clj-kondo","--lint",".","--config","{:output {:format :json}}"],coversExtensions:[...vn],strength:"reference-aware"}:null}function og(e){let t=[];if(Re(ce(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=Jf(e)}catch{return t}for(let i of n)i==="node_modules"||i.startsWith(".")||Re(ce(e,i,"Cargo.toml"))&&t.push(`${i}/Cargo.toml`);return t}function sg(e,t){let n=new Set(tr(e));return[...new Set(t.batches.flatMap(r=>r.entries.map(o=>o.file)))].filter(r=>n.has(r)).sort()}function tr(e){let t;try{t=Tt("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 ag(e,t){for(let n of["node_modules"]){let i=ce(e,n),r=ce(t,n);if(Re(i)&&!Re(r))try{zf(i,r,"junction")}catch{}}}function Wc(e,t){let n=new Map;for(let i of t.entries){let r=n.get(i.file)??[];r.push({start:i.startLine,end:i.endLine}),n.set(i.file,r)}for(let[i,r]of n){let o=ce(e,i);Re(o)&&Kf(o,cg(Gf(o,"utf-8"),r,{rust:i.endsWith(".rs")}))}}function or(e,t){for(let n of t)Wc(e,n)}function Hc(e,t){let n=_c(ce(qc(),"scip-cleanup-patch-"));try{return Tt("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),or(n,t),Tt("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{Tt("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{Bc(n,{recursive:!0,force:!0})}}}function sr(e,t={}){if(t.all)return[...e.batches];if(t.batch!==void 0){let n=e.batches.find(i=>i.depth===t.batch);return n?[n]:[]}return[...e.batches]}function ar(e,t,n={}){let i=[];e.checkers.length===0&&i.push("No project checker was detected, so no deletion patch is compiler-verified."),e.uncoveredFiles.length>0&&i.push(`No detected checker covers: ${e.uncoveredFiles.join(", ")}.`),!n.allowDirty&&e.dirtyOverlap.length>0&&i.push(`Plan files are dirty in the working tree: ${e.dirtyOverlap.join(", ")}.`);let r=new Set(e.batches.filter(o=>o.status==="verified").map(o=>o.depth));for(let o of t)r.has(o.depth)||i.push(`Batch ${o.depth} is not verified by the detected checker(s).`);return i}function cg(e,t,n={}){let i=e.split(`
|
|
4
|
+
`),r=(n.rust===!0?lg(e):Mo(e)).split(`
|
|
5
|
+
`),o=new Set;for(let s of t){let a=dg(i,s.start),c=pg(r,a,Math.min(s.end,i.length-1));for(let l=a;l<=c&&l<i.length;l++)o.add(l)}return i.filter((s,a)=>!o.has(a)).join(`
|
|
6
|
+
`)}function lg(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 dg(e,t){let n=t;for(;n>0;){let i=(e[n-1]??"").trim();if(/^(?:\/\/\/|\/\/!|#\[|#!\[|\/\*\*|\*|\*\/|@\w)/.test(i))n-=1;else break}return n}var ug=200;function pg(e,t,n){let i=0;for(let r=t;r<e.length;r++){for(let o of e[r]??"")o==="("||o==="["||o==="{"?i+=1:(o===")"||o==="]"||o==="}")&&(i-=1);if(r>=n&&i<=0)return r;if(r-n>ug)break}return n}function Nc(e,t,n){let i=Uf(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,env:e.env??process.env,maxBuffer:33554432}),r=`${i.stdout??""}
|
|
7
|
+
${i.stderr??""}`;if(i.status===0)return{ok:!0,exitCode:0,rawErrors:[],diagnostics:[],parseBasis:"heuristic",outputTail:Mc(r)};let o=mg(e.label,r),s=o.diagnostics.length>0?o.diagnostics:i.error?[{file:"",message:String(i.error),parseBasis:"heuristic"}]:[];return{ok:!1,exitCode:i.status,rawErrors:s.map(xg),diagnostics:s,parseBasis:o.parseBasis,outputTail:Mc(r)}}function mg(e,t){if(e.startsWith("tsc")||e.startsWith("npx tsc"))return{diagnostics:fg(t),parseBasis:"tsc"};if(e.startsWith("go build"))return{diagnostics:gg(t),parseBasis:"go"};if(e.startsWith("ruff")){let n=hg(t);return n.length>0?{diagnostics:n,parseBasis:"ruff-json"}:{diagnostics:yg(t),parseBasis:"ruff-text"}}return e.startsWith("cargo check")?{diagnostics:bg(t),parseBasis:"cargo-json"}:e.includes("clj-kondo")?{diagnostics:Sg(t),parseBasis:"clj-kondo-json"}:{diagnostics:vg(t),parseBasis:"heuristic"}}function fg(e){let t=[],n=/^(.+?)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.+)$/gm;for(let i of e.matchAll(n))t.push({file:i[1]??"",line:Number(i[2]),column:Number(i[3]),code:i[4],message:i[5]??"",parseBasis:"tsc"});return t}function gg(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+(.+)$/gm;for(let i of e.matchAll(n))t.push({file:i[1]??"",line:Number(i[2]),column:Number(i[3]),message:i[4]??"",parseBasis:"go"});return t}function hg(e){let t=Uc(e);if(!Array.isArray(t))return[];let n=[];for(let i of t){if(!i||typeof i!="object")continue;let r=i,o=r.location,s=o&&typeof o=="object"?o:{},a=typeof r.filename=="string"?r.filename:"",c=typeof r.message=="string"?r.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 r.code=="string"?r.code:void 0,message:c,parseBasis:"ruff-json"})}return n}function yg(e){let t=[],n=/^(.+?):(\d+):(\d+):\s+([A-Z]\d{3})\s+(.+)$/gm;for(let i of e.matchAll(n))t.push({file:i[1]??"",line:Number(i[2]),column:Number(i[3]),code:i[4],message:i[5]??"",parseBasis:"ruff-text"});return t}function bg(e){let t=[];for(let n of e.split(`
|
|
8
|
+
`)){if(!n.trim().startsWith("{"))continue;let i=nr(n);if(!i||typeof i!="object")continue;let r=i;if(r.reason!=="compiler-message")continue;let o=r.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 Sg(e){let t=Uc(e);if(!t||typeof t!="object")return[];let n=t.findings;if(!Array.isArray(n))return[];let i=[];for(let r of n){if(!r||typeof r!="object")continue;let o=r;o.level==="error"&&i.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 i}function vg(e){return e.split(`
|
|
9
|
+
`).map(t=>t.trim()).filter(t=>/\berror\b/i.test(t)).map(t=>({file:"",message:t,parseBasis:"heuristic"}))}function xg(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 Uc(e){let t=e.trim();if(t.length===0)return null;if(t.startsWith("{")||t.startsWith("["))return nr(t);let n=Math.min(...[t.indexOf("{"),t.indexOf("[")].filter(i=>i>=0));return Number.isFinite(n)?nr(t.slice(n)):null}function nr(e){try{return JSON.parse(e)}catch{return null}}function Mc(e,t=10){return e.split(`
|
|
10
|
+
`).map(n=>n.trim()).filter(n=>n.length>0).slice(-t)}var zc={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"]},kg={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"},wg={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??ot(e),i=n.map(a=>{let c=Pn(ct(a),e);return{...c,language:a,resolvedBinary:c.resolvedBinary??void 0}}),r=Ag(e,n,t),o=cr({semantics:r},"typescript"),s=rr(e).map(a=>({label:a.label,coversExtensions:a.coversExtensions,strength:a.strength}));return{languages:n,indexers:i,semantics:r,semantic:o,checkers:s,gitAvailable:Og(e)}}function Xe(e,t={}){let n=e.indexers.filter(c=>c.runnable).length,i=e.languages.length===0||n===0&&!t.hasIndexedGraph?"unavailable":n===e.indexers.length&&e.indexers.length>0?"available":"partial",r=i!=="unavailable",o=e.languages.map(c=>Ig(e,c,{hasIndexedGraph:Eg(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:i,evidence:"graph-fact",reason:i==="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.`},...$g(e),{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:r?"available":"unavailable",evidence:"heuristic",reason:r?"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&&r?"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 $g(e){return Cg(e).map(t=>{let n=cr(e,t),i=n?n.available?"available":n.dependencyAvailable?"partial":"unavailable":"unavailable";return{id:`semantic-${t}`,label:`${Pg(t)} semantic provider`,status:i,evidence:"semantic",reason:Tg(t,n)}})}function Cg(e){let t=new Set;for(let n of e.languages)(n==="typescript"||n==="rust")&&t.add(n);for(let n of Qc(e))t.add(n.language);return[...t].sort((n,i)=>Gc(n)-Gc(i))}function Gc(e){return e==="typescript"?0:1}function Pg(e){return e==="typescript"?"TypeScript":"Rust"}function Tg(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 i=e.indexers.find(d=>d.language===t),r=i?.runnable?"available":n.hasIndexedGraph?"partial":"unavailable",o=r!=="unavailable",s=jg(t,n.runtimeProbe),a=Lg(e,t),c=Dg(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:r,evidence:"graph-fact",reason:r==="available"?`${i?.binaryLabel??t} is runnable${i?.resolvedBinary?` at ${i.resolvedBinary}`:""}.`:r==="partial"?`An indexed ${t} graph is present, but ${i?.binaryLabel??t} is not currently runnable for refresh.`:i?.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 ${zc[t].join(", ")} files.`}}}function Eg(e,t){return t.indexedLanguages?t.indexedLanguages.includes(e):t.hasIndexedGraph===!0}function jg(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)??Jc(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=Kc(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 i=t?.(e)??Jc(e);return i==="unavailable"?{status:"partial",reason:"tree-sitter native module not loadable \u2014 regex/import-only evidence remains available where registered."}:i==="regex"?{status:"partial",reason:`${e} source fallback is regex-only for imports and exports.`}:i==="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 Jc(e){let t=kg[e];return t?xn(t):Kc(e)==="regex-only"?"regex":"unavailable"}function Kc(e){let t=wg[e],n=t?Wo(t):null;return n?.imports??n?.exports??n?.reExports??null}function Ag(e,t,n){let i=[];return t.includes("typescript")&&i.push({language:"typescript",...Oc(e,n.semantic?.typescript?.tsconfigs)}),t.includes("rust")&&i.push({language:"rust",...es(e)}),i}function Qc(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function cr(e,t){return Qc(e).find(n=>n.language===t)}function Lg(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=cr(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 Dg(e,t){let n=new Set(zc[t]);return e.checkers.filter(i=>i.coversExtensions.some(r=>n.has(r)))}function Og(e){try{return Rg("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as Fg,existsSync as It,readFileSync as Et,rmSync as Zc,writeFileSync as dr}from"fs";import{join as dt}from"path";var lt="<!-- scip-query:agent-setup:begin -->",qn="<!-- scip-query:agent-setup:end -->",lr="# scip-query:agent-setup";function jt(){if(process.stdin.isTTY)return"";try{return Et(0,"utf-8")}catch{return""}}function Vn(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function Qt(e){let t=Dn(e.findings),n=e.findings.length-t.length,i=e.rootCauseGroups?.length??e.findings.length,r=[`scip-query diff-gate found ${t.length} issue(s) in ${i} 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)r.push(`- group [${s.check}] ${s.count} finding(s): ${s.message}`),r.push(` -> ${s.remediation}`);for(let s of e.findings)r.push(`- [${s.check}]${s.advisory?" (advisory)":""} ${s.message}`),r.push(` -> ${s.remediation}`);return r.join(`
|
|
11
|
+
`)}function Wn(e,t={}){let n={written:[],unchanged:[],skipped:[]};return Ng(e,n),t.gitHook&&Mg(e,n),n}function el(e,t={}){let n={removed:[],unchanged:[],skipped:[]};return Xc(e,"AGENTS.md",t,n),Xc(e,"CLAUDE.md",t,n),_g(e,t,n),n}function Ng(e,t){let n=[lt,"## scip-query","","This repo is indexed by scip-query (compiler-resolved code intelligence).","","- Use native search and file reads for literal text and source. Use scip-query when a claim depends on compiler-resolved identity, references, callers, dependencies, consumers, public surface, transitive impact, architecture, historical co-change, or a scip detector/gate.","- 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 a non-trivial change: establish the current entry-to-effect flow, the affected consumers, and the reuse options before editing (`scip-concrete-plan` skill, anchored by `scip-query plan-context <target>`).","- Before claiming a complete relationship set, inspect the command coverage. If it is bounded or unknown, use `--full`, a narrower scope, or command pagination before making the claim.","- After the change, run the postchecks matching what you actually edited \u2014 the table is in the `scip-verify` skill \u2014 then `scip-query diff-gate`. Fix findings or state why each is accepted.","- For `refs`, `trace`, `system`, `plan-context`, and `diff-gate`, do not pipe output through `head`, `tail`, or line-range `sed`; use `--json --compact`, and use `refs --limit` plus its continuation cursor when pagination is needed.","- 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.",qn].join(`
|
|
12
|
+
`);Yc(e,"AGENTS.md",n,t);let i=It(dt(e,"CLAUDE.md"))?Et(dt(e,"CLAUDE.md"),"utf-8"):"";if(i.includes("@AGENTS.md")&&!i.includes(lt)){t.unchanged.push("CLAUDE.md");return}let r=[lt,"@AGENTS.md",qn].join(`
|
|
13
|
+
`);Yc(e,"CLAUDE.md",r,t)}function Yc(e,t,n,i){let r=dt(e,t),o=It(r)?Et(r,"utf-8"):"",s;if(o.includes(lt)){let a=new RegExp(`${lt}[\\s\\S]*?${qn}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
|
|
14
|
+
|
|
15
|
+
`)}${n}
|
|
16
|
+
`:`${n}
|
|
17
|
+
`;s===o?i.unchanged.push(t):(dr(r,s),i.written.push(t))}function Xc(e,t,n,i){let r=dt(e,t);if(!It(r)){i.unchanged.push(t);return}let o=Et(r,"utf-8");if(!o.includes(lt)){i.unchanged.push(t);return}let s=new RegExp(`${lt}[\\s\\S]*?${qn}`),a=o.replace(s,"").replace(/\n{3,}/g,`
|
|
18
|
+
|
|
19
|
+
`).trim();i.removed.push(t),!n.dryRun&&(a.length===0?Zc(r,{force:!0}):dr(r,`${a}
|
|
20
|
+
`))}function Mg(e,t){let n=dt(e,".git","hooks");if(!It(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let i=dt(n,"pre-commit"),r=["#!/bin/sh",lr,"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(It(i)){let o=Et(i,"utf-8");if(o.includes(lr)){if(o===r){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}}dr(i,r),Fg(i,493),t.written.push(".git/hooks/pre-commit")}function _g(e,t,n){let i=dt(e,".git","hooks","pre-commit");if(!It(i)){n.unchanged.push(".git/hooks/pre-commit");return}if(!Et(i,"utf-8").includes(lr)){n.skipped.push({target:".git/hooks/pre-commit",reason:"pre-commit hook is not managed by scip-query"});return}n.removed.push(".git/hooks/pre-commit"),t.dryRun||Zc(i,{force:!0})}import{createHash as Bg}from"crypto";import{existsSync as Un,mkdirSync as qg,readFileSync as Gn,readdirSync as Vg,rmSync as tl,writeFileSync as nl}from"fs";import{join as We}from"path";var Jn=We(".scipquery","events"),Wg=We(".scipquery","ledger"),il="events.jsonl";function rl(e){return We(e,Wg)}function ur(e){return We(rl(e),il)}function ol(e,t){let n=ur(e),i=Un(n),r=[...i?sl(n):[],...t];if(r.length>0){let o=We(e,Jn);qg(o,{recursive:!0});for(let s of r)Hg(o,s)}i&&Ug(e)}function Hg(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
|
+
`,i=Bg("sha256").update(n).digest("hex").slice(0,16).toUpperCase(),r=We(e,`${t.ts}-${i}.json`);try{nl(r,n,{flag:"wx"})}catch(o){if(o.code!=="EEXIST")throw o;if(Gn(r,"utf-8")!==n)throw new Error(`outcome event filename collision: ${r}`,{cause:o})}}function Ug(e){tl(ur(e));let t=We(rl(e),".gitattributes");if(!Un(t))return;let n=Gn(t,"utf-8").split(`
|
|
23
|
+
`).filter(i=>i.trim()!==`${il} merge=union`).join(`
|
|
24
|
+
`).replace(/^\n+|\n+$/g,"");n===""?tl(t):nl(t,`${n}
|
|
25
|
+
`)}function zn(e){let t=[],n=We(e,Jn);if(Un(n))for(let r of Vg(n).sort()){if(!r.endsWith(".json"))continue;let o=al(Gn(We(n,r),"utf-8"));o&&t.push(o)}let i=ur(e);return Un(i)&&t.push(...sl(i)),Gg(t)}function sl(e){let t=[];for(let n of Gn(e,"utf-8").split(`
|
|
26
|
+
`)){let i=al(n);i&&t.push(i)}return t}function al(e){if(e.trim()==="")return null;let t;try{t=JSON.parse(e)}catch{return null}return zg(t)?t:null}function Gg(e){let t=new Map;for(let n of e){let i=`${n.check}\0${n.findingId}\0${n.event}\0${n.commit??""}`,r=t.get(i);(!r||Hn(n)>Hn(r)||Hn(n)===Hn(r)&&n.ts<r.ts)&&t.set(i,n)}return[...t.values()].sort((n,i)=>n.ts-i.ts)}function Hn(e){return+(e.comparisonBaseCommit!==void 0)+ +(e.verifiedAgainstCommit!==void 0)*2}var Jg=["caught","resolved","suppressed","reopened"];function zg(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"&&Jg.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 Kn(e,t,n={}){let i=(n.now??Date.now)(),r=Yg(t),o=Da(e),s=e.config.projectRoot,a=n.headCommit?n.headCommit(s):rt(s)?.headCommit??null,c=n.resolveCommit?n.resolveCommit(s,t.base):Qg(s,t.base),l=Kg({previous:o,observed:r,result:t,projectRoot:s,commit:a,comparisonBaseCommit:c,runtime:n}),d=Oa(e,l.ledgerObserved,l.checksRun,i,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=ja(o,d,u,a,i,{...c?{comparisonBaseCommit:c}:{},verifiedAgainstByFinding:l.verifiedAgainstByFinding});return(n.appendEvents??ol)(s,m),{ledger:d,observed:r,now:i,...l.warning?{warning:l.warning}:{}}}catch(u){return{ledger:d,observed:r,now:i,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),i=new Set,r=new Map,o=new Map,s=new Set(e.observed.map(h=>Se(h.check,h.findingId))),a=new Set(e.result.checksRun),c=e.result.changedFiles.length===0&&!Ln(e.result)&&e.commit!==null&&e.comparisonBaseCommit!==null,l=e.previous.filter(h=>h.outcome!=="resolved"&&(a.has(h.check)||c)&&!s.has(Se(h.check,h.findingId)));if(ut(`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:i,verifiedAgainstByFinding:r,replaySymbols:o};let d;try{d=(e.runtime.readEvents??zn)(e.projectRoot)}catch(h){for(let y of l)i.add(Se(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:i,verifiedAgainstByFinding:r,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=Se(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=Se(h.check,h.findingId),S=zt(u.get(y)??[]),v=S?.comparisonBaseCommit??S?.commit;if(ut(`candidate ${y} anchor=${String(v)} current=${String(e.comparisonBaseCommit)}`),!S?.comparisonBaseCommit&&S?.commit&&S.commit===e.commit){n.add(h.check);continue}if(!v||!e.commit||!e.comparisonBaseCommit){i.add(y);continue}if(v===e.comparisonBaseCommit){n.add(h.check);continue}let w=m.get(v)??[];w.push(h),m.set(v,w)}if(m.size===0)return{ledgerObserved:t,checksRun:[...n],retainedKeys:i,verifiedAgainstByFinding:r,replaySymbols:o};let f=e.runtime.worktreeIsClean?.(e.projectRoot)??rt(e.projectRoot)?.clean??!1;if(ut(`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)i.add(Se(y.check,y.findingId));return{ledgerObserved:t,checksRun:[...n],retainedKeys:i,verifiedAgainstByFinding:r,replaySymbols:o}}let g=[];for(let[h,y]of m){let S;try{S=e.runtime.replayGate(h),ut(`replay base=${h} checks=${S.checksRun.join(",")} findings=${S.findings.length} suppressed=${S.suppressed.length}`)}catch(k){for(let O of y)i.add(Se(O.check,O.findingId));g.push(`cross-HEAD outcome verification deferred for ${h.slice(0,12)}: ${k instanceof Error?k.message:String(k)}`);continue}let v=new Set(S.checksRun),w=Xg(S);for(let k of y){let O=Se(k.check,k.findingId);if(!v.has(k.check)){i.add(O);continue}n.add(k.check);let q=w.find(F=>F.key===O);if(q){ut(`replay retained exact ${O}`),t.push(q.observed),q.symbol&&o.set(q.observed.findingId,q.symbol);continue}let K=zt(u.get(O)??[]),I=K?.symbol?w.find(F=>F.check===k.check&&F.symbol===K.symbol):void 0;if(I){ut(`replay moved ${O} -> ${I.key}`),t.push(I.observed),I.symbol&&o.set(I.observed.findingId,I.symbol);continue}r.set(O,h),ut(`replay verified ${O} against ${h}`)}}return{ledgerObserved:t,checksRun:[...n],retainedKeys:i,verifiedAgainstByFinding:r,replaySymbols:o,...g.length>0?{warning:g.join("; ")}:{}}}function Qg(e,t){let n=Ut(e,["rev-parse","--verify",`${t}^{commit}`]);return n&&/^[0-9a-f]{40}$/.test(n)?n:null}function ut(e){process.env.SCIP_QUERY_DEBUG&&console.error(`outcome-verification: ${e}`)}function Yg(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 Xg(e){return[...e.findings.map(t=>({key:Se(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:Se(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 yl="SCIP_QUERY_SKIP_HOOK_INSTALL",pr="SCIP_QUERY_STOP_HOOK_MODE",rh="scip-query hook-",oh="scip-query diff-gate --hook",cl="# scip-query:local-hooks:begin",ll="# scip-query:local-hooks:end",Yt=[{relativePath:".codex/hooks.json",label:".codex/hooks.json"},{relativePath:".claude/settings.local.json",label:".claude/settings.local.json"}];function Lt(e,t={}){let n=bl(),i=t.env??process.env;if(lh(i))return n.skipped.push({target:"project agent hooks",reason:`${yl}=1`}),n;let r=hh(e);return t.shared&&n.warnings.push("--shared is deprecated; project hooks are always checkout-local and will not be committed."),ah(e,n,t.dryRun),t.remove?(ul(e,Yt[0],n,{dryRun:t.dryRun}),ul(e,Yt[1],n,{writeDeclinedTombstone:!0,dryRun:t.dryRun}),n):(dl(e,Yt[0],n,{provider:"codex",commandPrefix:r,force:t.force}),dl(e,Yt[1],n,{provider:"claude",commandPrefix:r,force:t.force}),t.removeLegacyUserHooks!==!1&&sh({homeDir:t.homeDir,result:n}),n)}function sh(e={}){let t=e.result??bl(),n=e.homeDir??th();return mr({configPath:At(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),mr({configPath:At(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function bl(){return{installed:[],updated:[],unchanged:[],removed:[],gitExcluded:[],warnings:[],skipped:[]}}function dl(e,t,n,i){if(fr(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook setup will not modify it"});return}let r=At(e,t.relativePath);uh({provider:i.provider,rootDir:Zt(r),configPath:r,label:t.label,createRoot:!0,commandPrefix:i.commandPrefix,force:i.force,result:n})}function ul(e,t,n,i){if(fr(e,t.relativePath)){n.skipped.push({target:t.label,reason:"tracked repository config; checkout-local hook removal will not modify it"});return}ph({configPath:At(e,t.relativePath),label:t.label,result:n,writeDeclinedTombstone:i.writeDeclinedTombstone,dryRun:i.dryRun})}function ah(e,t,n=!1){let i=ch(e);if(!i){t.warnings.push("Could not locate .git/info/exclude; local hook files may appear as untracked.");return}let r=Yt.filter(d=>!fr(e,d.relativePath));if(r.length===0)return;let o=[cl,...r.map(d=>`/${d.relativePath}`),ll].join(`
|
|
27
|
+
`),s=He(i)?gl(i,"utf-8"):"",a=new RegExp(`${De(cl)}[\\s\\S]*?${De(ll)}\\n?`,"g"),c=s.replace(a,"").replace(/\n*$/,""),l=`${c}${c?`
|
|
28
|
+
|
|
29
|
+
`:""}${o}
|
|
30
|
+
`;!n&&l!==s&&(Qn(Zt(i),{recursive:!0}),Xt(i,l)),t.gitExcluded.push(...r.map(d=>d.label))}function ch(e){try{let t=fl("git",["-C",e,"rev-parse","--git-path","info/exclude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();return t?nh(t)?t:ih(e,t):null}catch{return null}}function fr(e,t){try{return fl("git",["-C",e,"ls-files","--error-unmatch","--",t],{stdio:"ignore"}),!0}catch{return!1}}function lh(e=process.env){let t=e[yl];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function dh(e=process.env){let t=e[pr]?.toLowerCase();return t==="block"||t==="blocking"?"block":t==="warn"?"warn":"feedback"}function uh(e){if(!e.createRoot&&!He(e.rootDir))return;let t=gr(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=mh(t,e.provider,e.commandPrefix);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let i=He(e.configPath);Qn(Zt(e.configPath),{recursive:!0}),Xt(e.configPath,`${JSON.stringify(n,null,2)}
|
|
31
|
+
`),e.result[i?"updated":"installed"].push(e.label)}function mr(e){if(!He(e.configPath))return;let t=gr(e.configPath,e.label,e.result);if(!t)return;let n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:{},i={...n},r=!1;for(let s of["SessionStart","UserPromptSubmit","PostCompact","PreToolUse","Stop"]){let a=Array.isArray(n[s])?n[s]:[],c=Sl(a);(c.length!==a.length||JSON.stringify(c)!==JSON.stringify(a))&&(r=!0,c.length>0?i[s]=c:delete i[s])}if(!r)return;let o={...t};Object.keys(i).length>0?o.hooks=i:delete o.hooks,e.dryRun||(Object.keys(o).length===0?hl(e.configPath,{force:!0}):Xt(e.configPath,`${JSON.stringify(o,null,2)}
|
|
32
|
+
`)),e.result.removed.push(e.label)}function ph(e){let t=e.result.removed.length;if(mr(e),!e.writeDeclinedTombstone)return;let n=gr(e.configPath,e.label,e.result);if(!n)return;let i={...n,scipQueryHooks:"declined"};e.dryRun||(Qn(Zt(e.configPath),{recursive:!0}),Xt(e.configPath,`${JSON.stringify(i,null,2)}
|
|
33
|
+
`)),e.result.removed.length===t&&e.result.removed.push(`${e.label} (declined)`)}function gr(e,t,n){if(!He(e))return{};try{let i=JSON.parse(gl(e,"utf-8"));if(!i||typeof i!="object"||Array.isArray(i)){n.skipped.push({target:t,reason:"existing hook config is not a JSON object"});return}return i}catch(i){n.skipped.push({target:t,reason:`could not parse existing hook config: ${i instanceof Error?i.message:String(i)}`});return}}function mh(e,t,n="scip-query"){let i=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},r={...e,hooks:{...i}};r.scipQueryHooks==="declined"&&delete r.scipQueryHooks;let o=t==="claude"?["SessionStart","UserPromptSubmit","PostCompact","PreToolUse","Stop"]:["SessionStart","UserPromptSubmit","Stop"];for(let s of o){let a=Array.isArray(i[s])?i[s]:[];r.hooks[s]=[...Sl(a),gh(t,s,n)]}return r}function Sl(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!fh(n)):[]})).filter(t=>t.hooks.length>0)}function fh(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(rh)||t===oh)}function gh(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"}]}:t==="PostCompact"?{hooks:[{type:"command",command:`${n} hook-context`,timeout:10,statusMessage:"Resetting scip-query context reminder"}]}:t==="PreToolUse"?{matcher:"Bash|Grep|Glob",hooks:[{type:"command",command:`${n} hook-pretool`,timeout:10,statusMessage:"Checking scip-query evidence integrity"}]}:{hooks:[{type:"command",command:`${n} hook-stop`,timeout:30,statusMessage:"Running scip-query diff gate"}]}}function hh(e){let t=At(e,"node_modules",".bin","scip-query");return He(t)?t:"scip-query"}async function vl(){let e=await wh(jt());e&&console.log(JSON.stringify(e))}function xl(){let e=hr(jt()),t=yr(e);if(!t||!He(t.paths.dbPath))return;let n=Rl(t.paths.cacheDir,e),i=bh(e,n?He(n):!0);if(i.kind==="allow")return;i.kind==="reconsider"&&n&&(Qn(Zt(n),{recursive:!0}),Xt(n,`shown
|
|
34
|
+
`));let r={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:i.reason}};console.log(JSON.stringify(r))}var yh=["refs","trace","system","plan-context","diff-gate"];function bh(e,t){let n=typeof e.tool_name=="string"?e.tool_name:"",i=e.tool_input&&typeof e.tool_input=="object"?e.tool_input:{},r=n==="Bash"&&typeof i.command=="string"?i.command:"";return r&&Sh(r)?{kind:"deny",reason:"Do not pipe scip-query output through head, tail, or a line-range sed selector: that hides whether evidence was omitted. Re-run with --json --compact; for refs, use --limit and the returned coverage.continuation.cursor."}:!(n==="Grep"||n==="Glob"||n==="Bash"&&/(?:^|[;&|]\s*)(?:rg|grep)(?:\s|$)/.test(r))||t?{kind:"allow"}:{kind:"reconsider",reason:"Pause once before native search in this indexed repository. If you need compiler-resolved identity or a complete set of definitions, references, callers, consumers, dependencies, or affected units, use scip-query. If you only need literal text, filenames, or local source, retry the same search unchanged; it will be allowed for the rest of this context window."}}function Sh(e){let t=yh.join("|");return new RegExp(`(?:^|[;&(]\\s*|\\s)(?:\\S*/)?scip-query\\s+(?:${t})(?:\\s|$)`).test(e)?/\|\s*(?:head|tail)(?:\s|$)/.test(e)||/\|\s*sed\s+(?:-[A-Za-z]+\s+)*(?:['"])?\d+\s*,\s*\d+\s*p/.test(e):!1}function Rl(e,t){let n=typeof t.session_id=="string"?t.session_id:null;if(!n)return null;let i=eh("sha256").update(n).digest("hex").slice(0,24);return At(e,"agent-hooks",`native-search-${i}`)}function vh(e,t){let n=Rl(e.paths.cacheDir,t);n&&hl(n,{force:!0})}function xh(e){if(Vn(e))return;let t=hr(e),n=yr(t);if(!(!n||!He(n.paths.dbPath)))return Lh(n,i=>{let r={minTogether:6,skip:[]},o=Rt(i,r),s=Kn(i,o,{replayGate:a=>Rt(i,{...r,base:a})});return s.warning&&console.error(`note: ${s.warning}`),o})}function kl(){let e=xh(jt());!e||e.findings.length===0||console.log(JSON.stringify(Rh(e,dh())))}function Rh(e,t="feedback"){let n=Qt(e),i=kh(e);return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${i}
|
|
35
|
+
|
|
36
|
+
This is non-error Stop hook feedback. Fix true findings, or explain why a finding is intentionally accepted before finishing.`}}:{systemMessage:`${i}
|
|
37
|
+
|
|
38
|
+
Stop hook allowed this turn to finish. Review these findings when relevant. Set ${pr}=feedback to ask the agent to continue without a hook error, or ${pr}=block to enforce the gate.`}}function kh(e){return Qt(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}async function wh(e){let t=hr(e),n=Ah(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit"&&n!=="PostCompact")return;let i=yr(t);if(!i||((n==="SessionStart"||n==="PostCompact")&&vh(i,t),n==="PostCompact"))return;let r=await Ch(i,n),o=n==="SessionStart"?Th(i.projectRoot,i.config,i.paths):Ih(String(t.prompt??""),i.config),s=[r,o].filter(a=>!!a?.trim()).join(`
|
|
39
|
+
`);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}var $h={prepare:uc,ensureService:Tc,freshness:Te,requestRefresh:Ec,startOneShot(e){Zg("scip-query",["reindex","--allow-partial"],{cwd:e,detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_AUTO_INSTALL:"1"}}).unref()}};async function Ch(e,t,n=$h){let i=Pe(e.config);if(i.autoRefresh===!1)return;n.prepare?.(e.projectRoot,e.config,e.paths);let r=n.freshness(e.projectRoot,e.config,e.paths);if(i.enabled){let o=n.ensureService({commandName:`agent-${t}`,projectRoot:e.projectRoot,cacheDir:e.paths.cacheDir,cliVersion:Me,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"?r.state==="fresh"?void 0:`scip-query index is ${r.state}; automatic watch service wake was skipped (${o.reason}).`:(Ph(o,r.state,e.paths.cacheDir,n),r.state!=="fresh"?`scip-query index is ${r.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(r.state!=="fresh"){if(t==="UserPromptSubmit")return`scip-query index is ${r.state}; evidence commands will note staleness. Run 'scip-query reindex' to refresh.`;try{return n.startOneShot(e.projectRoot),`scip-query index is ${r.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 ${r.state}, but background refresh failed to start: ${s}`}}}function Ph(e,t,n,i){t==="fresh"||e.kind==="started"||e.state.watcher.state!=="idle"||i.requestRefresh(jn(n).activityPath,`agent hook observed ${t} index while service was idle`)}function Th(e,t,n){let i=Te(e,t,n),r=he(e,t),s=Xe(r).capabilities.filter(c=>c.status!=="available").map(c=>c.label),a=r.languages.length>0?r.languages.join(", "):"none detected";return[`scip-query is available in this repository. Index state: ${i.state} (${i.reason})`,i.lastRefresh?`Last refresh: ${i.lastRefresh.result} by ${i.lastRefresh.trigger.kind} at ${i.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.","Before a non-trivial edit, establish the current entry-to-effect flow, affected consumers, and reuse options with scip-concrete-plan; then verify the finished diff with scip-verify."].filter(c=>c!==void 0).join(`
|
|
40
|
+
`)}function Ih(e,t={},n=process.env){if(jh(t,n)==="off")return"";let i=Eh(e);return i?`scip-query routing reminder:
|
|
41
|
+
${i.message}`:""}var pl=[{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","broken","doesn't work","not working","crash"],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:"Before editing: use scip-concrete-plan and `scip-query plan-context <target>` to establish the current flow, affected consumers, and reuse options. After editing: use 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=pl.find(r=>r.skillNames.some(o=>ml(e,o)));if(t)return t;let n=0,i=[];for(let r of pl){let o=r.keywords.filter(s=>ml(e,s)).length;n+=o,o>0&&i.push(r)}return n<2||i.length===0?null:i[0]}function jh(e,t){return t.SCIP_QUERY_ROUTER==="off"?"off":e.hooks?.router??"single"}function ml(e,t){let n=t.trim().split(/\s+/).map(i=>De(i)).join("\\s+");return new RegExp(`(?<![A-Za-z0-9_-])${n}(?![A-Za-z0-9_-])`,"i").test(e)}function hr(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Ah(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function yr(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=as(t);if(n)try{let i=fe(n),r=Fe(n,i);return{projectRoot:n,config:i,paths:r}}catch{return}}function Lh(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,sharedEvidenceDbPath:cc(e.projectRoot,e.config),entryRoots:e.config.entryRoots,semantic:e.config.semantic,suppressions:e.config.suppressions,declaredCouplings:e.config.declaredCouplings,locality:e.config.locality,architecture:e.config.architecture,coverageContracts:e.config.coverageContracts,docs:e.config.docs},i=new Ne(n,kt(e.projectRoot));try{return t(i)}finally{i.close()}}import{existsSync as Xn,mkdirSync as _h,symlinkSync as Bh,readlinkSync as vr,unlinkSync as xr,readdirSync as Il}from"fs";import{join as Ee,dirname as nn,resolve as Ze,relative as qh,isAbsolute as Vh}from"path";import{homedir as Zn,platform as Wh}from"os";import{fileURLToPath as El}from"url";import{execFileSync as wl}from"child_process";import{createRequire as Dh}from"module";import{existsSync as Oh}from"fs";import{platform as en,arch as $l}from"os";var Cl="v0.8.1",br="https://github.com/sourcegraph/scip",Pl="SCIP_QUERY_SCIP_BIN";function Fh(e){if(e.isOnPath("scip"))return{source:"path",path:"scip"};let t=e.env[Pl];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 Nh(e){let t=Dh(import.meta.url);for(let n of e==="arm64"?["arm64","x64"]:[e])try{return t.resolve(`scip-query-scip-windows/scip-win32-${n}.exe`)}catch{}return null}function Yn(e=process.env){return Fh({platform:en(),arch:$l(),env:e,isOnPath:Qe,fileExists:Oh,resolveSidecar:Nh})?.path??null}function tn(){return Yn()!==null}function Mh(){let e=en(),t=$l(),n,i,r;switch(e){case"darwin":n="darwin",r="tar.gz";break;case"linux":n="linux",r="tar.gz";break;default:return null}switch(t){case"arm64":i="arm64";break;case"x64":i="amd64";break;default:return null}let o=`scip-${n}-${i}.${r}`;return{url:`${br}/releases/download/${Cl}/${o}`,filename:o}}function Sr(){let e=Mh();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),en()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
|
|
42
|
+
`),console.log("Or download manually:")):en()==="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 ${Pl} to a local scip.exe path.
|
|
43
|
+
`),console.log("Upstream release page:")):console.log("Download from:"),console.log(e?` ${e.url}
|
|
44
|
+
`:` ${br}/releases/tag/${Cl}
|
|
45
|
+
`),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function Tl(e){if(en()==="darwin"&&Qe("brew")){e("Installing scip CLI via Homebrew...");try{if(wl("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),Qe("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(Qe("go")){e("Installing scip CLI via go install...");try{if(wl("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),Qe("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: ${br}/releases`),!1}var Hh=Wh()==="win32",ei=["_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 ti(e={}){let t=e.quiet?()=>{}:console.log,n=El(import.meta.url),i=Ze(nn(n),"..","skills"),r=[Ee(Zn(),".claude","skills"),Ee(Zn(),".codex","skills"),Ee(Zn(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let s of r){let a=nn(s);if(!Xn(a))continue;_h(s,{recursive:!0});let c=Ll(s);Uh(s,i,c,o,t);for(let l of ei){let d=Ee(i,l),u=Ee(s,l);if(!Xn(d)){o.skipped.push(`${c}/${l}`);continue}if(Xn(u)){try{let m=vr(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}xr(u)}Bh(d,u,Hh?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function Uh(e,t,n,i,r){let o=new Set(ei);for(let s of Il(e)){if(o.has(s))continue;let a=Ee(e,s),c;try{c=Ze(nn(a),vr(a))}catch{continue}Al(c,t)&&(xr(a),i.pruned.push(`${n}/${s}`),r(` prune: ${s} \u2192 ${n} (removed stale scip-query skill link)`))}}function jl(e={}){let t=El(import.meta.url),n=Ze(nn(t),"..","skills"),i=e.homeDir??Zn(),r=[Ee(i,".claude","skills"),Ee(i,".codex","skills"),Ee(i,".agents","skills")],o={removed:[],left:[],skipped:[]};for(let s of r){if(!Xn(s))continue;let a=Ll(s);for(let c of Il(s)){let l=Ee(s,c),d;try{let u=vr(l);d=Ze(nn(l),u)}catch{o.left.push(`${a}/${c} (not a symlink)`);continue}if(!Al(d,n)){o.left.push(`${a}/${c} (symlink outside scip-query package)`);continue}if(o.removed.push(`${a}/${c}`),!e.dryRun)try{xr(l)}catch(u){o.skipped.push(`${a}/${c} (${u instanceof Error?u.message:String(u)})`)}}}return o}function Al(e,t){let n=qh(Ze(t),Ze(e));return n===""||!n.startsWith("..")&&!Vh(n)}function Ll(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as ap}from"child_process";import{performance as nt}from"perf_hooks";import{existsSync as we,readFileSync as CR,renameSync as PR,rmSync as TR,unlinkSync as IR,writeFileSync as ER}from"fs";import{dirname as Ci,extname as jR,join as ft,resolve as AR}from"path";import{execFileSync as dv}from"child_process";import{createHash as uv}from"crypto";import{closeSync as pv,copyFileSync as hi,existsSync as ke,mkdirSync as gi,mkdtempSync as mv,openSync as fv,readdirSync as uu,readFileSync as yi,renameSync as pu,rmSync as Je,statSync as gv,writeFileSync as hv}from"fs";import{basename as fi,dirname as B,extname as yv,join as te,resolve as ru}from"path";import{platform as bv}from"os";import Gh from"better-sqlite3";import{execFileSync as Jh}from"child_process";import{existsSync as zh,readdirSync as Kh,readFileSync as Qh}from"fs";import{extname as ni,join as Dl}from"path";function pt(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>ii({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function ii(e){let t=new Set((e.extensions??qo).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!zh(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=kt(e.projectRoot),i=Yh(e.projectRoot,t).filter(o=>!n.isIgnored(o)),r=new Gh(e.dbPath);try{let o=Zh(r,i),s=r.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
|
|
46
|
+
VALUES (?, ?, NULL, ?)`),c=r.transaction(d=>{let u=0;for(let m of d){if(o.has(m))continue;let f=Qh(Dl(e.projectRoot,m),"utf-8"),g=s.run(ey(m),m,f);u+=Number(g.changes)}return u})(i),l={scanned:i.length,inserted:c,existing:i.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${l.existing} already present).`),l}finally{r.close()}}function Yh(e,t){let n=Xh(e,t);if(n)return n;let i=[],r=o=>{let s=o?Dl(e,o):e,a;try{a=Kh(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Vo.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){r(l);continue}t.has(ni(c.name).toLowerCase())&&i.push(l)}};return r(""),i.sort()}function Xh(e,t){try{return Jh("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
|
|
47
|
+
`).filter(i=>i&&t.has(ni(i).toLowerCase())).sort()}catch{return null}}function Zh(e,t){let n=new Set,i=500;for(let r=0;r<t.length;r+=i){let o=t.slice(r,r+i),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 ey(e){return ni(e).toLowerCase()===".vue"?"vue":ni(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as ny}from"crypto";import{appendFileSync as iy,existsSync as Bl,mkdirSync as ry,readFileSync as oy,renameSync as sy,rmSync as kr,statSync as ay}from"fs";import{dirname as ql,join as Fl}from"path";function Rr(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function ri(e,t,n){let i=e.changes.map(a=>a.path).sort();if(i.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:i,affectedFiles:[],reasons:[]};let r=new Set(n),o=Rr(e),s=new Set(o.reasons);return i.some(a=>!r.has(a))&&s.add("changed-file-outside-project"),t===null?(s.add("dependency-graph-unavailable"),Ol(i,r,s)):s.size>0?Ol(i,r,s):{mode:"closure",changedFiles:i,affectedFiles:ty(i,t,r),reasons:[]}}function Ol(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function ty(e,t,n){let i=new Map;for(let[s,a]of t)if(n.has(s))for(let c of a){if(!n.has(c))continue;let l=i.get(c)??new Set;l.add(s),i.set(c,l)}let r=new Set(e),o=[...e];for(let s=0;s<o.length;s+=1){let a=o[s];if(a!==void 0)for(let c of i.get(a)??[])r.has(c)||(r.add(c),o.push(c))}return[...r].sort()}var cy="<global-symbols>";function ly(e){let t=[];for(let n of e.all(`
|
|
48
|
+
SELECT relative_path, language, position_encoding, text
|
|
49
|
+
FROM documents
|
|
50
|
+
`))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
|
|
51
|
+
SELECT d.relative_path,
|
|
52
|
+
c.chunk_index,
|
|
53
|
+
c.start_line,
|
|
54
|
+
c.end_line,
|
|
55
|
+
hex(c.occurrences) AS occurrences_hex
|
|
56
|
+
FROM chunks c
|
|
57
|
+
JOIN documents d ON d.id = c.document_id
|
|
58
|
+
`))t.push({relativePath:n.relative_path,kind:"chunk",values:[n.chunk_index,n.start_line,n.end_line,n.occurrences_hex]});for(let n of e.all(`
|
|
59
|
+
SELECT d.relative_path,
|
|
60
|
+
r.start_line,
|
|
61
|
+
r.start_char,
|
|
62
|
+
r.end_line,
|
|
63
|
+
r.end_char,
|
|
64
|
+
g.symbol,
|
|
65
|
+
g.display_name,
|
|
66
|
+
g.kind,
|
|
67
|
+
g.documentation,
|
|
68
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
69
|
+
g.enclosing_symbol,
|
|
70
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
71
|
+
FROM defn_enclosing_ranges r
|
|
72
|
+
JOIN documents d ON d.id = r.document_id
|
|
73
|
+
JOIN global_symbols g ON g.id = r.symbol_id
|
|
74
|
+
`))t.push({relativePath:n.relative_path,kind:"definition",values:wr(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
|
|
75
|
+
SELECT d.relative_path,
|
|
76
|
+
c.chunk_index,
|
|
77
|
+
m.role,
|
|
78
|
+
g.symbol,
|
|
79
|
+
g.display_name,
|
|
80
|
+
g.kind,
|
|
81
|
+
g.documentation,
|
|
82
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
83
|
+
g.enclosing_symbol,
|
|
84
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
85
|
+
FROM mentions m
|
|
86
|
+
JOIN chunks c ON c.id = m.chunk_id
|
|
87
|
+
JOIN documents d ON d.id = c.document_id
|
|
88
|
+
JOIN global_symbols g ON g.id = m.symbol_id
|
|
89
|
+
`))t.push({relativePath:n.relative_path,kind:"mention",values:wr(n,[n.chunk_index,n.role])});for(let n of e.all(`
|
|
90
|
+
SELECT g.symbol,
|
|
91
|
+
g.display_name,
|
|
92
|
+
g.kind,
|
|
93
|
+
g.documentation,
|
|
94
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
95
|
+
g.enclosing_symbol,
|
|
96
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
97
|
+
FROM global_symbols g
|
|
98
|
+
WHERE NOT EXISTS (
|
|
99
|
+
SELECT 1 FROM defn_enclosing_ranges r WHERE r.symbol_id = g.id
|
|
100
|
+
) AND NOT EXISTS (
|
|
101
|
+
SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
|
|
102
|
+
)
|
|
103
|
+
`))t.push({relativePath:cy,kind:"global-symbol",values:wr(n)});return dy(t)}function dy(e){let t=new Map;for(let i of e){let r=JSON.stringify([i.kind,i.values]),o=t.get(i.relativePath)??[];o.push(r),t.set(i.relativePath,o)}let n=new Map;for(let[i,r]of[...t].sort(([o],[s])=>o.localeCompare(s))){let o=ny("sha256");for(let s of r.sort())o.update(String(Buffer.byteLength(s))),o.update(":"),o.update(s),o.update(`
|
|
104
|
+
`);n.set(i,o.digest("hex"))}return n}function uy(e,t){let n=[],i=[],r=[],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?r.push(a):c!==l?i.push(a):o.push(a)}return{addedFiles:n,modifiedFiles:i,deletedFiles:r,changedFiles:[...n,...i,...r].sort(),unchangedFiles:o}}function $r(e,t,n){let i=new Set(e.affectedFiles),r=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!i.has(c)),s=e.affectedFiles.filter(c=>!r.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 Cr(e,t=hy){let n=t.now();if(!t.databaseExists(e.previousDbPath))return oi(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return oi(e.refreshResult,"candidate-index-unavailable",n,t.now());let i=null,r=null;try{i=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),r=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let o=[...new Set([...t.indexedPaths(i),...t.indexedPaths(r)])].sort(),s=Tn(e.previousSnapshot,e.currentSnapshot),a=new Set(o),c=s.changes.length>0&&!Rr(s).fullProject&&s.changes.every(m=>a.has(m.path)),l=ri(s,c?t.dependencyGraph(i):new Map,o),d=uy(t.factDigests(i),t.factDigests(r)),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:$r(l,d,o.length)}}catch(o){return oi(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{Nl(i),Nl(r)}}function Vl(e,t,n,i=Date.now()){return oi(e,t,i,i,n)}function Wl(e){let t=ql(e);return{latestPath:Fl(t,"affected-shadow-latest.json"),historyPath:Fl(t,"affected-shadow.jsonl")}}function Hl(e,t=n=>oy(n,"utf-8")){let n=Wl(e),i;try{i=JSON.parse(t(n.latestPath))}catch(S){let v=xy(S),w=v?"telemetry-missing":vy(S);return et(n,w,v?void 0:S instanceof Error?S.message:String(S))}if(V(i)&&typeof i.version=="number"&&i.version!==1)return et(n,"unsupported-record-version",`Unsupported version ${i.version}.`);if(!by(i))return et(n,"telemetry-malformed");if(i.status==="unavailable")return Sy(i.reason)?{state:"unavailable",...n,reason:i.reason,recordedAt:i.recordedAt,refreshResult:i.refreshResult,durationMs:i.durationMs,...typeof i.error=="string"?{error:i.error}:{}}:et(n,"telemetry-malformed");if(i.status!=="evaluated")return et(n,"telemetry-malformed");let r=i.plan,o=i.comparison,s=i.evaluation;if(!V(i.manifest)||!V(r)||!V(o)||!V(s))return et(n,"telemetry-malformed");let a=r.mode,c=z(r.affectedFiles),l=z(r.reasons),d=z(o.changedFiles),u=z(s.predictedFiles),m=z(s.actualFiles),f=z(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"||!Ml(g)||!Ml(h))return et(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))?et(n,"telemetry-malformed"):{state:s.passed?"passing":"failing",...n,recordedAt:i.recordedAt,refreshResult:i.refreshResult,durationMs:i.durationMs,mode:a,recall:g,affectedRatio:h,predictedFiles:u,actualFiles:m,missingFiles:f,fallbackReasons:l}}function Ul(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 Gl(e,t,n=yy){let i=Wl(e);return n.appendHistory(i.historyPath,t),n.writeLatest(i.latestPath,t),i}var py=8*1024*1024,my=".previous";function fy(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function gy(e,t,n=py){let i=`${JSON.stringify(fy(t))}
|
|
105
|
+
`,r=Math.max(1,Math.floor(n)),o=`${e}${my}`;if(ry(ql(e),{recursive:!0}),Bl(e)){let s=ay(e).size;s>r?(kr(e,{force:!0}),kr(o,{force:!0})):s+Buffer.byteLength(i)>r&&(kr(o,{force:!0}),sy(e,o))}iy(e,i)}function wr(e,t=[]){let n=[];for(let i of t)n.push(i);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var hy={now:()=>Date.now(),databaseExists:e=>Bl(e),openDatabase:(e,t,n)=>new Ne({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Sn(e),dependencyGraph:e=>Rn(e),factDigests:e=>ly(e)},yy={appendHistory:gy,writeLatest:(e,t)=>vt(e,t,{spacing:2,trailingNewline:!0})};function oi(e,t,n,i,r){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(i).toISOString(),durationMs:Math.max(0,i-n),reason:t,...r?{error:r}:{}}}function Nl(e){try{e?.close()}catch{}}function by(e){return V(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 Sy(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="oracle-error"}function Ml(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function _l(e,t){return e.length===t.length&&e.every((n,i)=>n===t[i])}function et(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function vy(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function xy(e){return e instanceof Error&&e.code==="ENOENT"}import{createHash as Ry}from"crypto";import{copyFileSync as ky,existsSync as Jl,rmSync as zl}from"fs";import{resolve as wy}from"path";import Yl from"better-sqlite3";var $y={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}]},Cy={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 Xl(e){let t=Date.now(),n=Py(e.affectedFiles);if(Ty(e.previousDbPath,e.miniDbPath,e.candidateDbPath),zl(e.candidateDbPath,{force:!0}),!Jl(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Jl(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");Kl(e.previousDbPath,"previous SQLite generation",!1),Kl(e.miniDbPath,"incremental SQLite mini database"),ky(e.previousDbPath,e.candidateDbPath);let i=null;try{i=new Yl(e.candidateDbPath,{fileMustExist:!0}),i.pragma("busy_timeout = 5000"),i.pragma("foreign_keys = ON"),i.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Pr(i,"main","candidate SQLite generation"),Pr(i,"incremental","incremental SQLite mini database"),Iy(i,n),Ey(i,n.length);let r=Tr(i,"main",!0),o=tt(i,"SELECT COUNT(*) AS value FROM main.documents");i.transaction(()=>{jy(i),Ay(i),Ly(i),e.onStage?.("after-delete"),Dy(i),e.onStage?.("after-symbol-reconciliation"),Oy(i),e.onStage?.("after-insert"),Fy(i),Ny(i,n.length,o),e.onStage?.("before-commit")}).immediate(),Zl(i,"main","candidate SQLite generation");let c=[...My(i)].filter(([l,d])=>r.get(l)!==d).map(([l])=>l).sort();return i.exec("DETACH DATABASE incremental"),i.close(),i=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:Date.now()-t}}catch(r){try{i?.close()}finally{zl(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${r instanceof Error?r.message:String(r)}`,{cause:r})}}function Py(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 Ty(e,t,n){let i=[e,t,n].map(r=>wy(r));if(new Set(i).size!==i.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Kl(e,t,n=!0){let i=new Yl(e,{readonly:!0,fileMustExist:!0});try{Pr(i,"main",t),n&&Zl(i,"main",t)}finally{i.close()}}function Pr(e,t,n){for(let[i,r]of Object.entries($y)){let s=e.prepare(`PRAGMA ${t}.table_info('${i}')`).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(r))throw new Error(`${n} schema changed for table ${i}`)}for(let[i,r]of Object.entries(Cy)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(i),s=e.prepare(`PRAGMA ${t}.index_info('${i}')`).all().map(a=>a.name);if(o?.tbl_name!==r.table||JSON.stringify(s)!==JSON.stringify(r.columns))throw new Error(`${n} schema changed for index ${i}`)}Ql(e,t,"documents",["relative_path"],n),Ql(e,t,"global_symbols",["symbol"],n)}function Ql(e,t,n,i,r){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(i)}))throw new Error(`${r} lost the unique ${n}(${i.join(", ")}) constraint`)}function Zl(e,t,n){let i=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(i!=="ok")throw new Error(`${n} failed integrity_check: ${String(i)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function Iy(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(r=>{for(let o of r)n.run(o)})(t)}function Ey(e,t){let n=tt(e,"SELECT COUNT(*) AS value FROM incremental.documents"),i=tt(e,`SELECT COUNT(*) AS value
|
|
106
|
+
FROM main.documents d
|
|
107
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),r=e.prepare(`SELECT p.relative_path
|
|
108
|
+
FROM temp.incremental_affected_paths p
|
|
109
|
+
LEFT JOIN incremental.documents d ON d.relative_path = p.relative_path
|
|
110
|
+
WHERE d.id IS NULL
|
|
111
|
+
LIMIT 1`).pluck().get(),o=e.prepare(`SELECT d.relative_path
|
|
112
|
+
FROM incremental.documents d
|
|
113
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
114
|
+
WHERE p.relative_path IS NULL
|
|
115
|
+
LIMIT 1`).pluck().get();if(n!==t||i!==t||r!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function jy(e){e.exec(`
|
|
116
|
+
CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
117
|
+
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
118
|
+
SELECT g.symbol
|
|
119
|
+
FROM main.defn_enclosing_ranges r
|
|
120
|
+
JOIN main.documents d ON d.id = r.document_id
|
|
121
|
+
JOIN main.global_symbols g ON g.id = r.symbol_id
|
|
122
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path;
|
|
123
|
+
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
124
|
+
SELECT g.symbol
|
|
125
|
+
FROM main.mentions m
|
|
126
|
+
JOIN main.chunks c ON c.id = m.chunk_id
|
|
127
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
128
|
+
JOIN main.global_symbols g ON g.id = m.symbol_id
|
|
129
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
130
|
+
WHERE m.role = 1;
|
|
131
|
+
|
|
132
|
+
CREATE TEMP TABLE incremental_new_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
133
|
+
INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
|
|
134
|
+
SELECT g.symbol
|
|
135
|
+
FROM incremental.defn_enclosing_ranges r
|
|
136
|
+
JOIN incremental.global_symbols g ON g.id = r.symbol_id;
|
|
137
|
+
INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
|
|
138
|
+
SELECT g.symbol
|
|
139
|
+
FROM incremental.mentions m
|
|
140
|
+
JOIN incremental.global_symbols g ON g.id = m.symbol_id
|
|
141
|
+
WHERE m.role = 1;
|
|
142
|
+
`)}function Ay(e){let t=e.prepare(`WITH changed_symbols AS (
|
|
143
|
+
SELECT symbol FROM temp.incremental_old_defined_symbols
|
|
144
|
+
UNION
|
|
145
|
+
SELECT symbol FROM temp.incremental_new_defined_symbols
|
|
146
|
+
), unaffected_definitions AS (
|
|
147
|
+
SELECT g.symbol
|
|
148
|
+
FROM main.defn_enclosing_ranges r
|
|
149
|
+
JOIN main.documents d ON d.id = r.document_id
|
|
150
|
+
JOIN main.global_symbols g ON g.id = r.symbol_id
|
|
151
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
152
|
+
WHERE p.relative_path IS NULL
|
|
153
|
+
UNION
|
|
154
|
+
SELECT g.symbol
|
|
155
|
+
FROM main.mentions m
|
|
156
|
+
JOIN main.chunks c ON c.id = m.chunk_id
|
|
157
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
158
|
+
JOIN main.global_symbols g ON g.id = m.symbol_id
|
|
159
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
160
|
+
WHERE m.role = 1 AND p.relative_path IS NULL
|
|
161
|
+
)
|
|
162
|
+
SELECT u.symbol
|
|
163
|
+
FROM unaffected_definitions u
|
|
164
|
+
JOIN changed_symbols c ON c.symbol = u.symbol
|
|
165
|
+
LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function Ly(e){e.exec(`
|
|
166
|
+
DELETE FROM main.mentions
|
|
167
|
+
WHERE chunk_id IN (
|
|
168
|
+
SELECT c.id
|
|
169
|
+
FROM main.chunks c
|
|
170
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
171
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
172
|
+
);
|
|
173
|
+
DELETE FROM main.chunks
|
|
174
|
+
WHERE document_id IN (
|
|
175
|
+
SELECT d.id
|
|
176
|
+
FROM main.documents d
|
|
177
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
178
|
+
);
|
|
179
|
+
DELETE FROM main.defn_enclosing_ranges
|
|
180
|
+
WHERE document_id IN (
|
|
181
|
+
SELECT d.id
|
|
182
|
+
FROM main.documents d
|
|
183
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
184
|
+
);
|
|
185
|
+
DELETE FROM main.documents
|
|
186
|
+
WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
|
|
187
|
+
`)}function Dy(e){e.exec(`
|
|
188
|
+
UPDATE main.global_symbols
|
|
189
|
+
SET display_name = NULL,
|
|
190
|
+
kind = NULL,
|
|
191
|
+
documentation = NULL,
|
|
192
|
+
signature = NULL,
|
|
193
|
+
enclosing_symbol = NULL,
|
|
194
|
+
relationships = NULL
|
|
195
|
+
WHERE symbol IN (SELECT symbol FROM temp.incremental_old_defined_symbols);
|
|
196
|
+
|
|
197
|
+
INSERT OR IGNORE INTO main.global_symbols(
|
|
198
|
+
symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
|
|
199
|
+
)
|
|
200
|
+
SELECT symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
|
|
201
|
+
FROM incremental.global_symbols;
|
|
202
|
+
|
|
203
|
+
UPDATE main.global_symbols
|
|
204
|
+
SET display_name = (
|
|
205
|
+
SELECT source.display_name FROM incremental.global_symbols source
|
|
206
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
207
|
+
),
|
|
208
|
+
kind = (
|
|
209
|
+
SELECT source.kind FROM incremental.global_symbols source
|
|
210
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
211
|
+
),
|
|
212
|
+
documentation = (
|
|
213
|
+
SELECT source.documentation FROM incremental.global_symbols source
|
|
214
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
215
|
+
),
|
|
216
|
+
signature = (
|
|
217
|
+
SELECT source.signature FROM incremental.global_symbols source
|
|
218
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
219
|
+
),
|
|
220
|
+
enclosing_symbol = (
|
|
221
|
+
SELECT source.enclosing_symbol FROM incremental.global_symbols source
|
|
222
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
223
|
+
),
|
|
224
|
+
relationships = (
|
|
225
|
+
SELECT source.relationships FROM incremental.global_symbols source
|
|
226
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
227
|
+
)
|
|
228
|
+
WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
|
|
229
|
+
`)}function Oy(e){let t=tt(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=tt(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),i=tt(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)
|
|
230
|
+
SELECT id + ?, language, relative_path, position_encoding, text
|
|
231
|
+
FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
|
|
232
|
+
SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
|
|
233
|
+
FROM incremental.chunks`).run(n,t),e.prepare(`INSERT INTO main.mentions(chunk_id, symbol_id, role)
|
|
234
|
+
SELECT m.chunk_id + ?, target.id, m.role
|
|
235
|
+
FROM incremental.mentions m
|
|
236
|
+
JOIN incremental.global_symbols source ON source.id = m.symbol_id
|
|
237
|
+
JOIN main.global_symbols target ON target.symbol = source.symbol`).run(n),e.prepare(`INSERT INTO main.defn_enclosing_ranges(
|
|
238
|
+
id, document_id, symbol_id, start_line, start_char, end_line, end_char
|
|
239
|
+
)
|
|
240
|
+
SELECT r.id + ?, r.document_id + ?, target.id,
|
|
241
|
+
r.start_line, r.start_char, r.end_line, r.end_char
|
|
242
|
+
FROM incremental.defn_enclosing_ranges r
|
|
243
|
+
JOIN incremental.global_symbols source ON source.id = r.symbol_id
|
|
244
|
+
JOIN main.global_symbols target ON target.symbol = source.symbol`).run(i,t)}function Fy(e){e.exec(`
|
|
245
|
+
DELETE FROM main.global_symbols
|
|
246
|
+
WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
|
|
247
|
+
AND NOT EXISTS (
|
|
248
|
+
SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
|
|
249
|
+
);
|
|
250
|
+
`)}function Ny(e,t,n){let i=tt(e,"SELECT COUNT(*) AS value FROM main.documents"),r=tt(e,`SELECT COUNT(*) AS value
|
|
251
|
+
FROM main.documents d
|
|
252
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(i!==n||r!==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 My(e){let t=Tr(e,"main",!0),n=Tr(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 Tr(e,t,n){let i=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",r=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
|
|
253
|
+
FROM ${t}.documents d
|
|
254
|
+
${i}
|
|
255
|
+
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
|
|
256
|
+
FROM ${t}.chunks c
|
|
257
|
+
JOIN ${t}.documents d ON d.id = c.document_id
|
|
258
|
+
${i}
|
|
259
|
+
ORDER BY d.relative_path, c.chunk_index, c.start_line, c.end_line, c.id`).all(),s=e.prepare(`SELECT d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char,
|
|
260
|
+
g.symbol, g.display_name, g.kind, g.documentation,
|
|
261
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature,
|
|
262
|
+
g.enclosing_symbol,
|
|
263
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships
|
|
264
|
+
FROM ${t}.defn_enclosing_ranges r
|
|
265
|
+
JOIN ${t}.documents d ON d.id = r.document_id
|
|
266
|
+
JOIN ${t}.global_symbols g ON g.id = r.symbol_id
|
|
267
|
+
${i}
|
|
268
|
+
ORDER BY d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char, g.symbol`).all(),a=e.prepare(`SELECT d.relative_path, c.chunk_index, m.role, g.symbol
|
|
269
|
+
FROM ${t}.mentions m
|
|
270
|
+
JOIN ${t}.chunks c ON c.id = m.chunk_id
|
|
271
|
+
JOIN ${t}.documents d ON d.id = c.document_id
|
|
272
|
+
JOIN ${t}.global_symbols g ON g.id = m.symbol_id
|
|
273
|
+
${i}
|
|
274
|
+
ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,u]of Object.entries({documents:r,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=Ry("sha256");for(let f of u.sort())m.update(f).update(`
|
|
275
|
+
`);l.set(d,m.digest("hex"))}return l}function tt(e,t){return e.prepare(t).get().value}import{readFileSync as _y,writeFileSync as By}from"fs";function mt(e,t){let n=Date.now(),i=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:Date.now()-n,result:i}}function td(e){let t=e.readFingerprint(),n=qy(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let i=e.compute();return Vy(e.cachePath,e.readFingerprint(),i),i}function qy(e,t){try{let n=JSON.parse(_y(e,"utf-8"));return ed(n.fingerprint)===ed(t)?{result:n.result}:null}catch{return null}}function Vy(e,t,n){By(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
|
|
276
|
+
`)}function ed(e){return JSON.stringify(e)}import{appendFileSync as Wy,existsSync as Hy,mkdirSync as Uy,readFileSync as PT,renameSync as Gy,rmSync as Jy,statSync as id}from"fs";import{dirname as rd,join as zy}from"path";var si="reindex-activity.jsonl",Ky=".previous",Qy=1024*1024,IT=1440*60*1e3,Yy={appendFile:Wy,exists:Hy,mkdir:e=>Uy(e,{recursive:!0}),rename:Gy,remove:e=>Jy(e,{force:!0}),size:e=>id(e).size};function Ir(e){return zy(rd(e),si)}function Xy(e){if(e.reused)return 0;let t=nd(e.indexPath)+nd(e.dbPath);for(let n of e.shards??[])!n.reused&&n.outputBytes!==null&&(t+=n.outputBytes);return t}function Er(e,t){let n=t.lastRefresh;n&&jr(Ir(e),{version:1,event:"run",recordedAt:n.completedAt,trigger:n.trigger,result:n.result,durationMs:n.durationMs,estimatedLogicalOutputBytes:Xy(t)})}function od(e,t){jr(Ir(e),{version:1,event:"run",recordedAt:t.completedAt,trigger:t.trigger,result:"failed",durationMs:t.durationMs,estimatedLogicalOutputBytes:0})}function sd(e,t,n=new Date){jr(Ir(e),{version:1,event:"suppressed",recordedAt:n.toISOString(),trigger:t,reason:"completed-index-is-fresh"})}function Zy(e,t,n=Qy,i=Yy){let r=`${JSON.stringify(t)}
|
|
277
|
+
`,o=Math.max(1,Math.floor(n)),s=`${e}${Ky}`;if(i.mkdir(rd(e)),i.exists(e)){let a=i.size(e);a>o?(i.remove(e),i.remove(s)):a+Buffer.byteLength(r)>o&&(i.remove(s),i.rename(e,s))}i.appendFile(e,r)}function jr(e,t){try{Zy(e,t)}catch{}}function nd(e){try{return id(e).size}catch{return 0}}import{createHash as eb}from"crypto";import{existsSync as Ar,readFileSync as tb,readdirSync as nb}from"fs";import{dirname as Lr,join as ai,relative as ib,resolve as Dr,sep as ad}from"path";function cd(e,t){let n=t.includes("."),i={};for(let o of t)i[o]=[];let r=[];for(let o of e){let s=pd(o.path,t);s?i[s].push(o):n?i["."].push(o):r.push(o)}return{files:i,shared:r}}function ld(e,t){let n=new Map;for(let r of e){let o=t[r]?.packageName;o&&n.set(o,r)}let i=new Map;for(let r of e)i.set(r,new Set);for(let r of e){let o=t[r],s=i.get(r);if(!o||o.parseFailed){for(let a of e)a!==r&&s.add(a);continue}for(let a of o.dependencyNames){let c=n.get(a);c&&c!==r&&s.add(c)}for(let a of[...o.pathsTargets,...o.referencesPaths]){let c=pd(a,e);c&&c!==r&&s.add(c)}}return rb(e,i)}function dd(e,t,n){let i={};for(let r of e){let o=new Map;for(let s of t.files[r]??[])o.set(s.path,s);for(let s of n[r]??[])for(let a of t.files[s]??[])o.set(a.path,a);for(let s of t.shared)o.set(s.path,s);i[r]={files:[...o.values()].sort((s,a)=>s.path.localeCompare(a.path))}}return i}function Or(e){if(e===".")return"root";let t=eb("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function ud(e,t){let n=Dr(e),i={};for(let r of t)i[r]=ob(n,r);return i}function pd(e,t){let n;for(let i of t)i!=="."&&(e===i||e.startsWith(`${i}/`))&&(!n||i.length>n.length)&&(n=i);return n}function rb(e,t){let n={};for(let i of e){let r=new Set,o=[...t.get(i)??[]];for(;o.length>0;){let s=o.pop();if(!(s===i||r.has(s))){r.add(s);for(let a of t.get(s)??[])a!==i&&!r.has(a)&&o.push(a)}}n[i]=[...r].sort((s,a)=>s.localeCompare(a))}return n}function ob(e,t){let n=t==="."?e:ai(e,t),i=sb(n),r=ab(n),o=r?cb(r,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:i.name,dependencyNames:i.dependencyNames,pathsTargets:o.pathsTargets,referencesPaths:o.referencesPaths,parseFailed:i.failed||o.failed}}function sb(e){let t=ai(e,"package.json");if(!Ar(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Fr(t);if(!n.ok)return{name:void 0,dependencyNames:[],failed:!0};let i=typeof n.value.name=="string"?n.value.name:void 0,r=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))r.add(a)}return{name:i,dependencyNames:[...r],failed:!1}}function ab(e){let t=ai(e,"tsconfig.json");if(Ar(t))return t;let n;try{n=nb(e).filter(i=>/^tsconfig.*\.json$/.test(i))}catch{return}return n.sort((i,r)=>i.localeCompare(r)),n.length>0?ai(e,n[0]):void 0}function cb(e,t){let n=Fr(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let i=lb(n.value,e,t),r=md(e,n.value,t,0);return{pathsTargets:r.pathsTargets,referencesPaths:i,failed:r.failed}}function lb(e,t,n){let i=e.references;if(!Array.isArray(i))return[];let r=Lr(t),o=new Set;for(let s of i){if(!s||typeof s!="object")continue;let a=s.path;if(typeof a!="string"||a.trim()==="")continue;let c=fd(a,r,n);c&&o.add(c)}return[...o]}function md(e,t,n,i){let r=db(t);if(r)return{pathsTargets:ub(r,Lr(e),n),failed:!1};if(i>=5)return{pathsTargets:[],failed:!1};let o=pb(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let s=Fr(o);return s.ok?md(o,s.value,n,i+1):{pathsTargets:[],failed:!0}}function db(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 ub(e,t,n){let i=new Set;for(let r of Object.values(e))if(Array.isArray(r))for(let o of r){if(typeof o!="string")continue;let s=fd(o,t,n);s&&i.add(s)}return[...i]}function pb(e,t,n){let i=Array.isArray(e)?e.at(-1):e;if(typeof i!="string"||i.trim()===""||!i.startsWith(".")&&!i.startsWith("/"))return;let r=Dr(Lr(t),i);if(r.endsWith(".json")||(r=`${r}.json`),!r.split(ad).includes("node_modules")&&me(n,r)&&Ar(r))return r}function fd(e,t,n){let i=e.replace(/\/?\*+$/,""),r=Dr(t,i===""?".":i);if(!me(n,r))return;let s=ib(n,r).split(ad).join("/");return s===""?".":s}function mb(e){let t="",n=0,i=!1,r=e.length;for(;n<r;){let o=e[n];if(i){if(t+=o,o==="\\"&&n+1<r){t+=e[n+1],n+=2;continue}o==='"'&&(i=!1),n+=1;continue}if(o==='"'){i=!0,t+=o,n+=1;continue}if(o==="/"&&e[n+1]==="/"){for(n+=2;n<r&&e[n]!==`
|
|
278
|
+
`;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<r&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function Fr(e){try{let t=tb(e,"utf-8"),n=JSON.parse(mb(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{existsSync as fb,readFileSync as gb,readdirSync as hb,statSync as yb}from"fs";import ie from"path";var bb=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function rn(e,t=[]){let n=ie.resolve(e),i=t.flatMap(c=>vb(n,c));if(i.length>0)return gd(n,hd(i));let r=Sb(n),o=hd(r),s=Rb(n,o)?[n,...o]:o,a=s.length>0?s:[n];return gd(n,a)}function gd(e,t){return[...new Set(t.map(n=>wb(e,n)))].sort((n,i)=>n.localeCompare(i))}function Sb(e){let t=[],n=[e];for(;n.length>0;){let i=n.pop(),r;try{r=hb(i,{withFileTypes:!0})}catch{continue}for(let o of r){let s=ie.join(i,o.name);if(o.isDirectory()){!bb.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&xb(s)&&t.push(ie.dirname(s))}}return t}function vb(e,t){let n=t.trim();if(!n)return[];let i=ie.resolve(e,n);if(!me(e,i))return[];try{let r=yb(i);if(r.isDirectory())return[i];if(r.isFile()&&yd(ie.basename(i)))return[ie.dirname(i)]}catch{return[]}return[]}function xb(e){if(!yd(ie.basename(e)))return!1;let t=bd(e);return t?ie.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function yd(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function hd(e){let t=[...new Set(e.map(n=>ie.resolve(n)))].sort((n,i)=>n.localeCompare(i));return t.length<=1?t:t.filter(n=>!t.some(i=>i!==n&&$b(n,i)))}function Rb(e,t){if(t.length===0||t.some(i=>ie.resolve(i)===e))return!1;let n=ie.join(e,"tsconfig.json");return fb(n)&&kb(n)}function kb(e){let n=bd(e)?.include;return Array.isArray(n)?n.some(i=>typeof i=="string"&&i.trim()!==""&&!i.startsWith("!")&&(i.includes("/")||i.includes("**")||!ie.extname(i))):!1}function bd(e){try{let t=JSON.parse(gb(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function wb(e,t){let n=ie.relative(e,t);return n?n.split(ie.sep).join("/"):"."}function $b(e,t){let n=ie.relative(e,t);return!!n&&!n.startsWith("..")&&!ie.isAbsolute(n)}import{createHash as Gb}from"crypto";import{existsSync as Mr,readFileSync as jd,statSync as Jb,writeFileSync as _r}from"fs";import{join as zb}from"path";import{readFileSync as Sd}from"fs";import{createRequire as Cb}from"module";import{dirname as Pb,isAbsolute as WT,relative as HT,resolve as UT,sep as GT}from"path";var vd=Cb(import.meta.url),Tb=1,xd="0.4.0";function Nr(){let e=Ib();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Ib(){try{let e=vd.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(Sd(e,"utf8"));if(t.version!==xd)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${xd}`};let n=Pb(e),i=vd.resolve("typescript/package.json",{paths:[n]}),r=JSON.parse(Sd(i,"utf8"));return typeof r.version!="string"||!r.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:r.version,producerIdentity:Eb(t.version,r.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Eb(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Tb}`}import{createHash as jb}from"crypto";import{readFileSync as Ab}from"fs";import{dirname as Lb,join as ci}from"path";var li=2,Db="typescript-index";function Rd(e){let t=ci(e,Db);return{rootDir:t,requestDir:ci(t,"requests"),responseDir:ci(t,"responses")}}function kd(e){try{let t=JSON.parse(Ab(ci(Lb(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:jb("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 Ob}from"crypto";import{existsSync as Fb,mkdirSync as wd,readFileSync as Nb,rmSync as $d}from"fs";import{resolve as Cd}from"path";var Mb=12e4,_b=5,di=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=ls(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Hb(),this.runtime=n.runtime??Ub}request(t){let n=jn(this.cacheDir),i=Rd(this.cacheDir),r=Hi(n.statePath);if(!Pd(r,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),s=Cd(i.requestDir,`${o}.json`),a=Cd(i.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;wd(i.requestDir,{recursive:!0}),wd(i.responseDir,{recursive:!0}),vt(s,{protocolVersion:li,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(Fb(a))return Bb(Nb(a,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=Hi(n.statePath);if(!Pd(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(_b)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{$d(s,{force:!0}),$d(a,{force:!0})}}};function Pd(e,t,n){let i=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=os,r=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===li&&n.isProcessAlive(e.pid)&&(i||r)}function Bb(e,t,n,i,r){let o=JSON.parse(e);if(o.protocolVersion!==li||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=qb(o.response,i),a=[...new Set(r)].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 qb(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 i=new Set,r=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(Vb)||i.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");i.add(o.relativePath);let s=o.bytesBase64===null?null:Wb(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:r}}function Vb(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 Wb(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Hb(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Mb}var Ub={now:Date.now,randomId:Ob,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:St};function Kb(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=Tn(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"||!Gt(l.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let i=ri(n,e.graph,e.projectFiles);if(i.mode!=="closure"||i.affectedFiles.length===0)return{eligible:!1,reason:i.reasons.length>0?`affected set widened: ${i.reasons.join(", ")}`:"empty affected set"};let r=Qb([...i.changedFiles,...i.affectedFiles],t);if(!r)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=Td(e.currentSnapshot,e.projectFiles,e.producerIdentity),s=Td(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==s)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let a=Ed(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!a)return{eligible:!1,reason:"prior document identity unavailable"};let c=Ed(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,i.affectedFiles);return c?{eligible:!0,manifest:n,plan:i,projectIdentity:o,previousFragmentGeneration:Id(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Id(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:a,nextDocumentIdentities:c,tsconfigPath:r==="."?"tsconfig.json":`${r}/tsconfig.json`,projectArgument:r}:{eligible:!1,reason:"next document identity unavailable"}}function Qb(e,t){let n=null;for(let i of e){let r=t.filter(o=>o==="."||i===o||i.startsWith(`${o}/`));if(r.length!==1||n!==null&&n!==r[0])return null;n=r[0]}return n}function Ad(e){let t=Date.now();try{if(!Mr(e.previousDbPath)||!Mr(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),i=Nr();if(!i.available)throw new Error(i.reason);let r=performance.now()-n;n=performance.now();let o=new Ne({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),s,a;try{s=Sn(o,{includeIgnored:!1}).filter(Gt).sort(),a=Rn(o)}finally{o.close()}let c=performance.now()-n,l=Kb({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?rn(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:s,graph:a,producerIdentity:i.producerIdentity,rootTsconfigExists:Mr(zb(e.projectRoot,"tsconfig.json"))});if(!l.eligible)throw new Error(l.reason);let d=kd(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let m=new di({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:l.tsconfigPath,projectArgument:l.projectArgument,projectIdentity:l.projectIdentity,producerIdentity:i.producerIdentity,modifiedFiles:l.plan.changedFiles,affectedFiles:l.plan.affectedFiles}),f=performance.now()-n,g=Jb(e.previousShardPath).size>=ec;n=performance.now();let h=g?null:jd(e.previousShardPath),y=g?{completeIndexBytes:null,affectedIndexBytes:Qa(m.fragments)}:Za({packageVersion:i.packageVersion,baseIndexBytes:h,fragments:m.fragments}),S=performance.now()-n;n=performance.now(),g?tc({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,nextGenerationIdentity:l.nextFragmentGeneration,producerIdentity:i.producerIdentity,projectIdentity:l.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:m.fragments}):(Ya({cacheDir:e.cacheDir,packageVersion:i.packageVersion,indexBytes:h,producerIdentity:i.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.previousFragmentGeneration,documentIdentities:l.previousDocumentIdentities,allowUntrackedDocuments:!0}),Xa({cacheDir:e.cacheDir,previousGenerationIdentity:l.previousFragmentGeneration,producerIdentity:i.producerIdentity,projectIdentity:l.projectIdentity,generationIdentity:l.nextFragmentGeneration,fragments:m.fragments,documentIdentities:l.nextDocumentIdentities}));let v=performance.now()-n;n=performance.now(),y.completeIndexBytes&&_r(e.candidateShardPath,y.completeIndexBytes),_r(e.candidateAffectedScipPath,y.affectedIndexBytes);let w=performance.now()-n,k={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:i.producerIdentity,previousFragmentGeneration:l.previousFragmentGeneration,nextFragmentGeneration:l.nextFragmentGeneration,manifest:l.manifest,plan:l.plan,projectFileCount:s.length,referenceFragmentsByFile:new Map(m.fragments.map(O=>[O.relativePath,O.referenceFragments])),timings:{runtimeMs:r,graphMs:c,requestMs:f,serviceMs:m.durationMs,assemblyMs:S,fragmentStoreMs:v,writeMs:w}};return e.onStatus(`Incremental TypeScript index emitted ${k.affectedFiles.length} affected document(s) in ${(k.durationMs/1e3).toFixed(3)}s (${k.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${r.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${f.toFixed(0)}ms, assembly ${S.toFixed(0)}ms, fragments ${v.toFixed(0)}ms, write ${w.toFixed(0)}ms).`),k}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 Ld(e){let t=Nr();if(!t.available)throw new Error(t.reason);let n=nc({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:jd(e.baseShardPath),packageVersion:t.packageVersion});_r(e.candidateShardPath,n)}function Td(e,t,n){let i=e.files.filter(r=>ts(r.path,e.languages)!=="source").map(r=>({path:r.path,size:r.size,hash:r.hash})).sort((r,o)=>r.path.localeCompare(o.path));return Br(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:i}))}function Id(e,t){return Br(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function Ed(e,t,n,i,r){let o=new Set(e.files.map(c=>c.path)),s=gs({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:i}),a=new Map;for(let c of r){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,Br(JSON.stringify({version:1,producerIdentity:i,generatedDocument:c})))}return a}function Br(e){return Gb("sha256").update(e).digest("hex")}import{execFile as Yb}from"child_process";import{existsSync as ui,renameSync as Vr,rmSync as Wr,statSync as Xb}from"fs";import{cpus as Zb}from"os";import{join as Dd}from"path";function eS(e,t,n){if(!e.defaultOutputPath)return;let i=Dd(t,e.defaultOutputPath);n!==i&&ui(i)&&Vr(i,n)}function tS(e,t,n){if(!e.defaultOutputPath)return null;let i=Dd(t,e.defaultOutputPath);if(i===n)return null;let r=`${n}.default-output-backup`;return Wr(r,{force:!0}),ui(i)?(Vr(i,r),{defaultOutputPath:i,backupPath:r}):{defaultOutputPath:i,backupPath:null}}function nS(e){e&&(Wr(e.defaultOutputPath,{force:!0}),e.backupPath&&ui(e.backupPath)&&Vr(e.backupPath,e.defaultOutputPath))}function iS(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),i=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,Zb().length));return Math.max(1,Math.min(e,Math.floor(i)))}async function Od(e,t,n,i){let r=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=iS(o.length,i),c=await oS(o,a,l=>qr(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 qr(u,t,n)))}s.push(...c.map(d=>l.get(d.id)??d))}else s.push(...c);for(let l of r)s.push(await qr(l,t,n));return s.sort((l,d)=>e.findIndex(u=>u.id===l.id)-e.findIndex(u=>u.id===d.id))}async function qr(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Wr(e.scipPath,{force:!0});let i=tS(e.config,t,e.scipPath),r=[e.binary,...e.args].join(" "),o=Date.now();try{let a=Qo(e.binary,e.args);await rS(a.binary,a.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),eS(e.config,t,e.scipPath)}catch(a){let c=a instanceof Error?a.message:String(a),l=`${e.resolvedBinary} indexer failed: ${c.split(`
|
|
279
|
+
`)[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:r,skipped:{language:e.language,reason:d}}}finally{nS(i)}if(!ui(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:r,skipped:{language:e.language,reason:c}}}let s;try{s=Xb(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:r,outputBytes:s}}function rS(e,t,n){return new Promise((i,r)=>{Yb(e,[...t],n,o=>{o?r(o):i()})})}async function oS(e,t,n){if(e.length===0)return[];let i=new Array(e.length),r=0,o=Math.max(1,Math.min(e.length,t)),s=Array.from({length:o},async()=>{for(;r<e.length;){let a=r++;i[a]=await n(e[a])}});return await Promise.all(s),i}import{execFileSync as sS}from"child_process";import{platform as aS}from"os";function pi(e,t){let n=e.installMethods,i=$n(e);if(!n?.length)return t(`No auto-install method available for ${i}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let r of n)if(Qe(r.prerequisite)){t(`Installing ${i} via ${r.label}...`);try{sS(r.binary,r.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:aS()==="win32"});let o=Cn(e);if(o){let s=o===e.indexerBinary?"":` (using ${o})`;return t(`Successfully installed ${i} via ${r.label}${s}`),!0}t(`${r.label} command completed but ${i} was not found on PATH`)}catch(o){let s=o instanceof Error?o.message:String(o);t(`${r.label} install failed: ${s}`)}}return t(`Could not auto-install ${i}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}import VS from"better-sqlite3";import{existsSync as WS}from"fs";import{dirname as HS,join as US,resolve as GS}from"path";import{readFileSync as lS,rmSync as dS,statSync as uS,mkdtempSync as pS}from"fs";import{tmpdir as mS}from"os";import{join as Hr}from"path";import{Worker as fS}from"worker_threads";function cS(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Dt(){return{skippedReferences:0,skippedReferenceReasons:cS(),skippedReferenceSamples:[]}}function mi(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let i of t.skippedReferenceSamples.filter(r=>r.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===i.sourceFile).length<2&&e.skippedReferenceSamples.push(i)}}function Fd(e){return e.length>=8&&Md(e.length)>1}function Nd(e){let t=Md(e.vueFiles.length),n=hS(e.vueFiles),i=bS(n,t),r=new URL("./augment-vue-worker.js",import.meta.url),o=pS(Hr(mS(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=gS(),l=Date.now();try{for(let m=0;m<i.length;m++)new fS(r,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:i[m],resultPath:Hr(o,`${m}.json`),sharedBuffer:s}});for(;Atomics.load(a,0)<i.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=i.map((m,f)=>{let g=JSON.parse(lS(Hr(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),...Dt()};for(let m of d)mi(u,m);return u}finally{dS(o,{recursive:!0,force:!0})}}function Md(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 gS(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function hS(e){let t=yS(),n=[];for(let i of e){let r=_d(i),o=Math.max(1,Math.ceil(r/t));for(let s=0;s<o;s++)n.push({fileName:i,startOffset:Math.floor(r*s/o),endOffset:s===o-1?Number.POSITIVE_INFINITY:Math.floor(r*(s+1)/o),countFileSkip:s===0})}return n}function yS(){return Number.POSITIVE_INFINITY}function bS(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),i=e.map(r=>({task:r,weight:SS(r)})).sort((r,o)=>o.weight-r.weight);for(let r of i){let o=n.reduce((s,a)=>a.weight<s.weight?a:s);o.tasks.push(r.task),o.weight+=r.weight}return n.map(r=>r.tasks).filter(r=>r.length>0)}function SS(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,_d(e.fileName)-e.startOffset)}function _d(e){try{return uS(e).size}catch{return 1}}import{createRequire as vS}from"module";import{existsSync as xS,readFileSync as Gr}from"fs";import{dirname as Bd,extname as RS,join as qd,relative as kS,resolve as wS}from"path";import{pathToFileURL as $S}from"url";function CS(e){e.transaction(()=>{e.prepare(`
|
|
280
|
+
DELETE FROM mentions
|
|
281
|
+
WHERE chunk_id IN (
|
|
282
|
+
SELECT c.id
|
|
283
|
+
FROM chunks c
|
|
284
|
+
JOIN documents d ON d.id = c.document_id
|
|
285
|
+
WHERE d.language = 'vue' OR d.relative_path LIKE '%.vue'
|
|
286
|
+
)
|
|
287
|
+
`).run(),e.prepare(`
|
|
288
|
+
DELETE FROM chunks
|
|
289
|
+
WHERE document_id IN (
|
|
290
|
+
SELECT id
|
|
291
|
+
FROM documents
|
|
292
|
+
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
293
|
+
)
|
|
294
|
+
`).run()})()}function Vd(e,t){return e.prepare(`
|
|
295
|
+
SELECT relative_path AS relativePath
|
|
296
|
+
FROM documents
|
|
297
|
+
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
298
|
+
ORDER BY relative_path
|
|
299
|
+
`).all().map(i=>wS(t,i.relativePath))}function Wd(e,t){let{vueCore:n,ts:i,volarTs:r}=PS(e),{parsed:o,vueOptions:s}=TS(n,i,t),a=Bd(t),c=n.createVueLanguagePlugin(i,o.options,s,f=>f),l=IS(n,i,c),d=ES(a,o),{languageServiceHost:u}=r.createLanguageServiceHost(i,i.sys,l,f=>f,d),m=i.createLanguageService(u);return{ts:i,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function PS(e){let t=vS($S(qd(e,"package.json")).href);return{vueCore:Ur(t,"@vue/language-core",e),ts:Ur(t,"typescript",e),volarTs:Ur(t,"@volar/typescript",e)}}function TS(e,t,n){let i=t.readConfigFile(n,t.sys.readFile);if(i.error||!i.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(i.config,t.sys,Bd(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function IS(e,t,n){let i={},r=e.createLanguage([n],new Map,o=>{if(!xS(o))return;let s=Gr(o,"utf-8");i.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??FS(o))});return i.current=r,r}function ES(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Ur(e,t,n){try{return e(t)}catch(i){throw(typeof i=="object"&&i!==null&&"code"in i?i.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:i}):i}}function Hd(e,t,n){let i=jS(e);return r=>{if(!r.name)return null;let o=Ue(t,r.fileName),s=n.get(r.fileName);if(!s)return null;let a=n.positionAt(s,r.textSpan.start),c=i.get(o);if(!c)return null;let l=c.starts.find(u=>u.line===a.line&&u.displayName===r.name);if(l)return l.symbolId;let d=c.containingByLine.get(a.line);return d&&d.displayName===r.name?d.symbolId:AS(c.starts,a.line,2,r.name)}}function jS(e){let t=e.prepare(`
|
|
300
|
+
SELECT
|
|
301
|
+
d.relative_path AS relativePath,
|
|
302
|
+
der.start_line AS startLine,
|
|
303
|
+
der.end_line AS endLine,
|
|
304
|
+
der.symbol_id AS symbolId,
|
|
305
|
+
gs.display_name AS displayName
|
|
306
|
+
FROM defn_enclosing_ranges der
|
|
307
|
+
JOIN documents d ON d.id = der.document_id
|
|
308
|
+
JOIN global_symbols gs ON gs.id = der.symbol_id
|
|
309
|
+
ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
|
|
310
|
+
`).all(),n=new Map;for(let i of t){let r=n.get(i.relativePath);r||(r={containingByLine:new Map,starts:[]},n.set(i.relativePath,r)),r.starts.push({line:i.startLine,symbolId:i.symbolId,displayName:i.displayName});for(let o=i.startLine;o<=i.endLine;o++)r.containingByLine.set(o,{symbolId:i.symbolId,displayName:i.displayName})}for(let i of n.values())i.starts.sort((r,o)=>r.line-o.line);return n}function AS(e,t,n,i){let r=0,o=e.length-1;for(;r<=o;){let a=Math.floor((r+o)/2);e[a].line<t?r=a+1:o=a-1}let s=null;for(let a of[o,r]){let c=e[a];if(!c||c.displayName!==i)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 Ud(e,t,n){let i=_S(t),r=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
|
|
311
|
+
INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
|
|
312
|
+
VALUES (?, ?, ?, ?)
|
|
313
|
+
`),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let d=Ue(t,l),u=eu(i.name,i.version,d);o.run(u,"default",7,`Vue component|${d}`);let m=BS(r,i,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Gd(e,t,n,i,r){return e.transaction(()=>(CS(e),LS(e,t,n,i),DS(e,r)))()}function LS(e,t,n,i){let r=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
|
|
314
|
+
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
315
|
+
VALUES (?, ?, ?, ?, X'00')
|
|
316
|
+
`),s=e.prepare(`
|
|
317
|
+
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
318
|
+
VALUES (?, ?, 1)
|
|
319
|
+
`);for(let a of n){let c=i.get(a);if(!c)continue;let l=Ue(t,a),d=r.get(l);if(!d)continue;let u=o.run(d.id,-1,0,0);s.run(Number(u.lastInsertRowid),c)}}function Jd(e,t,n,i,r){if(e.fileName.endsWith(".vue")){let o=i.language.scripts.get(e.fileName),s=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&s){let a=i.language.maps.get(s,o);if(Jr(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(r)?n.get(e.fileName):null}return t(e)}function zd(e){let t=new Set,n=[];for(let i of e){let r=Kd(i);t.has(r)||(t.add(r),n.push(i))}return n}function Kd(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function DS(e,t){let n=MS(e,[...new Set(t.map(c=>c.sourceFile))]),i=e.prepare(`
|
|
320
|
+
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
321
|
+
VALUES (?, ?, ?, ?, X'00')
|
|
322
|
+
`),r=e.prepare(`
|
|
323
|
+
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
324
|
+
VALUES (?, ?, 0)
|
|
325
|
+
`),o=new Set,s=0,a=0;for(let c of t){let l=Kd(c);if(o.has(l))continue;o.add(l);let d=n.get(c.sourceFile);if(!d)continue;let u=i.run(d,a++,c.sourceLine,c.sourceLine),m=r.run(Number(u.lastInsertRowid),c.symbolId);s+=Number(m.changes)}return s}function*Qd(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"]),i;for(;i=t.exec(e);){let r=i[0];n.has(r)||(yield{text:r,start:i.index,end:i.index+r.length})}}function Yd(e,t){for(let[n]of e.toGeneratedLocation(t,i=>!!i.navigation))return n;return null}function Jr(e,t){let n=e;for(let[i]of n.toSourceLocation(t,r=>!!r.navigation))return i;return null}function OS(e,t){let n=0,i=e.lineStarts.length-1;for(;n<=i;){let o=Math.floor((n+i)/2);e.lineStarts[o]<=t?n=o+1:i=o-1}let r=Math.max(0,i);return{line:r,character:t-e.lineStarts[r]}}function Xd(e,t){return Ue(e,t).startsWith("node_modules/")}function Ue(e,t){return kS(e,t).replaceAll("\\","/")}function FS(e){switch(RS(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 Zd(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Gr(t,"utf-8"),i={text:n,lineStarts:NS(n)};return e.set(t,i),i}catch{return e.set(t,null),null}},positionAt:OS}}function NS(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function MS(e,t){let n=new Map,i=500;for(let r=0;r<t.length;r+=i){let o=t.slice(r,r+i),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 _S(e){try{let t=JSON.parse(Gr(qd(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 BS(e,t,n,i){let r=Ue(n,i),o=eu(t.name,t.version,r);return e.get(o)?.id??null}function eu(e,t,n){let i=n.split("/").map(r=>`\`${r.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${i}/default.`}function nu(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>JS({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Qr(e){return mt(pt(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),mt(nu({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function JS(e){let t=GS(e.projectRoot,e.tsconfig);if(!WS(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new VS(e.dbPath);try{let i=Vd(n,e.projectRoot),r=US(HS(e.dbPath),"augment-vue-meta.json");return td({cachePath:r,readFingerprint:()=>QS(n,e.projectRoot,e.tsconfig),compute:()=>zS({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:i,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function zS(e){let t=Ud(e.db,e.projectRoot,e.vueFiles),n=KS(e,t),i=zd(n.occurrences),r=Gd(e.db,e.projectRoot,e.vueFiles,t,i),o={vueFiles:e.vueFiles.length,resolvedReferences:i.length,resolvedReferenceSamples:ov(e.db,i,20),insertedMentions:r,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:rv(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function KS(e,t){if(Fd(e.vueFiles))return Nd({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=YS({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return XS({...n,vueFiles:n.context.fileNames.filter(i=>i.endsWith(".vue"))})}function QS(e,t,n){let i=e.prepare(`
|
|
326
|
+
SELECT
|
|
327
|
+
(SELECT COUNT(*) FROM documents) AS documents,
|
|
328
|
+
(SELECT COUNT(*) FROM global_symbols) AS symbols,
|
|
329
|
+
(SELECT COUNT(*) FROM chunks) AS chunks,
|
|
330
|
+
(SELECT COUNT(*) FROM mentions) AS mentions,
|
|
331
|
+
(SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
|
|
332
|
+
(SELECT MAX(id) FROM chunks) AS maxChunkId,
|
|
333
|
+
(SELECT MAX(id) FROM global_symbols) AS maxSymbolId
|
|
334
|
+
`).get();return{version:3,tsconfig:n,files:In(t),db:i}}function YS(e){let t=Zd();return{projectRoot:e.projectRoot,context:Wd(e.projectRoot,e.configPath),symbolLookup:Hd(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function XS(e){let t=[],n=Dt(),i=e.tasks??e.vueFiles.map(r=>({fileName:r,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let r of i){let o=ZS(e,r);t.push(...o.occurrences),mi(n,o)}return{occurrences:t,...n}}function ZS(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return tu(e.projectRoot,t,"missing-source-file");let i=e.context.language.scripts.get(t.fileName),r=i?.generated?.languagePlugin.typescript?.getServiceScript(i.generated.root)?.code;if(!i||!r)return tu(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(r,i),s=Ue(e.projectRoot,t.fileName),a=[...Qd(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:av(a),processedStarts:new Set};return ev({...e,fileName:t.fileName,sourceInfo:n,sourceFile:s,map:o,tokenContext:c})}function ev(e){let t=[],n=Dt();for(let i of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(i.start)||tv(e.sourceInfo.text,i.start))continue;let r=Yd(e.map,i.start);if(r===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,r+1)??[]).find(d=>!Xd(e.projectRoot,d.fileName));if(!s){zr(n,e.sourceReader,e.sourceInfo,e.sourceFile,i,"no-definition");continue}let a=Ue(e.projectRoot,s.fileName),c=nv(e.sourceFile,i.text,a);if(c){zr(n,e.sourceReader,e.sourceInfo,e.sourceFile,i,c);continue}let l=Jd(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(l===null){zr(n,e.sourceReader,e.sourceInfo,e.sourceFile,i,"unindexed-definition");continue}iu(t,e.sourceReader,e.sourceInfo,e.sourceFile,i,a,l),e.tokenContext.processedStarts.add(i.start),sv(t,e,i,r,a,l)}return{occurrences:t,...n}}function tv(e,t){let n=e.lastIndexOf(`
|
|
335
|
+
`,t-1)+1,i=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(i)||/\bimport\s*\(\s*['"][^'"]*$/.test(i)}function nv(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function tu(e,t,n){let i=Dt();return t.countFileSkip&&(i.skippedReferences=1,i.skippedReferenceReasons[n]=1,i.skippedReferenceSamples.push({sourceFile:Ue(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...i}}function zr(e,t,n,i,r,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(a=>a.reason===o&&a.sourceFile===i).length>=2)return;let s=t.positionAt(n,r.start);e.skippedReferenceSamples.push({sourceFile:i,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+r.text.length,token:r.text,reason:o})}function Kr(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 i=[...n.keys()].sort(),r=[];for(let o=0;r.length<t;o++){let s=!1;for(let a of i){let c=n.get(a)?.[o];if(c&&(r.push(c),s=!0,r.length===t))break}if(!s)break}return r}function iv(e,t){let n=Kr(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),i=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),r=Kr(e.filter(o=>!i.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...r]}function rv(e,t){let n=[...new Set(e.map(r=>r.reason))].sort(),i=[];for(let[r,o]of n.entries()){let s=n.length-r,a=Math.ceil((t-i.length)/s);i.push(...Kr(e.filter(c=>c.reason===o),a))}return i.slice(0,t)}function ov(e,t,n){let i=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return iv(t,n).map(({symbolId:r,...o})=>({...o,definitionSymbol:i.get(r)?.symbol??`symbol-id:${r}`}))}function sv(e,t,n,i,r,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of cv(t.context.languageService,t.fileName,i+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(s))continue;let a=t.tokenContext.tokenByStart.get(s);a&&(iu(e,t.sourceReader,t.sourceInfo,t.sourceFile,a,r,o),t.tokenContext.processedStarts.add(s))}}function iu(e,t,n,i,r,o,s){let a=t.positionAt(n,r.start);e.push({sourceFile:i,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+r.text.length,sourceToken:r.text,definitionFile:o,symbolId:s})}function av(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function cv(e,t,n,i,r,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=lv(i,l.textSpan.start,o,r.text);d!==null&&a.push(d)}return a}function lv(e,t,n,i){let r=n.get(t);if(r?.text===i)return r.start;let o=Jr(e,t);if(o===null)return null;let s=n.get(o);return s?.text===i?s.start:null}async function Ot(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:i=console.log,skipAutoInstall:r=!1}=e,o=vv(e),s=Date.now();gi(B(o.outputScip),{recursive:!0}),gi(B(o.outputDb),{recursive:!0});let a=e.languages??ot(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.");i(`Detected languages: ${a.join(", ")}`);let c=qt("reindex.fingerprint",()=>rs(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:a.length}),l,d;if(e.skipIfUnchanged!==!1&&!ac(t,o.outputDb)&&ru(o.outputScip)===ru(te(B(o.outputDb),"index.scip"))){let g=rt(t);if(l=g?On(g,c):void 0,l){let h=Fn(l);if(h){if(!Sv(o,c))try{Ji({snapshot:l,manifest:h,targetCacheDir:B(o.outputDb),targetProjectRoot:t}),i(`Attached shared generation ${l.generationId.slice(0,12)}`)}catch(y){i(`Shared generation attach failed; continuing locally: ${sn(y)}`)}}else{let y=await dc(l);if(y.kind==="owner")d=y.release;else if(y.kind==="generation-ready"){let S=Fn(l);if(S)try{Ji({snapshot:l,manifest:S,targetCacheDir:B(o.outputDb),targetProjectRoot:t,action:"waited"}),i(`Attached shared generation ${l.generationId.slice(0,12)} after waiting`)}catch(v){i(`Shared generation attach failed after waiting; continuing locally: ${sn(v)}`)}}else i("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let u=Ka(te(B(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!u)throw d?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${B(o.outputDb)}.`);let m;try{m=await Vt("reindex.lock",()=>Jv(te(B(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:i}),{languages:a.length})}catch(g){throw u.release(),d?.(),g}let f=null;try{let g=wv(B(o.outputDb));g.removed>0&&i(`Removed ${g.removed} abandoned reindex workspace(s)`);for(let k of g.errors)i(`Could not remove abandoned reindex workspace: ${k}`);let h=null,y=qt("reindex.reuse-check",()=>(h=xv({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:i}),h),()=>({languages:a.length,reused:h!==null}));if(y)return ou({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:i}),Er(o.outputDb,y),y;await Vt("reindex.scip-cli-ready",()=>_v(r,i));let S=kv(o);f=S.runDir;let v,w=await Vt("reindex.fresh",async()=>(v=await $v({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:S,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:r,onStatus:i}),v),()=>({languages:a.length,reused:v?.reused,skipped:v?.skipped.length}));return ou({snapshot:l,paths:o,projectRoot:t,fingerprint:c,onStatus:i}),Er(o.outputDb,w),w}catch(g){let h=Si({trigger:e.trigger,result:"failed",start:s,error:g instanceof Error?g.message:String(g)});throw Ru(o.metaPath,h),od(o.outputDb,h),g}finally{f&&Je(f,{recursive:!0,force:!0}),m(),u.release(),d?.()}}function ou(e){if(e.snapshot){if(Fn(e.snapshot)){zi(e.snapshot,B(e.paths.outputDb),"local-fresh");return}try{let t=rt(e.projectRoot),n=t?On(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}lc({snapshot:e.snapshot,sourceCacheDir:B(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=rt(e.projectRoot);return(i?On(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),zi(e.snapshot,B(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: ${sn(t)}`)}}}function Sv(e,t){if(!ke(e.outputScip)||!ke(e.outputDb)||!xu(e.metaPath,t))return!1;let n=st(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function sn(e){return e instanceof Error?e.message:String(e)}function vv(e){let t=e.outputScip??te(e.projectRoot,"index.scip"),n=e.outputDb??te(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:te(B(n),"meta.json")}}function xv(e){let t=st(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!ke(e.paths.outputScip)||!ke(e.paths.outputDb)||!xu(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;mt(pt(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,i=Si({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return Ru(e.paths.metaPath,i),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:i,shards:Rv(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Rv(e,t,n,i){let r=Su(t,n,i);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:on(r[o]),outputBytes:an(Zr(e.outputDb,o)),durationMs:0}))}function kv(e){let t=mv(te(B(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:te(t,fi(e.outputScip)),tempOutputDb:te(t,fi(e.outputDb)),tempMetaPath:te(t,fi(e.metaPath))}}function wv(e){let t=[],n;try{n=uu(e,{withFileTypes:!0})}catch(r){return{removed:0,errors:[sn(r)]}}let i=0;for(let r of n)if(!(!r.name.startsWith("reindex-")||!r.isDirectory()))try{Je(te(e,r.name),{recursive:!0,force:!0}),i+=1}catch(o){t.push(`${r.name}: ${sn(o)}`)}return{removed:i,errors:t}}async function $v(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,i=await Vt("reindex.language-indexers",async()=>(n=await Pv(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:r,skippedLanguages:o,reusedLanguages:s,languageFingerprints:a,shards:c,typescriptProjectShardContext:l,incrementalTypeScript:d}=i;if(s.length>0&&e.onStatus(`Reused ${s.length} cached language shard(s): ${s.join(", ")}`),Cv({run:e,indexedOutputs:r,skippedLanguages:o,reusedLanguages:s})){let f=qt("reindex.publish",()=>Fv(e,r,o,s,a,l),{mode:"metadata-only",languages:r.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:r.map(h=>h.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:f,shards:c}}let u=qt("reindex.publish",()=>Ov(e,t,r,o,s,a,l,d),{mode:d?"incremental-or-fallback":"full",languages:r.length,reused:s.length,skipped:o.length}),m=u.durationMs;return e.onStatus(`Done in ${(m/1e3).toFixed(1)}s`),{languages:r.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:m,reused:!1,skipped:o,lastRefresh:u,shards:c}}function Cv(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!ke(e.run.paths.outputScip)||!ke(e.run.paths.outputDb))return!1;let t=st(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),i=new Set(e.indexedOutputs.map(r=>r.language));return e.run.languages.length>0&&i.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(r=>n.has(r)&&i.has(r))}async function Pv(e,t){let n=Av({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}),i=[],r=new Set;for(let[F,ee]of n)ee.reused&&(i.push({language:F,scipPath:ee.scipPath}),r.add(F));for(let F of r)e.onStatus(`Reusing cached ${F} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),s=st(e.paths.outputDb,e.paths.metaPath),a=ln(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?Ad({projectRoot:e.projectRoot,cacheDir:B(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:cn(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:cn(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:Xr(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,u=new Set(d?["typescript"]:[]),m=d?void 0:Tv(e,n),{preparedRuns:f,skippedLanguages:g,languageOutputScipPaths:h}=Bv({languages:e.languages.filter(F=>!r.has(F)&&!u.has(F)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:m?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),y=m?f.filter(F=>F.language!=="typescript"||m.missedProjectIds.has(F.id)):f,S=await Od(y,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),v=[];if(m){Ev(e.paths.outputDb,S);let F=h.typescript??e.tempPaths.tempOutputScip;v=jv({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:F,reusedProjects:m.reusedProjects})}let w=[...S,...v],{indexedOutputs:k}=Vv(w,g),O=d?[{language:"typescript",scipPath:d.scipPath}]:[],q=[...i,...O,...k];Wv(q,g,e.languages,e.opts.allowPartial,e.onStatus);let K=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:an(d.scipPath)??void 0}]:[],I=Lv(n,[...S,...K],m?{outputDb:e.paths.outputDb,classification:m.classification}:void 0);return{indexedOutputs:q,skippedLanguages:g,reusedLanguages:[...r],languageFingerprints:Dv(n,e.languages),shards:I,typescriptProjectShardContext:m?{projects:m.allProjects,fingerprints:m.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function Tv(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let i=rn(e.projectRoot,e.opts.typescriptProjects);if(i.length===0)return;let r=ud(e.projectRoot,i),o=cd(n.fingerprint.files,i),s=ld(i,r),a=dd(i,o,s),c=ln(e.paths.metaPath),d=Iv(c,a,g=>ke(bi(e.paths.outputDb,g))),u=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),m=new Set(u),f=new Set(i.filter(g=>!m.has(g)).map(g=>`typescript:${g}`));return{allProjects:i,fingerprints:a,classification:d,reusedProjects:u,missedProjectIds:f}}function Iv(e,t,n){let i=new Map;for(let r of Object.keys(t)){let o=t[r];if(!e){i.set(r,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let s=e.typescriptProjectShards?.[r];if(!s){i.set(r,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(r)){i.set(r,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(Ge(s)!==Ge(o)){i.set(r,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}i.set(r,{reused:!0,fingerprint:o})}return i}function Ev(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let i=n.id.slice(11),r=bi(e,i);gi(B(r),{recursive:!0}),hi(n.scipPath,r)}}function jv(e){return e.reusedProjects.map((t,n)=>{let i=bi(e.outputDb,t),r=cn(e.tempOutputScip,"typescript-project-cached",n);return hi(i,r),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:r,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:an(r)??void 0}})}function Av(e){let t=ln(e.paths.metaPath),n=Su(e.projectRoot,e.languages,e),i=new Map;for(let r of e.languages){let o=Zr(e.paths.outputDb,r),s=n[r];if(!t){i.set(r,{reused:!1,reason:"no reindex metadata found",fingerprint:s,scipPath:o});continue}if(t.version!==3){i.set(r,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:o});continue}if(r==="typescript"&&t.scipCompanion==="deferred"){i.set(r,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:s,scipPath:o});continue}if(!t.languageFingerprints){i.set(r,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:s,scipPath:o});continue}let a=t.languageFingerprints[r];if(!a){i.set(r,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:s,scipPath:o});continue}if(!ke(o)){i.set(r,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:o});continue}if(Ge(a)!==Ge(s)){i.set(r,{reused:!1,reason:"language inputs changed since last index",fingerprint:s,scipPath:o});continue}i.set(r,{reused:!0,fingerprint:s,scipPath:o})}return i}function Lv(e,t,n){let i=[];for(let[r,o]of e)o.reused&&i.push({id:r,language:r,reused:!0,fingerprint:on(o.fingerprint),outputBytes:an(o.scipPath),durationMs:0});for(let r of t){let o=e.get(r.language),s=n&&r.id.startsWith("typescript:")?r.id.slice(11):null,a=s?n.classification.get(s):void 0;i.push({id:r.id,language:r.language,reused:!1,missReason:a?.reason??o?.reason??r.skipped?.reason,fingerprint:a?on(a.fingerprint):o?on(o.fingerprint):"unknown",outputBytes:r.outputBytes??null,durationMs:r.durationMs,command:r.command})}if(n)for(let[r,o]of n.classification)o.reused&&i.push({id:`typescript:${r}`,language:"typescript",reused:!0,fingerprint:on(o.fingerprint),outputBytes:an(bi(n.outputDb,r)),durationMs:0});return i}function on(e){return uv("sha256").update(Ge(e)).digest("hex").slice(0,16)}function an(e){try{return gv(e).size}catch{return null}}function Dv(e,t){let n={};for(let i of t){let r=e.get(i);r&&(n[i]=r.fingerprint)}return n}function Ov(e,t,n,i,r,o,s,a){let c=!a||a.completeScipUpdated,l=!1;c&&(su(e.paths.outputDb,n),l=au(n,e.tempPaths.tempOutputScip,e.onStatus));let d=Hv({run:e,env:t,indexedOutputs:n,skippedLanguages:i,reusedLanguages:r,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..."),Ld({cacheDir:B(e.paths.outputDb),generationIdentity:a.nextFragmentGeneration,baseShardPath:a.scipPath,candidateShardPath:a.candidateScipPath});let v=n.map(w=>w.language==="typescript"?{language:w.language,scipPath:a.candidateScipPath}:w);return su(e.paths.outputDb,v),l=au(v,e.tempPaths.tempOutputScip,e.onStatus),l}});if(mt(pt(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&a){let v=null,w=null;try{v=new Ne({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),w=new Ne({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let k=hs(v,e.fingerprint,a.referenceFragmentsByFile,w);e.onStatus(`Cached exact TypeScript reference fragments for ${k} affected document(s).`)}catch(k){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${k instanceof Error?k.message:String(k)}.`)}finally{v?.close(),w?.close()}}let u=Xr(e.paths.metaPath),m=d.mode==="incremental"&&a?Gv(a,d.changedDocumentPaths):Cr({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=Si({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(v=>v.language),skipped:[...i]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",h={...o};g&&delete h.typescript;let{metadata:y,pruneProjects:S}=fu({run:e,indexedOutputs:n,skippedLanguages:i,reusedLanguages:r,languageFingerprints:h,typescriptProjectShardContext:s,lastRefresh:f});return y.scipCompanion=g?"deferred":"current",gu(e.paths.outputDb,S),eo(e.tempPaths.tempMetaPath,y),Ja({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}:{}}}),ic(B(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[a.nextFragmentGeneration]:[]),mu(e.paths.outputDb,m,e.onStatus),f}function Fv(e,t,n,i,r,o){let s=Xr(e.paths.metaPath),a=null;try{hi(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(u){a=Vl("reused","oracle-error",`Could not snapshot the prior database: ${u instanceof Error?u.message:String(u)}`)}mt(pt(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),a??=Cr({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=Si({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(u=>u.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=fu({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:i,languageFingerprints:r,typescriptProjectShardContext:o,lastRefresh:c});return gu(e.paths.outputDb,d),eo(e.paths.metaPath,l),za(e.paths.outputDb,e.paths.metaPath),mu(e.paths.outputDb,a,e.onStatus),c}function Xr(e){return ns(ln(e)?.fingerprint)}function mu(e,t,n){try{Gl(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(i){n(`Affected-set shadow telemetry unavailable: ${i instanceof Error?i.message:String(i)}`)}}function fu(e){let t=Nv({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 Nv(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=ln(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 gu(e,t){let n=vu(e);if(t===null){Je(n,{recursive:!0,force:!0});return}let i;try{i=uu(n)}catch{return}for(let r of Mv(i,t))Je(te(n,r),{force:!0})}function Mv(e,t){let n=new Set(t.map(i=>`${Or(i)}.scip`));return e.filter(i=>!n.has(i))}function su(e,t){for(let n of t){let i=Zr(e,n.language);gi(B(i),{recursive:!0}),n.scipPath!==i&&hi(n.scipPath,i)}}async function _v(e,t){if(!Yn()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
336
|
+
Install from: https://github.com/sourcegraph/scip/releases`);if(bv()==="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..."),!Tl(t))throw new Error(`The scip CLI is required but could not be installed.
|
|
337
|
+
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function Bv(e){let t=[],n=[],i=e.languages.map((o,s)=>({language:o,scipPath:e.languages.length>1?cn(e.tempOutputScip,o,s):e.tempOutputScip})),r=Object.fromEntries(i.map(({language:o,scipPath:s})=>[o,s]));for(let{language:o,scipPath:s}of i){let a=qv({...e,language:o,scipPath:s});for(let c of a)"skipped"in c?hu(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:r}}function qv(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Yr({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??rn(e.projectRoot,e.typescriptProjects);return t.length===0?[Yr({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(e.onStatus(`Indexing TypeScript workspace as ${t.length} project shard(s).`),t.map((n,i)=>Yr({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:cn(e.tempOutputScip,"typescript-project",i),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Yr(e){let t=ct(e.language),n=$n(t),i=Xo(t,e.projectRoot);if(!i&&!Yo(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...`),!pi(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 r=i??Cn(t);if(!r){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:r,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:r,binary:o,args:s,env:Zo(t,e.env,r)}}}function Vv(e,t){let n=new Map;for(let r of e)if(r.skipped)hu(t,r.skipped);else{let o=`${r.language}\0${r.outputScipPath}`,s=n.get(o)??{language:r.language,outputScipPath:r.outputScipPath,scipPaths:[]};s.scipPaths.push(r.scipPath),n.set(o,s)}let i=[];for(let r of n.values())if(r.scipPaths.length>1)oc(r.scipPaths,r.outputScipPath),i.push({language:r.language,scipPath:r.outputScipPath});else{let o=r.scipPaths[0];o!==r.outputScipPath&&pu(o,r.outputScipPath),i.push({language:r.language,scipPath:r.outputScipPath})}return{indexedOutputs:i}}function hu(e,t){let n=e.find(i=>i.language===t.language);if(!n){e.push(t);return}n.reason.includes(t.reason)||(n.reason=`${n.reason}; ${t.reason}`)}function Wv(e,t,n,i,r){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
|
|
338
|
+
`);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
|
|
339
|
+
`+o)}if(t.length!==0&&(r(`Indexed ${e.length} language output(s); skipped or incomplete: ${t.map(o=>o.language).join(", ")}.`),!i))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
|
|
340
|
+
`+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
|
|
341
|
+
`))}function au(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let i=performance.now(),r=sc(e.map(o=>o.scipPath),t);return bu(r,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-i).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&pu(e[0].scipPath,t);return!1}function Hv(e){let t;if(Uv(e)){let r=te(e.run.tempPaths.runDir,"typescript-affected.db");try{yu(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();cu(e.incrementalTypeScript.affectedScipPath,r,e.env,e.run.onStatus),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let s=Xl({previousDbPath:e.run.paths.outputDb,miniDbPath:r,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),Je(r,{force:!0}),Je(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 i=performance.now();return cu(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-i,...t?{fallbackReason:t}:{}}}function Uv(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!ke(e.run.paths.outputDb)||!ke(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 Gv(e,t){let n=Date.now(),i=[...t].sort(),r=new Set(i),o={addedFiles:[],modifiedFiles:i,deletedFiles:[],changedFiles:i,unchangedFiles:e.affectedFiles.filter(s=>!r.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:$r(e.plan,o,e.projectFileCount)}}function cu(e,t,n,i,r=!1){if(i("Converting to SQLite..."),!ke(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{r||yu(e,i);let o=Yn();if(!o)throw new Error("scip CLI is not available");dv(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 yu(e,t){let n=rc(e);bu(n,t)}function bu(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function cn(e,t,n){let i=yv(e)||".scip",r=fi(e,i);return te(B(e),`${r}.${n+1}.${t}${i}`)}async function Jv(e,t){for(let n=0;n<2;n++){let i=zv(e,t);if(i)return i;let r=Kv(e);if(r&&Qv(t.trigger,r)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${r.startedAt}.`),!await Xv(r.pid))throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${r.pid}) terminated for ${B(e)}; refusing to steal an active lock.`);Je(e,{force:!0});continue}if(r&&!St(r.pid)){Je(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${B(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${B(e)}.`)}function zv(e,t){let n;try{n=fv(e,"wx")}catch(r){if((typeof r=="object"&&r&&"code"in r?r.code:void 0)==="EEXIST")return null;throw r}let i={version:1,pid:process.pid,projectRoot:t.projectRoot,startedAt:new Date().toISOString(),trigger:t.trigger};return hv(n,JSON.stringify(i)+`
|
|
342
|
+
`),()=>{try{pv(n)}finally{Je(e,{force:!0})}}}function Kv(e){try{let t=JSON.parse(yi(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:B(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function Qv(e,t){return e?.kind==="manual-cli"&&Yv(t?.trigger)}function Yv(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function Xv(e){return lu(e,"SIGTERM"),await du(e,2e3)?!0:(lu(e,"SIGKILL"),du(e,1e3))}function lu(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function du(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!St(e))return!0;await Zv(50)}return!St(e)}function Zv(e){return new Promise(t=>setTimeout(t,e))}function Su(e,t,n){return Object.fromEntries(t.map(i=>{let r=ct(i).markerFiles,o=i==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:is(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},s=i==="clojure"?ex(n.clojureConfigPath):void 0;return[i,{version:2,languages:[i],pnpmWorkspaces:i==="typescript"&&tx(n),...o,clojureConfigPath:s,files:In(e,{language:i,markerFiles:r})}]}))}function ex(e){return e?.trim()||void 0}function tx(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Zr(e,t){return te(B(e),"language-indexes",`${t}.scip`)}function vu(e){return te(B(e),"language-indexes","typescript-projects")}function bi(e,t){return te(vu(e),`${Or(t)}.scip`)}function ln(e){try{return JSON.parse(yi(e,"utf-8"))}catch{return null}}function xu(e,t){try{let n=JSON.parse(yi(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&Ge(n.fingerprint)===Ge(t)&&Ge([...n.indexedLanguages??[]].sort())===Ge(t.languages)}catch{return!1}}function eo(e,t){vt(e,t,{spacing:2,trailingNewline:!0})}function Ru(e,t){try{let n=JSON.parse(yi(e,"utf-8"));if(n.version!==2&&n.version!==3)return;eo(e,{...n,lastRefresh:t})}catch{}}function Si(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 Ge(e){return JSON.stringify(e)}var to=864e5;function ku(e,t={}){let i=[...t.check?e.filter(l=>l.check===t.check):[...e]].sort((l,d)=>l.ts-d.ts),r=new Map;for(let l of i){let d=`${l.check}\0${l.findingId}`,u=r.get(d);u||(u={check:l.check,findingId:l.findingId,caughtAt:l.ts,events:[]},r.set(d,u)),u.events.push(l)}let o=[...r.values()].filter(l=>t.sinceMs===void 0||l.caughtAt>=t.sinceMs),s=nx(i),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 w of d){f+=w.events.filter(q=>q.event==="reopened").length;let k=w.events[w.events.length-1],O=`${w.check}\0${w.findingId}`;if(k.event==="resolved"&&s.has(O))g+=1;else if(k.event==="resolved"){let q=zt(w.events.slice(0,-1)),K=q?.comparisonBaseCommit??q?.commit,I=k.comparisonBaseCommit??k.commit;K&&(I===K||k.verifiedAgainstCommit===K)?(u+=1,S.push((k.ts-w.caughtAt)/to)):h+=1}else k.event==="suppressed"?m+=1:y+=1}let v=u+m;c.push({check:l,caught:d.length,fixed:u,suppressed:m,reopened:f,moved:g,unverified:h,open:y,precision:v>0?u/v:null,medianDaysToFix:S.length>0?ix(S):null})}return{totalEvents:i.length,windowStart:t.sinceMs??null,checks:c.sort((l,d)=>l.check.localeCompare(d.check))}}function nx(e){let t=new Map;for(let r of e){if(r.event!=="caught"||!r.commit||!r.symbol)continue;let o=t.get(r.commit)??[];o.push(r),t.set(r.commit,o)}let n=new Map;for(let r of e)r.event==="caught"&&r.symbol&&n.set(`${r.check}\0${r.findingId}`,r.symbol);let i=new Set;for(let r of e){if(r.event!=="resolved"||!r.commit)continue;let o=`${r.check}\0${r.findingId}`,s=r.symbol??n.get(o);if(!s)continue;(t.get(r.commit)??[]).some(c=>c.check===r.check&&c.symbol===s&&c.findingId!==r.findingId)&&i.add(o)}return i}function wu(e,t){let n=/^(\d+)([dw])$/.exec(e.trim());if(n){let r=Number(n[1]),o=n[2]==="w"?7*to:to;return t-r*o}let i=Date.parse(e);return Number.isNaN(i)?null:i}function ix(e){let t=[...e].sort((i,r)=>i-r),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}import{fork as rx}from"child_process";import{statSync as ox}from"fs";import{isAbsolute as sx,join as ax,relative as cx}from"path";import{watch as lx}from"chokidar";import dx from"ignore";var vi=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onRefreshSuppressed;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=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.onRefreshSuppressed=t.onRefreshSuppressed??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=kt(t.projectRoot),this.extraIgnore=dx(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(t){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(t,n={}){if(!n.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(t);return}this.pendingTrigger=$u(this.pendingTrigger,t),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}startSourceWatcher(t=!1){let n=lx(this.projectRoot,{ignoreInitial:!0,ignored:(i,r)=>this.isIgnoredWatchPath(i,r?.isDirectory()??!1),usePolling:t,...t?{interval:500,binaryInterval:1e3}:{}});n.on("all",(i,r)=>{this.stopped||this.handleFileChange(r)}),n.on("error",i=>this.handleSourceWatcherError(n,i,t)),this.fsWatchers.push(n)}handleSourceWatcherError(t,n,i){if(i||this.sourcePollingFallbackStarted||!ux(n)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(n)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(r=>r!==t),t.close();try{this.startSourceWatcher(!0)}catch(r){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(r)}`))}}isIgnoredWatchPath(t,n){let i=this.relativeWatchPath(t);if(!i)return!1;let r=n?`${i}/`:i;return r===".git/"||r.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(r)||this.extraIgnore.ignores(r)}handleFileChange(t){let n=this.relativeWatchPath(t);!n||n===".."||n.startsWith("../")||n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||n.endsWith("index.db")||n.endsWith("index.scip")||n.endsWith("index.db.tmp")||n.endsWith(si)||n.endsWith(`${si}.previous`)||this.scheduleReindex({kind:"watch-source",detail:n})}relativeWatchPath(t){let n=sx(t)?t:ax(this.projectRoot,t);return cx(this.projectRoot,n).replaceAll("\\","/")}scheduleReindex(t){if(this.pendingTrigger=$u(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 r=this.watchConfig.cooldownMs-t;this.dirty=!0;let o=Date.now()+r;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},r);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let i=Date.now();this.setStatus({state:"indexing",startedAt:i}),this.runReindex(n).then(r=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now();let o=!1;try{o=this.onReindexComplete(r)===!0}catch(s){this.onError(s instanceof Error?s:new Error(String(s)))}if(this.dirty&&!this.stopped){if(o){let a=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(a),this.setStatus({state:"idle"});return}let s=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:s,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(r=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(r instanceof Error?r:new Error(String(r))),this.setStatus({state:"idle"})})}runReindex(t){return new Promise((n,i)=>{let r=Date.now(),o=fe(this.projectRoot),s=Object.keys(o).length>0?o:this.config,a=Fe(this.projectRoot,s),c=s.indexer?.typescript,l=s.indexer?.clojure,d=rx(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()-r):i(new Error(`Reindex worker exited with code ${u}`))}),d.on("error",i)})}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 i=t.head!==n.head,r=t.indexPath!==n.indexPath||t.indexMtimeMs!==n.indexMtimeMs||t.indexSize!==n.indexSize;i&&r?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):i?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):r&&this.scheduleReindex({kind:"watch-git-index",detail:n.indexPath??"index changed"})}readGitState(){let t=Ut(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n=cs(this.projectRoot,t),i={head:Ut(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:n};try{let r=ox(n);i.indexMtimeMs=r.mtimeMs,i.indexSize=r.size}catch{i.indexMtimeMs=void 0,i.indexSize=void 0}return i}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function $u(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}function ux(e){return e instanceof Error&&"code"in e&&e.code==="EMFILE"||String(e).includes("EMFILE: too many open files")}import{existsSync as Lx}from"fs";import{existsSync as Pu,mkdirSync as Tu,readFileSync as Iu,writeFileSync as Eu}from"fs";import{homedir as px}from"os";import{dirname as ju,isAbsolute as mx,join as no,relative as Cu,resolve as fx}from"path";function Au(e,t={}){let n=t.dossierDir?fx(e.projectRoot,t.dossierDir):no(e.projectRoot,"docs","scip-query"),i={markdownPath:no(n,"health-dossier.md"),jsonPath:no(n,"health-dossier.json"),status:"written",written:[],unchanged:[]},r=kx({...e,generatedAt:new Date().toISOString(),healthDossier:i},e.projectRoot);try{return vx(i.markdownPath,gx(r),i),xx(i.jsonPath,r,i),i}catch(o){return{...i,status:"failed",error:o instanceof Error?o.message:String(o)}}}function gx(e){return`${["# scip-query Health Dossier","",`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${ro(e.health)}`,"","## Items That Need Attention","",...hx(e),"","## Blocked Or Unavailable Checks","",...yx(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","",...bx(e),"","## JSON","",`Machine-readable report: \`${Sx(e)}\``,""].join(`
|
|
343
|
+
`)}`}function hx(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 yx(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 bx(e){return e.indexerRemediation.length===0?["All detected indexers were already runnable."]:e.indexerRemediation.map(t=>{let n=t.after.runnable?"READY":"BLOCKED",i=t.attempted?"install attempted":"no automatic install attempted";return`- ${n} ${t.language}: ${t.binaryLabel} (${i})`})}function ro(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function Sx(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function vx(e,t,n){if(Tu(ju(e),{recursive:!0}),(Pu(e)?Iu(e,"utf-8"):null)===t){n.unchanged.push(e);return}Eu(e,t),n.written.push(e)}function xx(e,t,n){Tu(ju(e),{recursive:!0});let i=`${JSON.stringify(t,null,2)}
|
|
344
|
+
`,r=Pu(e)?Iu(e,"utf-8"):null;if(r&&Rx(r,i)){n.unchanged.push(e);return}Eu(e,i),n.written.push(e)}function Rx(e,t){try{let n=JSON.parse(e),i=JSON.parse(t);return delete n.generatedAt,delete i.generatedAt,JSON.stringify(n)===JSON.stringify(i)}catch{return e===t}}function kx(e,t){return io(e,t)}function io(e,t){return typeof e=="string"?wx(e,t):Array.isArray(e)?e.map(n=>io(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,i])=>[n,io(i,t)])):e}function wx(e,t){if(e===t)return".";if(!mx(e))return e;let n=Cu(t,e).replace(/\\/g,"/");if(!n)return".";if(n.startsWith("..")){let i=Cu(px(),e).replace(/\\/g,"/");return i&&!i.startsWith("..")?`~/${i}`:e}return n}import{spawnSync as $x}from"child_process";import{readFileSync as Du}from"fs";import{dirname as Lu,join as Cx,resolve as Px}from"path";import{fileURLToPath as Tx}from"url";var xi={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 Ix(e,t){let n=new Set(["tree-sitter"]);for(let i of e)for(let r of xi[i]?.packages??[])n.add(r);return[...n].filter(i=>t[i]).sort().map(i=>`${i}@${t[i]}`)}function oo(e){return[...new Set(e.filter(t=>xi[t]!==void 0))].sort()}function Ou(e,t={}){let n=t.runtime??Ax,i=t.packageRoot??Ex(),r=oo(e),o=r.filter(u=>n.probe(xi[u].ast)),s=r.filter(u=>!o.includes(u));if(s.length===0)return{supportedLanguages:r,availableBefore:o,installed:[],availableAfter:o,unavailable:[],attempted:!1};let a=jx(i),c=Ix(s,a),l=n.install(i,c);l.ok&&n.resetProbe();let d=r.filter(u=>n.probe(xi[u].ast));return{supportedLanguages:r,availableBefore:o,installed:l.ok?c:[],availableAfter:d,unavailable:r.filter(u=>!d.includes(u)),attempted:!0,...l.error?{error:l.error}:{}}}function Ex(){let e=Lu(Tx(import.meta.url));for(;;){let t=Cx(e,"package.json");try{if(JSON.parse(Du(t,"utf8")).name==="scip-query")return e}catch{}let n=Lu(e);if(n===e)throw new Error("Unable to locate the installed scip-query package root.");e=n}}function jx(e){return JSON.parse(Du(Px(e,"package.json"),"utf8")).optionalDependencies??{}}var Ax={probe:e=>xn(e)==="ast",resetProbe:_o,install:(e,t)=>{let n=$x(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 Mu(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(i=>!i.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 _u(e={}){let t=[],n=_e(),{projectRoot:i,paths:r,dbPath:o}=n,s=e.automaticRefresh??n.config.watch?.enabled??!0,a=e.languages?Ua(i,n.config,e.languages):null,c=a?.config??n.config,l=wt(c,{projectRoot:i}),d=l.filter(A=>A.level==="error"),u=null,m=null;if(d.length===0&&c.watch?.enabled!==s)try{u=Ga(i,c,s)}catch(A){m=Ft(A)}let f=u?.config??c,g=tn();M(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]}:{}}),M(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:[]}:ti({quiet:!0});M(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(A=>`Pruned ${A}`),...h.skipped.map(A=>`Skipped ${A}`)]});let y=u?wt(f,{projectRoot:i}):l,S=y.filter(A=>A.level==="error");M(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(A=>`${A.level.toUpperCase()} ${A.path}: ${A.message}`)});let v=he(i,f);M(t,{id:"readiness",label:"Indexer readiness",status:v.languages.length===0?"failed":v.indexers.some(A=>!A.runnable)?"warn":"ok",message:v.languages.length===0?"No supported project languages detected.":`Detected languages: ${v.languages.join(", ")}`,details:v.indexers.map(A=>`${A.runnable?"OK":A.installed?"WARN":"MISSING"} ${A.language}: ${A.binaryLabel}${A.note?` - ${A.note}`:""}`)});let w=e.installAstParsers===!1?{supportedLanguages:[],availableBefore:[],installed:[],availableAfter:[],unavailable:[],attempted:!1}:Ou(v.languages);M(t,{id:"ast-parsers",label:"AST parser packages",status:e.installAstParsers===!1?"skipped":w.unavailable.length>0?"warn":"ok",message:e.installAstParsers===!1?"Skipped by setup choice.":w.supportedLanguages.length===0?"No selected language uses a bundled Tree-sitter parser.":`${w.availableAfter.length}/${w.supportedLanguages.length} selected language parser(s) available${w.installed.length>0?`; installed ${w.installed.join(", ")}`:""}.`,details:[...w.unavailable.length>0?[`Unavailable: ${w.unavailable.join(", ")}`]:[],...w.error?[w.error]:[]]});let k=e.installIndexers??!0,O=k?Hx(i,v,t):[];k||M(t,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped by guided setup choice."});let q=he(i,f),K=await Dx({projectRoot:i,paths:r,config:f,readiness:q,configHasErrors:S.length>0,steps:t,onStatus:e.onStatus}),I=K.reindexResult,F=K.freshness,ee=Pe(f),N=Ox({projectRoot:i,cacheDir:r.cacheDir,watchConfig:ee,readiness:q,configHasErrors:S.length>0,reindexResult:I,postReindexFreshness:F,steps:t}),H=he(i,f),yn=Xe(H),Fo=Te(i,f,r);M(t,{id:"capabilities",label:"Capability matrix",status:Qx(yn),message:Yx(yn)}),e.onStatus?.(e.runHealth===!1?"Skipping optional full health audit.":"Running full health audit\u2026");let No=e.runHealth===!1?Jx(t):await Gx(r.dbPath,t),$e=H.languages.includes("rust")?En(i,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION):null;M(t,{id:"rust-semantic-session",label:"Rust semantic session",status:$e===null?"skipped":$e.valid?"ok":"failed",message:$e===null?"Skipped because Rust was not detected.":`${$e.transport}/${$e.state} selected from ${$e.source}; ${$e.fallback} fallback; opt out with ${$e.optOut}.`});let ne=null;try{e.noHooks?M(t,{id:"project-hooks",label:"Project agent hooks",status:"skipped",message:"Skipped by --no-hooks."}):(ne=Lt(i),M(t,{id:"project-hooks",label:"Project agent hooks",status:ne.skipped.length>0?"warn":"ok",message:`${ne.installed.length} installed, ${ne.updated.length} updated, ${ne.unchanged.length} already configured, ${ne.removed.length} hook config(s) cleaned up, ${ne.skipped.length} skipped.`,details:[...ne.gitExcluded.map(A=>`Checkout-local Git exclude: ${A}`),...ne.removed.map(A=>`Removed ${A}`),...ne.skipped.map(A=>`Skipped ${A.target}: ${A.reason}`),...ne.warnings]}))}catch(A){M(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:Ft(A)})}let be=null;try{e.noAgentGuidance?M(t,{id:"agent-guidance",label:"Project agent guidance",status:"skipped",message:"Skipped by guided setup choice."}):(be=Wn(i,{gitHook:e.gitHook}),M(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(A=>`Skipped ${A.target}: ${A.reason}`)}))}catch(A){M(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:Ft(A)})}let bn=Fx({reindexResult:I,readiness:H,capabilities:yn,freshness:Fo,health:No,hooksResult:ne,agentResult:be,watchConfig:ee,watchService:N,rustSemanticSession:$e,steps:t});M(t,{id:"smoke-tests",label:"Setup smoke tests",status:Nx(bn),message:Mx(bn),details:bn.map(A=>`${A.command}: ${A.status} - ${A.evidence}`)});let Nf={repository:[...a?.changed?[a.configPath]:[],...u?.changed?[u.configPath]:[],...be?.written.filter(A=>!A.startsWith(".git/hooks/"))??[]],checkout:[...new Set([...ne?.installed??[],...ne?.updated??[],...ne?.gitExcluded??[],...be?.written.filter(A=>A.startsWith(".git/hooks/"))??[]])],user:[...h.installed,...w.installed,...O.filter(A=>A.attempted).map(A=>`${A.binaryLabel} installer`)]},Le={projectRoot:i,dbPath:o,configuredDbPath:r.dbPath,scipCliInstalled:g,languages:H.languages,steps:t,skills:h,astParsers:w,initialReadiness:v,indexerRemediation:O,readiness:H,capabilities:yn,freshness:Fo,reindex:I,automaticRefreshConfig:u,watchService:N,rustSemanticSession:$e,health:No,smokeTests:bn,healthDossier:null,hooks:ne,setupAgent:be,changeScopes:Nf,filesWritten:be?.written??[],verdict:ao(t,H)};if(e.runHealth===!1)return M(t,{id:"health-dossier",label:"Health dossier",status:"skipped",message:"Skipped because the optional health audit was not selected."}),Le.verdict=ao(t,H),Le;let Ce=Au(Le,{dossierDir:e.dossierDir});return Le.healthDossier=Ce,Le.changeScopes.repository.push(...Ce.written),Le.filesWritten=[...Le.filesWritten,...Ce.written],M(t,{id:"health-dossier",label:"Health dossier",status:Ce.status==="failed"?"failed":"ok",message:Ce.status==="failed"?Ce.error:`${Ce.written.length} written, ${Ce.unchanged.length} unchanged.`,details:[Ce.markdownPath,Ce.jsonPath]}),Le.verdict=ao(t,H),Le}async function Dx(e){if(e.readiness.languages.length===0||e.configHasErrors)return M(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,i=null;try{let r=0,o=!1;for(let s=0;s<2;s+=1){if(n=await Ot({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)}}),r+=n.durationMs,o||=!n.reused,i=Te(e.projectRoot,e.config,e.paths),s===0&&n.skipped.length===0&&i.state==="stale"){t.push(`Index inputs changed during the first build (${i.reason}); running one settling refresh.`);continue}break}if(!n)throw new Error("Setup index refresh produced no result.");M(e.steps,{id:"reindex",label:"Index refresh",status:n.skipped.length>0?"warn":"ok",message:`${o?"Indexed":"Reused"} ${n.languages.join(", ")} in ${(r/1e3).toFixed(1)}s.`,details:[...t,...n.skipped.map(s=>`Skipped ${s.language}: ${s.reason}`)]})}catch(r){M(e.steps,{id:"reindex",label:"Index refresh",status:"failed",message:Ft(r),details:t})}return{reindexResult:n,freshness:i}}function Ox(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 M(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"skipped",message:t}),null;try{let n=Bn({projectRoot:e.projectRoot,cacheDir:e.cacheDir,cliVersion:Me,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 i=e.watchConfig.idleTimeoutMs===0?"configured to remain running":`clean-idle exit scheduled for ${n.state.idleDeadlineAt}`;return M(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"ok",message:`${n.disposition} pid ${n.state.pid}; ${i}.`,details:[`watcher=${n.state.watcher.state}`,`autoRefresh=${e.watchConfig.autoRefresh}`,`gitPollMs=${e.watchConfig.gitPollMs}`]}),n}catch(n){return M(e.steps,{id:"watch-refresh",label:"Automatic indexing service",status:"failed",message:Ft(n)}),null}}function Bu(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${ro(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:"),so("Repository records (commit)",e.changeScopes.repository),so("Checkout preferences (do not commit)",e.changeScopes.checkout),so("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",i=t.attempted?"attempted install":"manual action required";console.log(` - ${t.language}: ${n} (${i})`),t.recovery&&console.log(` ${t.recovery}`)}}}function so(e,t){if(console.log(` ${e}:`),t.length===0){console.log(" - none");return}for(let n of t)console.log(` - ${n}`)}function Fx(e){let t=e.steps.find(o=>o.id==="reindex"),n=e.steps.find(o=>o.id==="project-hooks"),i=e.steps.find(o=>o.id==="agent-guidance"),r=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:_x(e.steps),evidence:Bx(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?qx(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:Fu(e.readiness,e.freshness),evidence:Nu(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:Fu(e.readiness,e.freshness),evidence:Nu(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:Vx(e.capabilities),evidence:Wx(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:r?.status==="failed"?"fail":e.watchConfig.enabled&&e.watchService?"pass":"unavailable",evidence:r?.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":i?.status==="failed"?"fail":"unavailable",evidence:e.agentResult?`${e.agentResult.written.length} written, ${e.agentResult.unchanged.length} already wired, ${e.agentResult.skipped.length} skipped.`:i?.message??"Project agent guidance was not written."}]}function Nx(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function Mx(e){let t=e.filter(r=>r.status==="pass").length,n=e.filter(r=>r.status==="unavailable").length,i=e.filter(r=>r.status==="fail").length;return`${t} passed, ${n} unavailable, ${i} failed.`}function _x(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function Bx(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function qx(e){let t=e.matrix.filter(n=>[n.indexing,n.sourceFacts,n.semantic,n.cleanupVerification].some(i=>i.status==="unavailable")).length;return`${e.matrix.length} language row(s), ${t} with unavailable capability cells.`}function Fu(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function Nu(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 Vx(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function Wx(e){if(e.matrix.length===0)return"No detected languages produced capability rows.";let t=e.matrix.filter(r=>r.cleanupVerification.status==="available").length,n=e.matrix.filter(r=>r.cleanupVerification.status==="partial").length,i=e.matrix.filter(r=>r.cleanupVerification.status==="unavailable").length;return`${t} available, ${n} partial, ${i} unavailable cleanup-verification row(s).`}function Hx(e,t,n){let i=[];if(t.languages.length===0)return M(n,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because no supported languages were detected."}),i;for(let s of t.indexers){if(s.runnable)continue;let a=ct(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,d=!1;l?d=pi(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=Ux(Pn(a,e));i.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(i.length===0)return M(n,{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"All detected indexers are runnable."}),i;let r=i.filter(s=>!s.after.runnable),o=i.filter(s=>s.attempted);return M(n,{id:"indexer-remediation",label:"Indexer remediation",status:r.length>0?"warn":"ok",message:r.length===0?`${o.length} install attempt(s); all detected indexers are runnable.`:`${o.length} install attempt(s); ${r.length} indexer(s) still blocked.`,details:i.flatMap(s=>[`${s.language}: ${s.after.runnable?"ready":"blocked"}`,...s.messages])}),i}function Ux(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function Gx(e,t){if(!Lx(e)){let n="Skipped because no SQLite index database exists yet.";return M(t,{id:"health",label:"Health audit",status:"skipped",message:n}),co(n)}try{let n=await Mn({full:!0,json:!0});return M(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),zx(n)}catch(n){let i=Ft(n);return M(t,{id:"health",label:"Health audit",status:"failed",message:i}),co(i)}}function Jx(e){let t="Skipped by setup choice; run `scip-query health --full` when wanted.";return M(e,{id:"health",label:"Health audit",status:"skipped",message:t}),co(t)}function zx(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(Kx),warnings:e.warnings??[]}}function Kx(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 co(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function ao(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 Qx(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 Yx(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 M(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function Ft(e){return e instanceof Error?e.message:String(e)}import{emitKeypressEvents as Xx}from"readline";function Zx(e){return{cursor:0,selected:new Set(e.filter(t=>t.selected).map(t=>t.id))}}function eR(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 i=n[e.cursor]?.id;if(!i)return e;let r=new Set(e.selected);return r.has(i)?r.delete(i):r.add(i),{...e,selected:r}}async function qu(e,t=process.stdin,n=process.stdout){if(e.length===0)return new Set;let i=Zx(e);Xx(t);let r=t.isRaw;t.setRawMode(!0),t.resume();let o=(s=!1)=>{s||n.write(`\x1B[${e.length+3}A`),n.write(`scip-query setup
|
|
345
|
+
`),n.write(`Use \u2191/\u2193 to move, space to toggle, enter to start. Ctrl-C cancels.
|
|
346
|
+
|
|
347
|
+
`),e.forEach((a,c)=>{let l=c===i.cursor?"\u203A":" ",d=i.selected.has(a.id)?"\u25CF":"\u25CB";n.write(`${l} ${d} ${a.label} [${a.scope}]\x1B[K
|
|
348
|
+
`)}),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(`
|
|
349
|
+
`),s(i.selected);return}let m=u.name==="up"?"up":u.name==="down"?"down":u.name==="space"?"toggle":null;m&&(i=eR(i,m,e),o())},l=()=>{t.off("keypress",c)};t.on("keypress",c)})}finally{t.setRawMode(!!r),t.pause()}}import{existsSync as Vu,mkdirSync as tR,writeFileSync as nR}from"fs";import{dirname as iR,join as Wu}from"path";function Hu(e,t={}){let n=Wu(e,".github","workflows","scip-query.yml"),i=rR({hasNpmProject:Vu(Wu(e,"package.json"))});return Vu(n)&&!t.force?{path:n,written:!1,skipped:!0,content:i,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(tR(iR(n),{recursive:!0}),nR(n,i)),{path:n,written:!t.dryRun,skipped:!1,content:i})}function rR(e){let t=`scip-query@${Me}`;return`name: scip-query
|
|
350
|
+
|
|
351
|
+
# Generated by scip-query setup-ci.
|
|
352
|
+
# Install the language indexers your repository needs before the reindex step
|
|
353
|
+
# if they are not already provided by your dependency install.
|
|
354
|
+
|
|
355
|
+
on:
|
|
356
|
+
pull_request:
|
|
357
|
+
|
|
358
|
+
jobs:
|
|
359
|
+
diff-gate:
|
|
360
|
+
runs-on: ubuntu-latest
|
|
361
|
+
steps:
|
|
362
|
+
- uses: actions/checkout@v4
|
|
363
|
+
with:
|
|
364
|
+
fetch-depth: 0
|
|
365
|
+
- uses: actions/setup-node@v4
|
|
366
|
+
with:
|
|
367
|
+
node-version: 22
|
|
368
|
+
- uses: actions/cache@v4
|
|
369
|
+
with:
|
|
370
|
+
path: ~/.cache/scip-query
|
|
371
|
+
key: scip-query-\${{ runner.os }}-\${{ hashFiles('package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lockb', 'Cargo.lock', 'go.sum', 'poetry.lock', 'uv.lock') }}
|
|
372
|
+
${e.hasNpmProject?` - run: npm ci
|
|
373
|
+
`:[" # TODO: install this repository's dependencies before indexing."," # This project did not have a package.json when the workflow was generated."].join(`
|
|
374
|
+
`)+`
|
|
375
|
+
`} - run: npx ${t} reindex
|
|
376
|
+
- run: npx ${t} diff-gate --base "origin/\${{ github.base_ref }}"
|
|
377
|
+
`}import{existsSync as oR}from"fs";import{join as Ri}from"path";function Uu(e){let t=e.global===!0,n=e.project===!0,i=!t&&!n,r=t||i,o=n||i,s={dryRun:e.dryRun===!0};return r&&(s.global=jl({dryRun:e.dryRun,homeDir:e.homeDir})),o&&(s.project=sR(e.projectRoot,{dryRun:e.dryRun})),s}function sR(e,t={}){return{hooks:Lt(e,{remove:!0,dryRun:t.dryRun}),agentSetup:el(e,{dryRun:t.dryRun}),left:aR(e)}}function aR(e){return[[".scipquery.json",Ri(e,".scipquery.json")],[".scipquery/suppressions/ (repository records)",Ri(e,".scipquery","suppressions")],[".scipquery/ledger/ (repository records)",Ri(e,".scipquery","ledger")],["docs/scip-query/",Ri(e,"docs","scip-query")]].filter(([,t])=>oR(t)).map(([t])=>t)}import{existsSync as cR,readFileSync as lR}from"fs";import{createRequire as dR}from"module";import wi from"path";import{performance as ki}from"perf_hooks";var uR=dR(import.meta.url),dn;function Qu(e){let t=pR();if(!t)return An("typescript is not installed");let n=ps(e);if(n.length===0)return An("no tsconfig found");try{return new lo(e.config.projectRoot,t,n.map(i=>mR(t,i)))}catch(i){return An(i instanceof Error?i.message:String(i),n[0],n)}}function Yu(e,t,n){let i=ki.now(),r=Gu(t,e),o=ki.now()-i,s=ki.now(),a=Gu(n,e),c=ki.now()-s,l=[],d=0,u=0,m=0,f=0,g=0;for(let h of e){let y=r.get(h.symbolId)??[],S=a.get(h.symbolId)??[];u+=y.length,m+=S.length;let v=Ju(y),w=Ju(S),k=zu(y,w),O=zu(S,v);if(k.length===0&&O.length===0){d+=1;continue}f+=k.length,g+=O.length,l.push({symbol:h.symbol,missing:k,extra:O})}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 lo=class{constructor(t,n,i){this.projectRoot=t;this.ts=n;this.bundles=i}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 i=this.computeReferences(t);return this.referencesCache.set(t.symbolId,i),i}referencesForDefinitions(t){let n=new Map;for(let i of t)n.set(i.symbolId,this.referencesFor(i));return n}calleesFor(t){return[]}signatureFor(t){return null}computeReferences(t){let n=wi.join(this.projectRoot,t.relativePath),i=this.bundleForFile(n);if(!i)return[];let r=i.service.getProgram()?.getSourceFile(n);if(!r)return[];let o=gR(this.ts,r,t);if(o===null)return[];let s=i.service.findReferences(n,o)??[],a=[];for(let c of s)for(let l of c.references){let d=hR(this.ts,i.service,this.projectRoot,l);d&&(d.file===t.relativePath&&d.line>=t.startLine&&d.line<=t.endLine||a.push(d))}return ds(a)}bundleForFile(t){let n=Zu(t);return this.bundles.find(i=>i.files.has(n))??null}};function pR(){if(dn!==void 0)return dn;try{dn=uR("typescript")}catch{dn=null}return dn}function mR(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(Ku(e,n.error));let i=e.parseJsonConfigFileContent(n.config,e.sys,wi.dirname(t));if(i.errors.length>0)throw new Error(i.errors.map(s=>Ku(e,s)).join(`
|
|
378
|
+
`));let r=new Set(i.fileNames.map(Zu)),o=e.createLanguageService(fR(e,i),e.createDocumentRegistry());return{tsconfigPath:t,service:o,files:r}}function fR(e,t){return{getCompilationSettings:()=>t.options,getCurrentDirectory:()=>t.options.configFilePath?wi.dirname(String(t.options.configFilePath)):process.cwd(),getDefaultLibFileName:n=>e.getDefaultLibFilePath(n),getDirectories:e.sys.getDirectories,getScriptFileNames:()=>t.fileNames,getScriptSnapshot:n=>{if(cR(n))return e.ScriptSnapshot.fromString(lR(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 gR(e,t,n){let i=t.text.split(`
|
|
379
|
+
`),r=Math.max(0,n.startLine),o=Math.min(i.length-1,Math.max(n.endLine,n.startLine));for(let s=r;s<=o;s+=1){let a=i[s]?.indexOf(n.leaf)??-1;if(a>=0)return e.getPositionOfLineAndCharacter(t,s,a)}return null}function hR(e,t,n,i){let r=us(n,i.fileName);if(!r)return null;let o=t.getProgram()?.getSourceFile(i.fileName);if(!o)return null;let s=e.getLineAndCharacterOfPosition(o,i.textSpan.start);return{file:r,line:s.line,column:s.character}}function Gu(e,t){return e.referencesForDefinitions?e.referencesForDefinitions(t):new Map(t.map(n=>[n.symbolId,e.referencesFor(n)]))}function Ju(e){return new Set(e.map(Xu))}function zu(e,t){return e.filter(n=>!t.has(Xu(n)))}function Xu(e){return`${e.file}:${e.line}:${e.column}`}function Zu(e){return wi.resolve(e).replace(/\\/g,"/")}function Ku(e,t){return e.flattenDiagnosticMessageText(t.messageText,`
|
|
380
|
+
`)}import{readFileSync as yR}from"fs";function ep(e){let t=[];for(let[n,i]of yR(e,"utf8").split(`
|
|
381
|
+
`).entries()){let r=i.trim();if(!r)continue;let o;try{o=JSON.parse(r)}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 tp(e,t={}){let n=new Map,i=new Map,r=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 v=ye(S.name)??ye(S.phase),w=wR(S.durationMs),k=ye(S.runId);v&&w!==null&&(l+=1,s.add(v),k&&o.add(k),bR(r,S,v,w),SR(i,S,v,w,k),ye(S.subsystemWorkIdentity)&&c.add(v));let O=ye(S.workIdentity);if(!O)continue;d+=1,v&&a.add(v);let q=kR(S.workOutcome);if(!v||w===null||!q){u+=1;continue}let K=k??`unknown-run-${y}`,I=JSON.stringify([v,O]),F=n.get(I)??{spanName:v,workIdentity:O,observations:[]};F.observations.push({runId:K,command:ye(S.command)??"unknown",durationMs:w,outcome:q}),n.set(I,F)}let m=[...n.values()].map(RR).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=[...i.values()].map(vR).filter(y=>y!==null).sort((y,S)=>S.laterRunMs-y.laterRunMs||S.laterRunEvents-y.laterRunEvents||y.spanName.localeCompare(S.spanName)),g=[...r.values()].map(xR).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 np(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 i of e.rows)n.push([i.estimatedAvoidableMs,i.withinRunAvoidableMs,i.crossRunRecomputeMs,i.repeatComputations,i.runCount,i.spanName,i.workIdentity,i.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 i of e.workloadRows)n.push([i.laterRunMs,i.firstRunMs,i.laterRunEvents,i.runCount,i.subsystem,i.spanName,i.subsystemWorkIdentity,i.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(`
|
|
382
|
+
`)}
|
|
383
|
+
`}function bR(e,t,n,i){let r=ye(t.subsystem)??n.split(/[.:]/,1)[0]??n,o=e.get(r)??{subsystem:r,events:0,totalDurationMs:0,spanNames:new Set,workloadIdentifiedEvents:0,workloadIdentifiedSpanNames:new Set,exactIdentifiedEvents:0,exactIdentifiedSpanNames:new Set};o.events+=1,o.totalDurationMs+=i,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(r,o)}function SR(e,t,n,i,r){let o=ye(t.subsystemWorkIdentity);if(!o||!r||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:r,command:ye(t.command)??"unknown",durationMs:i}),e.set(a,c)}function vR(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 i=n[0],r=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:i.length,laterRunEvents:r.length,totalDurationMs:Nt(e.observations.map(o=>o.durationMs)),firstRunMs:Nt(i.map(o=>o.durationMs)),laterRunMs:Nt(r.map(o=>o.durationMs))}}function xR(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 RR(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 i=[...n.values()],r=Nt(i.flatMap(a=>a.slice(1).map(c=>c.durationMs))),o=Nt(i.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:i.length,repeatComputations:t.length-1,withinRunRepeats:t.length-i.length,crossRunRecomputes:Math.max(0,i.length-1),totalComputeMs:Nt(t.map(a=>a.durationMs)),firstComputeMs:t[0]?.durationMs??0,withinRunAvoidableMs:r,crossRunRecomputeMs:o,estimatedAvoidableMs:r+o,cacheHits:$i(e.observations,"cache-hit"),cacheMisses:$i(e.observations,"cache-miss"),reused:$i(e.observations,"reused"),skipped:$i(e.observations,"skipped")}}function kR(e){switch(e){case"computed":case"cache-hit":case"cache-miss":case"reused":case"skipped":return e;default:return null}}function $i(e,t){return e.filter(n=>n.outcome===t).length}function wR(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 Nt(e){return e.reduce((t,n)=>t+n,0)}var ip={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 rp(e,t){let n=$R(t);return{...e,warnings:[...e.warnings??[],ip.note,...n],capabilities:t,scoreInterpretation:ip}}function $R(e){return e.matrix.flatMap(t=>{let n=[t.indexing,t.sourceFacts,t.semantic,t.cleanupVerification].map(i=>/syntax only/i.test(i.reason)?`${i.label}=partial (syntax only)`:i.status==="available"?null:`${i.label}=${i.status}`).filter(i=>i!==null);return n.length===0?[]:[`${t.language} capability limits: ${n.join(", ")}. Unsupported analyses are not clean zeros.`]})}var LR=new Set(Wa),DR=18e4,cp=100*1024*1024,OR=new Set(Bo),FR=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],NR=[["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 MR(e){return e.filter(t=>LR.has(t))}async function lp(e){let t=G(e),n=X(),i=fe(n),r=Fe(n,i),o=b(t,"json");try{let s=MR(Pt(t,"language")),a=await Ot({projectRoot:n,languages:s.length>0?s:i.languages,outputScip:r.indexPath,outputDb:r.dbPath,pnpmWorkspaces:b(t,"pnpmWorkspaces")||i.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:i.indexer?.typescript?.projectMode,typescriptProjects:i.indexer?.typescript?.projects,clojureConfigPath:i.indexer?.clojure?.configPath,skipIfUnchanged:!b(t,"force"),allowPartial:b(t,"allowPartial"),skipAutoInstall:process.env.SCIP_QUERY_SKIP_AUTO_INSTALL==="1",indexerConcurrency:J(t,"indexerConcurrency")??i.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"},...o?{onStatus:()=>{}}:{}});if(o){E("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 dp(){let e=X(),t=$t(e);try{let n=ii({projectRoot:e,dbPath:t,onStatus:i=>console.log(i)});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 up(e){let t=G(e),n=X(),i=$t(n);try{let r=Qr({projectRoot:n,dbPath:i,tsconfig:$(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${r.vueFiles}; resolved references: ${r.resolvedReferences}; inserted mentions: ${r.insertedMentions}; not-inserted identifier tokens: ${r.skippedReferences}; synthetic symbols: ${r.syntheticSymbols}.`),console.log(`Not inserted by reason: no definition ${r.skippedReferenceReasons["no-definition"]}; same-file definition ${r.skippedReferenceReasons["same-file-definition"]}; unindexed definition ${r.skippedReferenceReasons["unindexed-definition"]}; missing source ${r.skippedReferenceReasons["missing-source-file"]}; missing service script ${r.skippedReferenceReasons["missing-service-script"]}. Samples: ${r.skippedReferenceSamples.length} omitted, ${r.resolvedReferenceSamples.length} resolved.`)}catch(r){console.error(`error: ${r instanceof Error?r.message:r}`),process.exit(1)}}function pp(e){let t=G(e);le(n=>{let i=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),r=sa(n,{base:$(t,"base")}),o=aa(n,i,r.changedFiles,r.changedRanges);console.log(JSON.stringify(o))})}async function mp(e){let t=G(e);try{let n=await gc({base:$(t,"base")});if(b(t,"json")){E("diff-impact",[],t,n);return}hc(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function fp(e,t){let n=G(t),i=String(e).split(",").filter(r=>r.length>0);le(r=>{let o=[];for(let c of i)Fa.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:$(n,"scope"),full:b(n,"full")},a=o.length===1?Na(r,o[0],s):Ma(r,o,s);console.log(JSON.stringify(a))})}async function gp(e){let t=G(e);if(b(t,"writeBaseline")||b(t,"baseline")){XR(t);return}try{let n=await Mn({scope:$(t,"scope"),full:b(t,"full"),json:b(t,"json")}),{projectRoot:i,config:r,dbPath:o}=_e(),s=Xe(he(i,r),{hasIndexedGraph:we(o)}),a=rp(n,s);if(b(t,"json")){E("health",[],t,a);return}fc(a,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function hp(e){let t=G(e),n=X(),i=J(t,"timeoutMs")??DR,r=b(t,"progress"),o=b(t,"profile"),s=$(t,"profileOut"),a={projectRoot:n,...zR(n),index:uo(we($t(n))),commands:[]};b(t,"coldIndex")&&(Mt(r,"cold index started"),a.coldIndex=await _R(n),Mt(r,`cold index finished ${a.coldIndex.durationMs}ms`),Wt({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),Mt(r,"warm index started"),a.warmIndex=await WR(n),Mt(r,`warm index finished ${a.warmIndex.durationMs}ms`),Wt({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=uo(we($t(n))));for(let c of HR(t))a.commands.push(GR(n,c,i,{progress:r,profile:o,profileOut:s}));if(b(t,"json")){E("bench",[],t,a);return}KR(a)}function yp(e,t){let n=G(t),i=AR(String(e)),r=tp(ep(i),{top:J(n,"top")??20});if(b(n,"json")){E("work-audit",[i],n,{profilePath:i,...r});return}process.stdout.write(np(r,i))}function bp(e){let t=G(e);le(n=>{let i=n.config.projectRoot,r=$(t,"scope")??null,o=b(t,"full"),s=J(t,"limit")??200,a=Math.max(0,J(t,"maxMismatches")??10),c=Uo(n).filter(w=>Gt(w.relativePath)).filter(w=>!n.isIgnored(w.relativePath)).sort(YR),l=r?c.filter(w=>w.relativePath.includes(r)):c,d=o?l:l.slice(0,s),u=nt.now(),m=fs(n),f=Number((nt.now()-u).toFixed(3)),g=nt.now(),h=Qu(n),y=Number((nt.now()-g).toFixed(3)),S=Yu(d,m,h),v={projectRoot:i,selection:{scope:r,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")){E("typescript-semantic-compare",[],t,v);return}QR(v)})}async function _R(e){let t=fe(e),n=Fe(e,t),i=Ci(n.dbPath),r=`${i}.bench-backup-${Date.now()}`;BR(i);let o=qR(i,r);try{let s=await Sp(()=>Ot({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 op(i,r,o,"discard-backup"),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...vp(e)}}catch(s){throw op(i,r,o,"restore-backup"),s}}var po={existsSync:we,readFileSync:CR,writeFileSync:ER,renameSync:PR,rmSync:TR,unlinkSync:IR};function mo(e){return ft(Ci(e),"bench-restore.json")}function BR(e,t=po){let n=mo(e);if(!t.existsSync(n))return!1;let i=VR(t.readFileSync(n,"utf8"));return i&&!t.existsSync(i.originalPath)&&t.existsSync(i.backupPath)&&t.renameSync(i.backupPath,i.originalPath),t.unlinkSync(n),!0}function qR(e,t,n=po){return n.existsSync(e)?(n.writeFileSync(mo(e),JSON.stringify({originalPath:e,backupPath:t})),n.renameSync(e,t),!0):!1}function op(e,t,n,i,r=po){n&&i==="restore-backup"&&!r.existsSync(e)&&r.existsSync(t)?r.renameSync(t,e):n&&i==="discard-backup"&&r.rmSync(t,{recursive:!0,force:!0});let o=mo(e);r.existsSync(o)&&r.unlinkSync(o)}function VR(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 WR(e){let t=fe(e),n=Fe(e,t),i=await Sp(()=>Ot({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:i.durationMs,result:i.value.reused?"reused":"rebuilt",languages:i.value.languages,...vp(e)}}async function Sp(e){let t=nt.now(),n=await e();return{durationMs:Math.round(nt.now()-t),value:n}}function vp(e){return we($t(e))?le(t=>{let n=xt(t);return{files:n.documents,symbols:n.symbols}}):{}}function HR(e){let t=Pt(e,"command");return t.length>0?t.map(UR).filter(n=>n.length>0):[...FR.map(n=>[...n]),...b(e,"includeHeavy")?NR.map(n=>[...n]):[]]}function UR(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function GR(e,t,n,i={}){let r=`scip-query ${t.join(" ")}`;Mt(i.progress,`${r} started`),Wt({type:"bench-command-start",command:r,projectRoot:e},i.profileOut);let o=nt.now(),s={...i.profile?JR(r,i.profileOut):process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"},a=ap(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:cp,timeout:n}),c=Math.round(nt.now()-o),l={command:r,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,...i.profileOut?{profilePath:i.profileOut}:{}};return Mt(i.progress,`${r} finished ${c}ms exit=${l.exitCode??l.signal??"unknown"}${l.timedOut?" timed-out":""}`),Wt({type:"bench-command-finish",command:r,projectRoot:e,durationMs:c,exitCode:l.exitCode,signal:l.signal,timedOut:l.timedOut,stdoutBytes:l.stdoutBytes,stderrBytes:l.stderrBytes},i.profileOut),l}function Mt(e,t){e&&process.stderr.write(`[bench] ${t}
|
|
384
|
+
`)}function JR(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function zR(e){let t=ap("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:cp});if(t.status!==0)return{repoFiles:null,sourceFiles:null};let n=t.stdout.split(`
|
|
385
|
+
`).filter(Boolean);return{repoFiles:n.length,sourceFiles:n.filter(i=>OR.has(jR(i).toLowerCase())).length}}function KR(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, ${Be(e.index.indexSizeBytes)}`),e.coldIndex&&sp("Cold index",e.coldIndex),e.warmIndex&&sp("Warm index",e.warmIndex),console.log(`
|
|
386
|
+
Commands:`);for(let t of[...e.commands].sort((n,i)=>i.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 sp(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function QR(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(`
|
|
387
|
+
Mismatch samples:`);for(let t of e.comparison.mismatches)console.log(` ${t.symbol}`),console.log(` missing=${t.missing.length} extra=${t.extra.length}`)}}function YR(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||(e.startChar??0)-(t.startChar??0)||e.symbolId-t.symbolId}function XR(e){let t=$(e,"scope");le(n=>{if(b(e,"writeBaseline")){let r=ga(n,{scope:t});console.log(`Baseline written to ${r.path} (${r.findingCount} finding(s)).`);return}let i=ha(n,{scope:t});if(i.fixedFindings.length>0&&console.log(`${i.fixedFindings.length} finding(s) fixed since baseline. Re-run --write-baseline to ratchet down.`),i.newFindings.length===0){console.log(`OK: no new findings vs baseline (${i.baselineCount} baselined, ${i.current.length} current).`);return}console.log(`FAIL: ${i.newFindings.length} new finding(s) vs ${i.baselinePath}:`);for(let r of i.newFindings)console.log(` + ${r}`);process.exitCode=1})}function xp(){let e=ti(),t=e.installed.length+e.alreadyLinked.length;console.log(`
|
|
388
|
+
${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 Rp(e){let t=G(e),n=X(),i=Lt(n,{shared:b(t,"shared"),remove:b(t,"remove"),force:b(t,"force")});if(b(t,"json")){E("setup-hooks",[],t,i);return}for(let o of i.installed)console.log(` done: ${o}`);for(let o of i.updated)console.log(` update: ${o}`);for(let o of i.unchanged)console.log(` ok: ${o} (already configured)`);for(let o of i.removed)console.log(` remove: ${o}`);for(let o of i.gitExcluded)console.log(` local: ${o} (excluded through .git/info/exclude)`);for(let o of i.warnings)console.log(` warning: ${o}`);for(let o of i.skipped)console.log(` skip: ${o.target} \u2014 ${o.reason}`);i.installed.length+i.updated.length+i.unchanged.length>0?(console.log(`
|
|
389
|
+
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(`
|
|
390
|
+
No project-local hook config was written.`)}function kp(){let e=!1;tn()?console.log("scip CLI: installed"):(Sr(),e=!0);let t=X(),n=fe(t),i=he(t,n);if(i.languages.length===0){console.log(`
|
|
391
|
+
No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
|
|
392
|
+
Detected languages: ${i.languages.join(", ")}`),console.log(`
|
|
393
|
+
Indexer readiness:`);for(let o of i.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 r=qp(i);r.length>0&&console.log(`
|
|
394
|
+
Semantic provider readiness:`);for(let o of r){let s=o.available?" OK":o.dependencyAvailable?" WARN":" MISSING";console.log(`${s} ${o.language}: ${ck(o)}${Vp(o)}`),o.reason&&console.log(` ${o.reason}`)}process.exitCode=e?1:0}function wp(e){Cp(e,"capabilities")}function $p(e){b(G(e),"json")||console.error('note: capability-matrix is deprecated; use "scip-query capabilities --matrix".'),Cp(e,"capability-matrix")}function Cp(e,t){let n=G(e),{projectRoot:i,config:r,paths:o,dbPath:s}=_e(),a=he(i,r),c=Te(i,r,o),l=Xe(a,{hasIndexedGraph:we(s)&&c.state!=="missing"});if(b(n,"json")){E(t,[],n,l);return}fo(l)}function Pp(){let e=X(),t=ot(e),n=Ha(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Tp(e){let t=G(e),n=X(),i=fe(n),r=wt(i,{projectRoot:n});if(b(t,"json"))E("config-validate",[],t,{diagnostics:r});else if(r.length===0)console.log("Config OK.");else for(let o of r)console.log(`${o.level.toUpperCase()} ${o.path}: ${o.message}`);r.some(o=>o.level==="error")&&(process.exitCode=1)}function Ip(e,t){let n=G(t),i=$(n,"reason");if(!i||i.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let r=Sa(X(),{id:String(e),check:$(n,"check"),file:$(n,"file"),reason:i,expiresAt:$(n,"expiresAt")});if(b(n,"json")){E("suppress",[String(e)],n,r);return}console.log(`Suppression written to ${r.path}.`)}catch(r){console.error(`error: ${r instanceof Error?r.message:r}`),process.exitCode=1}}function Ep(e){let t=G(e),n=Date.now(),i=$(t,"since"),r;if(i){let y=wu(i,n);if(y===null){console.error(`error: could not parse --since "${i}" (use 30d, 12w, or an ISO date).`),process.exitCode=1;return}r=y}let o=X(),s=zn(o),a=ku(s,{sinceMs:r,check:$(t,"check")});if(b(t,"json")){E("effectiveness",[],t,a);return}if(a.checks.length===0){console.log(s.length===0?`No outcome events recorded yet (${ft(Jn,"*.json")} is missing or empty). Events accrue as diff-gate runs; commit the event files so history is shared.`:"No findings match the requested window/check.");return}let c=["check","caught","fixed","suppressed","open","moved","unverified","precision","median-days-to-fix"],l=a.checks.map(y=>[y.check,String(y.caught),String(y.fixed),String(y.suppressed),String(y.open),String(y.moved),String(y.unverified),y.precision===null?"-":`${Math.round(y.precision*100)}%`,y.medianDaysToFix===null?"-":y.medianDaysToFix.toFixed(1)]),d=c.map((y,S)=>Math.max(y.length,...l.map(v=>v[S].length))),u=y=>y.map((S,v)=>S.padEnd(d[v])).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(`
|
|
395
|
+
${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(`
|
|
396
|
+
${g} finding(s) disappeared without comparable comparison-base evidence; precision is not available.`)}function jp(e){let t=G(e),{report:n,hasIndexerProblems:i,hasErrors:r}=Ap("doctor");b(t,"json")?E("doctor",[],t,n):rk(n,i),process.exitCode=r?1:0}function Ap(e){let{projectRoot:t,config:n,paths:i,dbPath:r}=_e(),o=wt(n,{projectRoot:t}),s=he(t,n),a=Te(t,n,i),c=we(r),l=Xe(s,{hasIndexedGraph:c&&a.state!=="missing"}),d=Ac(t,n,i),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:r,configuredDbPath:i.dbPath,exists:c,configDiagnostics:o,readiness:s,freshness:a,capabilities:l,sharedCache:d,ok:!m},hasIndexerProblems:u,hasErrors:f}}function Lp(e){let t=G(e),n=X(),i=Wn(n,{gitHook:b(t,"gitHook")});for(let r of i.written)console.log(` done: ${r}`);for(let r of i.unchanged)console.log(` ok: ${r} (already wired)`);for(let r of i.skipped)console.log(` skip: ${r.target} \u2014 ${r.reason}`);console.log(`
|
|
397
|
+
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 Dp(e){let t=G(e);try{let n={gitHook:b(t,"gitHook"),noHooks:b(t,"noHooks")||t.hooks===!1,dossierDir:$(t,"dossierDir"),runHealth:b(t,"yes")?!1:t.health!==!1,installSkills:t.skills!==!1,installAstParsers:t.parsers!==!1,...b(t,"yes")?{automaticRefresh:!0}:{}},i=b(t,"json"),r=!i&&!b(t,"yes")&&process.stdin.isTTY&&process.stdout.isTTY;(b(t,"guided")||r)&&(n=await ZR(n,{json:b(t,"json")})),i||(n.onStatus=s=>console.log(` ${s}`));let o=await _u(n);b(t,"json")?E("setup",[],t,o):Bu(o),process.exitCode=o.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function ZR(e,t){let{projectRoot:n,config:i}=_e(),r=he(n,i),o=Mu({files:ek(n),watchEnabled:Pe(i).enabled,readiness:r}),s=r.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=oo(r.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 qu([...s,...a]):new Set([...tk(o.actions),...s.map(g=>g.id)]);l&&nk(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:r.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 ek(e){return{agentsMd:we(ft(e,"AGENTS.md")),claudeMd:we(ft(e,"CLAUDE.md")),codexHooks:we(ft(e,".codex","hooks.json")),claudeSettings:we(ft(e,".claude","settings.local.json"))}}function tk(e){return new Set([...e.filter(t=>t.recommended).map(t=>t.id),"install-agent-skills","install-ast-parsers"])}function nk(e,t){console.log(""),console.log("Selected setup changes:");for(let n of["repository","checkout","user"]){let i=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"}): ${i.length>0?i.join(", "):"none"}`)}}function Op(e){let t=G(e),n=X(),i=Hu(n,{force:b(t,"force"),dryRun:b(t,"dryRun")});if(b(t,"dryRun")){console.log(i.content);return}if(i.skipped){console.log(`skip: ${i.path} \u2014 ${i.reason}`);return}console.log(`done: ${i.path}`)}function Fp(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=Uu({projectRoot:X(),global:b(t,"global"),project:b(t,"project"),dryRun:b(t,"dryRun")});if(b(t,"json")){E("uninstall",[],t,n);return}let i=n.dryRun?"would ":"";if(n.global){for(let o of n.global.removed)console.log(` ${i}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(` ${i}remove: ${o}`);for(let o of n.project.agentSetup.removed)console.log(` ${i}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 Np(e){let t=G(e),n=X(),i=fe(n),r=J(t,"debounce"),o=J(t,"cooldown"),s=J(t,"gitPoll"),a=J(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",r,!1],["--cooldown",o,!0],["--git-poll",s,!1],["--idle-timeout",a,!0]].find(([,k,O])=>k!==void 0&&(!Number.isInteger(k)||(O?Number(k)<0:Number(k)<=0)));if(f){console.error(`error: ${f[0]} requires ${f[2]?"a non-negative":"a positive"} integer.`),process.exitCode=1;return}let g={...r===void 0?{}:{debounceMs:r},...o===void 0?{}:{cooldownMs:o},...s===void 0?{}:{gitPollMs:s},...a===void 0?{}:{idleTimeoutMs:a}};r&&((i.watch??={}).debounceMs=r),o!==void 0&&((i.watch??={}).cooldownMs=o),s&&((i.watch??={}).gitPollMs=s),a!==void 0&&((i.watch??={}).idleTimeoutMs=a);let h=Pe(i);i.watch=h;let y=Fe(n,i),S={projectRoot:n,cacheDir:y.cacheDir,cliVersion:Me,watchOverrides:g};if(l){let k=Mp(Zi(S),h.enabled);u?E("watch",[],t,k):_p(k);return}if(d){try{let k=Ic(S);u?E("watch",[],t,k):console.log(k.disposition==="stopped"?`Stopped watch service${k.pid?` (pid ${k.pid})`:""}.`:"Watch service is already stopped.")}catch(k){console.error(`error: ${k instanceof Error?k.message:String(k)}`),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 k=Bn(S);u?E("watch",[],t,k):console.log(`${k.disposition==="started"?"Started":"Reused"} watch service for ${n} (pid ${k.state.pid}).`)}catch(k){console.error(`error: ${k instanceof Error?k.message:String(k)}`),process.exitCode=1}return}let v=jc(ft(Ci(y.dbPath),ss),n);if(!v.acquired){console.error(v.message),process.exitCode=1;return}let w=new vi({projectRoot:n,config:i,languages:i.languages,onStatus:k=>{process.stdout.write(`\r\x1B[K${Ki(k)}`)},onReindexComplete:k=>(console.log(`
|
|
398
|
+
Reindex complete in ${(k/1e3).toFixed(1)}s`),Te(n,i,y).state==="fresh"),onRefreshSuppressed:k=>{sd(y.dbPath,k),console.log(`
|
|
399
|
+
Skipped redundant refresh; the completed index already includes the queued changes.`)},onError:k=>{console.error(`
|
|
400
|
+
Watch error: ${k.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.
|
|
401
|
+
`),w.start(),process.on("SIGINT",()=>{w.stop(),v.release(),console.log(`
|
|
402
|
+
Stopped.`),process.exit(0)}),process.once("exit",v.release)}function Mp(e,t=!0){let{classification:n}=e;switch(n.kind){case"stopped":return e.lockIsLive&&e.lock?{enabled:t,state:"running",mode:"foreground-or-starting",pid:e.lock.pid,projectRoot:e.identity.projectRoot,worktreeId:e.identity.worktreeId,startedAt:e.lock.startedAt}:{enabled:t,state:"stopped",mode:"none"};case"live":return{enabled:t,state:"running",mode:"daemon",pid:n.state.pid,projectRoot:n.state.projectRoot,worktreeId:n.state.worktreeId,startedAt:n.state.startedAt,heartbeatAt:n.state.heartbeatAt,lastActivityAt:n.state.lastActivityAt,idleDeadlineAt:n.state.idleDeadlineAt,watcher:n.state.watcher,indexGeneration:n.state.indexGeneration,lastRefresh:n.state.lastRefresh,lastError:n.state.lastError,reindexActivity:n.state.reindexActivity,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};case"stale":case"incompatible":return{enabled:t,state:n.kind,mode:"daemon",reason:n.reason,pid:n.state.pid,projectRoot:n.state.projectRoot,worktreeId:n.state.worktreeId,heartbeatAt:n.state.heartbeatAt,watcher:n.state.watcher,indexGeneration:n.state.indexGeneration,lastRefresh:n.state.lastRefresh,lastError:n.state.lastError,reindexActivity:n.state.reindexActivity,typescriptSemantic:n.state.typescriptSemantic,typescriptIndex:n.state.typescriptIndex};default:return ik(n)}}function _p(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: ${Ki(e.watcher)}`),"indexGeneration"in e&&e.indexGeneration&&console.log(`Index generation: ${e.indexGeneration.slice(0,12)}`),"idleDeadlineAt"in e&&e.idleDeadlineAt&&console.log(`Idle exit: ${e.idleDeadlineAt}`),"reason"in e&&console.log(`Reason: ${e.reason}`),"lastError"in e&&e.lastError&&console.log(`Last error: ${e.lastError.message}`),"reindexActivity"in e&&e.reindexActivity){let n=e.reindexActivity;console.log(`Reindex activity (24h): ${n.runs} run(s) (${n.rebuilt} rebuilt, ${n.reused} reused, ${n.failed} failed), ${n.suppressed} redundant refresh(es) suppressed, ${Be(n.estimatedLogicalOutputBytes)} estimated logical output`)}if("typescriptSemantic"in e&&e.typescriptSemantic){let n=e.typescriptSemantic;console.log(`TypeScript semantics: ${n.state} (${n.projectsCreated} Projects, ${n.requests} requests)`)}if("typescriptIndex"in e&&e.typescriptIndex){let n=e.typescriptIndex;console.log(`TypeScript index: ${n.state} (${n.initializations} warmups, ${n.programUpdates} updates, ${n.requests} requests)`)}}function ik(e){throw new Error(`Unhandled watch service classification: ${JSON.stringify(e)}`)}function Bp(e){let t=G(e),{report:n}=Ap("status"),i=Pe(fe(n.projectRoot)).enabled,r=Mp(Zi({projectRoot:n.projectRoot,cacheDir:Ci(n.configuredDbPath),cliVersion:Me}),i),o=Hl(n.dbPath),s=st(n.dbPath,n.freshness.metaPath),a=En(n.projectRoot,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION);if(b(t,"json")){E("status",[],t,{...n,affectedSetShadow:o,sqliteGeneration:s,rustSemanticSession:a,watchService:r,stats:uo(n.exists)});return}ok(n,{affectedSetShadow:o,capabilities:b(t,"capabilities"),sqliteGeneration:s,rustSemanticSession:a,watchService:r})}function rk(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(i=>!i.runnable))console.log(` MISSING ${n.language}: ${n.note??n.binaryLabel}`);console.log(` Freshness: ${e.freshness.state}${e.freshness.remedy?` (${e.freshness.remedy})`:""}`),fo(e.capabilities)}function ok(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 qp(e.readiness)){let i=n.available?"available":n.dependencyAvailable?"fallback":"unavailable",r=n.language==="typescript"?"TS sem:":`${n.language} sem:`;console.log(`${r.padEnd(9)}${i}${Vp(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: ${lk(e.freshness.lastRefresh)}`),_p(t.watchService),sk(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"),ak(t.sqliteGeneration),console.log(`Shadow: ${Ul(t.affectedSetShadow)}`),console.log(`Latest: ${t.affectedSetShadow.latestPath}`),dk(e.exists),t.capabilities&&(console.log(""),fo(e.capabilities))}function sk(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), ${Be(e.generationBytes)}`),e.reason&&console.log(`Share why: ${e.reason}`),console.log(`Share GC: ${e.protectedGenerations} protected, ${e.unreferencedGenerations} unreferenced (${Be(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), ${Be(e.cleanup.deletedBytes??0)} removed`)}function ak(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",i=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(r=>r!==null).join(", "):"no publication metrics";console.log(`DB gen: ${e.state} ${e.generation.currentGeneration.slice(0,12)} (${n}; ${i})`),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 qp(e){return e.semantics?e.semantics:e.semantic?[e.semantic]:[]}function ck(e){return e.language==="typescript"?"ts-morph":"rust-analyzer"}function Vp(e){return e.tsconfigPaths&&e.tsconfigPaths.length>1?` (${e.tsconfigPaths.length} tsconfigs)`:e.tsconfigPath?` (${e.tsconfigPath})`:e.resolvedBinary?` (${e.resolvedBinary})`:""}function lk(e){let t=(e.durationMs/1e3).toFixed(1),n=e.trigger.detail?` (${e.trigger.detail})`:"",i=e.error?`: ${e.error}`:"";return`${e.result} by ${e.trigger.kind}${n} in ${t}s at ${e.completedAt}${i}`}function uo(e){if(e)return le(t=>{let n=xt(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function dk(e){e&&le(t=>{let n=xt(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${Be(n.indexSizeBytes)}`),n.lastBuilt){let i=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${i}s ago`)}})}function fo(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(`
|
|
403
|
+
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 un(e){return{...e,options:T(e.options)}}function je({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:r,toJson:o,coverage:s,agentResult:a,after:c,...l}){let d=un(l);return{...d,renderShape:"list",handler:Sc({commandName:d.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:r,toJson:o,coverage:s,agentResult:a,after:c})}}function Pi({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:r,toJson:o,coverage:s,agentResult:a,after:c,headers:l,dashWidths:d,...u}){let m=un(u);return{...m,renderShape:"table",handler:vc({commandName:m.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:r,toJson:o,coverage:s,agentResult:a,after:c,headers:l,dashWidths:d})}}function Wp({query:e,format:t,emptyMessage:n,heuristicLabel:i,before:r,toJson:o,coverage:s,agentResult:a,after:c,key:l,...d}){let u=un(d);return{...u,renderShape:"grouped-by-file",handler:xc({commandName:u.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,before:r,toJson:o,coverage:s,agentResult:a,after:c,key:l})}}function Hp({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:r,toJson:o,coverage:s,agentResult:a,after:c,...l}){let d=un(l);return{...d,renderShape:"sectioned-report",handler:Rc({commandName:d.id,query:e,emptyMessage:t,heuristicLabel:n,before:r,sections:i,toJson:o,coverage:s,agentResult:a,after:c})}}function Ti({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:r,toJson:o,coverage:s,agentResult:a,after:c,...l}){let d=un(l);return{...d,budget:d.budget??"semantic",renderShape:"sectioned-report",handler:kc(d.id,{commandName:d.id,query:e,emptyMessage:t,heuristicLabel:n,before:r,sections:i,toJson:o,coverage:s,agentResult:a,after:c})}}import{existsSync as Vk,mkdirSync as Wk,writeFileSync as Hk}from"fs";import{dirname as Uk,relative as Gk}from"path";import{existsSync as Ke,readdirSync as hk,readFileSync as gt}from"fs";import{basename as yk,dirname as Yp,isAbsolute as Xp,join as bk,relative as Sk,resolve as pn,sep as vk}from"path";import{spawnSync as pk}from"child_process";import{dirname as mk}from"path";function Gp(e){let n=(e.spawnSync??pk)("java",["-cp",e.jarPath,"tla2sany.xml.XMLExporter","-o",e.specPath],{encoding:"utf8",cwd:mk(e.specPath),maxBuffer:1024*1024*32});if(n.status!==0)return null;let i=n.stdout??"";return i.includes("<?xml")?i:null}function Jp(e){let t=gk(e),n=new Map,i=new Map,r=[],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?i.set(a.uid,a.uniquename):a.type==="UserDefinedOpKind"&&a.uniquename&&(r.push(a),o.set(a.uid,a));let s=[];for(let a of r){let c=zp(a.block,n,i,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:r.map(a=>a.uniquename).sort(),actions:s}}var fk=8;function gk(e){let t=[],n=/<entry>\s*<UID>(\d+)<\/UID>\s*<(\w+)>/g;for(let i of e.matchAll(n)){let r=i.index,o=e.indexOf("</entry>",r),s=e.slice(r,o<0?e.length:o),a=go(s,"uniquename"),c=go(s,"kind"),l=go(s,"filename");t.push({uid:i[1],type:i[2],uniquename:a===null?null:Up(a),kind:c===null?null:Number.parseInt(c,10),filename:l===null?null:Up(l),block:s})}return t}function zp(e,t,n,i,r,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=i.get(m);if(f&&s<fk&&!o.has(f.uid)&&f.filename===r){let g=zp(f.block,t,n,i,r,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 go(e,t){let n=e.match(new RegExp(`<${t}>([^<]*)</${t}>`));return n?n[1]:null}function Up(e){return e.replaceAll(""",'"').replaceAll("'","'").replaceAll("<","<").replaceAll(">",">").replaceAll("&","&")}var Zp=["update","insert","delete"],em=["select","query","findFirst","findMany"],ho=new Set([...Zp,...em]);function yo(e){let t=e.methods&&e.methods.length>0?e.methods:[...ho],n=new Set(Zp),i=new Set(em);return{write:t.filter(r=>n.has(r)),read:t.filter(r=>i.has(r))}}var xk=/^(.*)@L(\d+)-L(\d+)$/;function bo(e){let t=e.match(xk);if(!t)return{ref:e};let n=t[1],i=Number.parseInt(t[2],10),r=Number.parseInt(t[3],10);return n?i<1?{error:`codeRef "${e}" line window must start at line 1 or later`}:r<i?{error:`codeRef "${e}" line window end (L${r}) is before its start (L${i})`}:{ref:n,window:{startLine:i,endLine:r}}:{error:`codeRef "${e}" has a line window but no referent before @L${t[2]}-L${t[3]}`}}var Rk=new Set(["auto","sany","tlc","apalache","none"]),Ei=/^[A-Za-z_][A-Za-z0-9_]*$/;function tm(e){return Rk.has(e)}function ji(e,t){let n=[],i=pe(e,t);if(!i)return{errors:[`map path escapes project root: ${t}`]};if(!Ke(i))return{errors:[`map file not found: ${t}`]};let r;try{r=JSON.parse(gt(i,"utf8"))}catch(s){return{errors:[`map file is not valid JSON: ${s instanceof Error?s.message:String(s)}`]}}let o=kk(r,n);return o?{loaded:{contract:o,mapPath:i,mapDir:Yp(i)},errors:n}:{errors:n}}function pe(e,t){if(!t)return null;let n=Xp(t)?pn(t):pn(e,t);return me(e,n)?n:null}function nm(e,t,n){if(!n)return null;if(Xp(n)){let s=pn(n);return me(e,s)?s:null}let i=pn(e,n);if(me(e,i)&&Ke(i))return i;let r=pn(t,n);if(me(e,r)&&Ke(r))return r;let o=me(e,i)?i:r;return me(e,o)?o:null}function im(e,t){let n=pe(e,t);if(!n||!Ke(n))return null;let i=gt(n,"utf8");return{path:n,modelParse:"regex-fallback",text:i,variables:Nk(i),operators:Mk(i),actions:[]}}function rm(e,t,n){let i=pe(e,t);if(!i||!Ke(i))return null;let r=gt(i,"utf8"),o=Jp(n);return{path:i,modelParse:"sany",text:r,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(!Ke(n))return{steps:[],errors:[`trace file not found: ${t}`]};try{let i=JSON.parse(gt(n,"utf8")),r=Array.isArray(i)?i:V(i)&&Array.isArray(i.steps)?i.steps:null;if(!r)return{steps:[],errors:["trace file must be an array or an object with a steps array"]};let o=[],s=[];for(let[a,c]of r.entries()){if(!V(c)||typeof c.action!="string"){s.push(`trace step ${a} must include an action string`);continue}o.push({action:c.action,before:V(c.before)?c.before:void 0,after:V(c.after)?c.after:void 0,code:typeof c.code=="string"?c.code:void 0})}return{steps:o,errors:s}}catch(i){let r=i instanceof Error?i.message:String(i);return{steps:[],errors:[`trace file is not valid JSON: ${r}`]}}}function vo(e,t){let n=new Set,i=[];for(let r of t){let o=pe(e,r)??r;n.has(o)||(n.add(o),i.push(r))}return i}function kk(e,t){if(!V(e))return t.push("map file must contain a JSON object"),null;let n=Ik(e.variables,t);Tk(n,t);let i=Ok(e.actions,n,t),r=wk(e.init,t);Ck(r,i,t);let o={module:Qp(e.module,"module",t),config:Qp(e.config,"config",t),scope:z(e.scope)??[],variables:n,actions:i,...r?{init:r}:{},invariants:z(e.invariants)??[],traces:z(e.traces)??[],unmappedWriteScope:Pk(e.unmappedWriteScope,t)};return Bk(e.scope,t),t.length===0?o:null}function wk(e,t){if(e===void 0)return;if(!V(e)){t.push("init must be an object when present");return}let n=z(e.codeRefs);if(!n||n.length===0){t.push("init.codeRefs must name at least one TypeScript referent");return}let i=$k(e.waive,t);return{codeRefs:n,...i?{waive:i}:{}}}function $k(e,t){if(e===void 0)return;if(!V(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 Ck(e,t,n){if(!e)return;let i=new Set(e.codeRefs),r=new Set;for(let o of Object.values(t))for(let s of o.code)i.has(s)&&r.add(s);r.size>0&&n.push(`init.codeRefs overlaps action code referents: ${[...r].sort().join(", ")} \u2014 a referent cannot be both Init and an action`)}function Pk(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 Tk(e,t){Ii(e,t,"alias",n=>n.aliases),Ii(e,t,"resource path",n=>n.resource?[n.resource.path]:[]),Ii(e,t,"statement pattern",n=>n.statements?n.statements.map(i=>i.pattern):[]),Ii(e,t,"ORM table/method",n=>(n.ormCalls??[]).flatMap(i=>{let{write:r,read:o}=yo(i);return[...r,...o].map(s=>`${i.table}:${s}`)}))}function Ii(e,t,n,i){let r=new Map;for(let[o,s]of Object.entries(e))for(let a of i(s)){let c=r.get(a);c?c.push(o):r.set(a,[o])}for(let[o,s]of r)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 Ik(e,t){if(!V(e))return t.push("variables must be an object keyed by TLA+ variable name"),{};let n={};for(let[i,r]of Object.entries(e)){if(!Ei.test(i)){t.push(`invalid TLA+ variable name: ${i}`);continue}if(!V(r)){t.push(`variables.${i} must be an object`);continue}let o=sm(r.code);if(!o||o.length===0){t.push(`variables.${i}.code must name at least one TypeScript referent`);continue}let s=z(r.aliases)??[],a=jk(r.resource,i,t),c=Ak(r.statements,i,t),l=Lk(r.ormCalls,i,t),d=Dk(r.waive,i,t),u=Ek(r.selfAlias,i,t),m=u?[...new Set([i,...s])]:[...new Set(s)];u===!1&&m.length===0&&!a&&!c&&!l&&!d&&t.push(`variables.${i}.selfAlias is false but no aliases, resource, statements, ormCalls, or waive are set \u2014 ${i} would be unattributable; add an explicit alias, bind resource/statements/ormCalls, or add variables.${i}.waive with a reason`),n[i]={code:o,aliases:m,projection:typeof r.projection=="string"?r.projection:void 0,...a?{resource:a}:{},...c?{statements:c}:{},...l?{ormCalls:l}:{},...d?{waive:d}:{},...u===!1?{selfAlias:!1}:{}}}return n}function Ek(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 jk(e,t,n){if(e===void 0)return;if(!V(e)){n.push(`variables.${t}.resource must be an object when present`);return}let i=typeof e.path=="string"?e.path.trim():"";if(!i){n.push(`variables.${t}.resource.path must be a non-empty string`);return}return{path:i}}function Ak(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 i=[];return e.forEach((r,o)=>{if(!V(r)){n.push(`variables.${t}.statements[${o}] must be an object`);return}let s=typeof r.pattern=="string"?r.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}i.push({pattern:s})}),i.length>0?i:void 0}function Lk(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 i=[];return e.forEach((r,o)=>{if(!V(r)){n.push(`variables.${t}.ormCalls[${o}] must be an object`);return}let s=typeof r.table=="string"?r.table.trim():"";if(!s){n.push(`variables.${t}.ormCalls[${o}].table must be a non-empty string`);return}if(r.methods===void 0){i.push({table:s});return}let a=z(r.methods);if(!a){n.push(`variables.${t}.ormCalls[${o}].methods must be an array of strings when present`);return}let c=a.filter(l=>!ho.has(l));if(c.length>0){n.push(`variables.${t}.ormCalls[${o}].methods contains unrecognized name(s): ${c.join(", ")} \u2014 must be one of ${[...ho].join(", ")}`);return}i.push(a.length>0?{table:s,methods:a}:{table:s})}),i.length>0?i:void 0}function Dk(e,t,n){if(e===void 0)return;if(!V(e)){n.push(`variables.${t}.waive must be an object when present`);return}let i=typeof e.reason=="string"?e.reason.trim():"";if(!i){n.push(`variables.${t}.waive.reason must be a non-empty string`);return}return{reason:i}}function Ok(e,t,n){if(!V(e))return n.push("actions must be an object keyed by TLA+ action name"),{};let i=new Set(Object.keys(t)),r={};for(let[o,s]of Object.entries(e)){if(!Ei.test(o)){n.push(`invalid TLA+ action name: ${o}`);continue}if(!V(s)){n.push(`actions.${o} must be an object`);continue}let a=sm(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=bo(m);"error"in f&&n.push(`actions.${o}.code: ${f.error}`)}let c=z(s.reads)??[],l=z(s.writes)??[],d=z(s.calls)??[];for(let m of[...c,...l])i.has(m)||n.push(`actions.${o} references unknown variable: ${m}`);let u=Fk(s.waive,s.allowUnknown===!0,c,l,i,o,n);r[o]={code:a,reads:c,writes:l,calls:d,...u?{waive:u}:{}}}return r}function Fk(e,t,n,i,r,o,s){if(V(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=z(e.reads)??[],l=z(e.writes)??[];return c.length===0&&l.length===0&&s.push(`actions.${o}.waive must list reads or writes`),Kp(o,"reads",c,r,s),Kp(o,"writes",l,r,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(i)],reason:"legacy allowUnknown",legacy:!0}}function Kp(e,t,n,i,r){for(let o of n)i.has(o)||r.push(`actions.${e}.waive.${t} references unknown variable: ${o}`)}function Nk(e){let t=new Set;for(let n of e.matchAll(/^\s*VARIABLES?\s+([^\n]+)/gm)){let i=n[1]??"";for(let r of i.split(",")){let o=r.trim();Ei.test(o)&&t.add(o)}}return[...t].sort()}function Mk(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 _k=new Set(["ACTION_CONSTRAINT","ACTION_CONSTRAINTS","ALIAS","CHECK_DEADLOCK","CONSTANT","CONSTANTS","CONSTRAINT","CONSTRAINTS","INIT","INVARIANT","INVARIANTS","NEXT","POSTCONDITION","PROPERTIES","PROPERTY","SPECIFICATION","SYMMETRY","VIEW"]);function om(e){if(!e||!Ke(e))return[];let t=gt(e,"utf8").replace(/\(\*[\s\S]*?\*\)/g," ").replace(/\\\*[^\n]*/g," "),n=new Set,i=!1;for(let r of t.split(/[\s,]+/))if(r){if(_k.has(r)){i=r==="INVARIANT"||r==="INVARIANTS";continue}i&&Ei.test(r)&&n.add(r)}return[...n].sort()}function Qp(e,t,n){if(e!==void 0){if(typeof e=="string")return e;n.push(`${t} must be a string when present`)}}function sm(e){return typeof e=="string"?[e]:z(e)}function Bk(e,t){e!==void 0&&(z(e)||t.push("scope must be an array of strings when present"))}function Ai(e){return`${e.replace(/\.tla$/i,"")}.scip-tla.json`}var qk=/^-{4,}\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*-{4,}/m;function am(e,t){if(!Ke(t))return{status:"none"};let i=gt(t,"utf8").match(qk)?.[1],r=Sk(e,t).split(vk).join("/"),o=yk(t),s=new Set([i,r,o,o.replace(/\.tla$/i,"")].filter(d=>!!d)),a=Yp(t);if(!Ke(a))return{status:"none"};let c=[];for(let d of hk(a)){if(!d.endsWith(".scip-tla.json"))continue;let u=bk(a,d),m;try{m=JSON.parse(gt(u,"utf8"))}catch{continue}V(m)&&typeof m.module=="string"&&s.has(m.module)&&c.push(u)}c.sort();let l=i??r;return c.length===0?{status:"none"}:c.length>1?{status:"ambiguous",candidates:c,moduleName:l}:{status:"found",mapPath:c[0],moduleName:l}}function Li(e,t,n,i,r={count:e.length,loc:i}){let o=r.count===e.length&&r.loc===i?`${e.length}, ${i} LOC`:`${e.length} of ${r.count}, ${i} of ${r.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 xo=20,cm=Q("dead",({db:e,args:t,opts:n,budget:i})=>{let r={scope:W(t,0)||void 0,minLoc:P(n,"minLoc",1),includeTests:b(n,"includeTests"),skipBarrels:b(n,"skipBarrels"),includeMembers:b(n,"includeMembers"),scanLimit:i.scanLimit,semantic:i.semantic},o=ws(e,r),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),v=b(n,"full"),w=v?m:m.slice(0,xo),k=v?f:f.slice(0,xo),O=v?g:g.slice(0,xo),q=w.reduce((N,H)=>N+H.loc,0),K=k.reduce((N,H)=>N+H.loc,0),I=O.reduce((N,H)=>N+H.loc,0),F={total:m.length+f.length+g.length,deadCode:m.length,fileInternal:f.length,implicitUsage:g.length,loc:h+y+S};if(b(n,"json")){E("dead",t,n,{...o,shown:{deadCode:m,fileInternal:f,implicitUsage:g},shownCounts:F,totals:{total:o.counts.total,deadCode:o.counts.deadCode,fileInternal:o.counts.fileInternal,implicitUsage:o.counts.implicitUsage,loc:o.counts.loc}},{analysisBudget:i.analysisBudget});return}if(m.length===0&&f.length===0&&g.length===0){j.empty("No matching dead-code symbols found.");return}m.length>0&&(Li(w,"DEAD CODE",` Zero references anywhere -- no cross-file callers AND no same-file uses.
|
|
404
|
+
Deletion candidates -- confirm with cleanup-plan --verify before deleting.`,q,{count:m.length,loc:h}),!v&&m.length>w.length&&console.log(`
|
|
405
|
+
Showing top ${w.length} by LOC. Re-run with --full for the remaining ${m.length-w.length}.`)),f.length>0&&(m.length>0&&console.log(""),Li(k,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
|
|
406
|
+
single-use helper, an abstraction-in-progress, or a callback registered
|
|
407
|
+
through a framework path that static analysis cannot trace (signal
|
|
408
|
+
handlers, event listeners, dependency injection). NOT necessarily dead \u2014
|
|
409
|
+
review case by case.`,K,{count:f.length,loc:y}),!v&&f.length>k.length&&console.log(`
|
|
410
|
+
Showing top ${k.length} by LOC. Re-run with --full for the remaining ${f.length-k.length}.`)),g.length>0&&((m.length>0||f.length>0)&&console.log(""),Li(O,"IMPLICIT USAGE",` Traits, macros, attributes, ABI exports, or reflection provide a
|
|
411
|
+
consumer that the static reference graph cannot trace. Investigation
|
|
412
|
+
signals only \u2014 not deletion candidates and not counted as dead code.`,I,{count:g.length,loc:S}),!v&&g.length>O.length&&console.log(`
|
|
413
|
+
Showing top ${O.length} by LOC. Re-run with --full for the remaining ${g.length-O.length}.`));let ee=[];l&&ee.push(`${m.length} dead code (${h} LOC)`),d&&ee.push(`${f.length} file-internal (${y} LOC)`),u&&ee.push(`${g.length} implicit usage (${S} LOC)`),console.log(`
|
|
414
|
+
\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 ${ee.join(" + ")}`)}),lm=ue("unused-imports",{query:({db:e,args:t,budget:n})=>Ts(e,L(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
|
|
415
|
+
${e.length} unused import(s)`)}),dm=wc("isolated",{query:({db:e,opts:t,budget:n})=>_s(e,{scope:$(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(`
|
|
416
|
+
${e.length} isolated symbol(s)`)}),um=Q("extract-candidates",({db:e,args:t,opts:n,budget:i})=>{let r=ta(e,{scope:$(n,"scope"),minLoc:P(n,"minLoc",10),minCallees:P(n,"minCallees",6),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(b(n,"json")){E("extract-candidates",t,n,r,{analysisBudget:i.analysisBudget});return}if(r.length===0)return j.empty("No extraction candidates found.");Ie("extraction candidates");for(let o of r){console.log(`
|
|
417
|
+
${_(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(`
|
|
418
|
+
${r.length} extraction candidate(s) found.`)}),pm=Q("locality-candidates",({db:e,args:t,opts:n,budget:i})=>{let r=na(e,{target:W(t,0)||void 0,scope:$(n,"scope"),minConsumers:P(n,"minConsumers",1),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(b(n,"json")){E("locality-candidates",t,n,r,{analysisBudget:i.analysisBudget});return}if(r.length===0)return j.empty("No locality candidates found.");Ie("locality candidates");for(let o of r){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?_(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
|
|
419
|
+
${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(`
|
|
420
|
+
${r.length} locality candidate(s) found.`)}),mm=ue("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>fa(e,{scope:$(t,"scope"),maxLoc:P(t,"maxLoc",15),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${_(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
|
|
421
|
+
Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
|
|
422
|
+
Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
|
|
423
|
+
${e.length} wrapper candidate(s).`)}),fm=ue("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>pa(e,{scope:$(t,"scope"),maxLoc:P(t,"maxLoc",15),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${_(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
|
|
424
|
+
Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
|
|
425
|
+
Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
|
|
426
|
+
Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
|
|
427
|
+
Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
|
|
428
|
+
${e.length} passthrough candidate(s).`)}),gm=ue("stale-abstractions",{query:({db:e,opts:t,budget:n})=>ma(e,{scope:$(t,"scope"),minLoc:P(t,"minLoc",3),limit:D(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}] ${_(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
|
|
429
|
+
${e.reason}
|
|
430
|
+
Kind: ${e.stalenessKind}; tier: ${e.actionTier}
|
|
431
|
+
Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
|
|
432
|
+
${e.length} stale abstraction(s).`)}),hm=_n("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>Ea(e,{scope:$(t,"scope"),minLoc:P(t,"minLoc",10),limit:D(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]}),ym=ve("similar",{query:({db:e,args:t,opts:n,budget:i})=>{if(b(n,"plan")){let o=W(t,0),s=W(t,1);if(!o||!s)throw new Error("similar --plan requires two symbols: similar <symbol1> <symbol2> --plan");return{mode:"plan",result:Us(e,o,s,{scanLimit:i.scanLimit,semantic:i.semantic})}}let r=W(t,0);return r?{mode:"target",rows:Hs(e,r,{minSimilarity:P(n,"minSimilarity",.4),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic})}:{mode:"all",rows:Gs(e,{minSimilarity:P(n,"minSimilarity",.4),limit:D(n,"limit",20),scope:$(n,"scope"),minCallees:P(n,"minCallees",4),crossFileOnly:b(n,"crossFileOnly"),scanLimit:i.scanLimit,semantic:i.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(`
|
|
433
|
+
${Math.round(t.similarity*100)}% ${n}
|
|
434
|
+
`),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}
|
|
435
|
+
`),console.log(` Shared evidence (${t.sharedEvidence.length}):`);for(let i of t.sharedEvidence)console.log(` ${i}`);if(t.uniqueToA.length>0){console.log(`
|
|
436
|
+
Unique to A (${t.uniqueToA.length}):`);for(let i of t.uniqueToA)console.log(` ${i}`)}if(t.uniqueToB.length>0){console.log(`
|
|
437
|
+
Unique to B (${t.uniqueToB.length}):`);for(let i of t.uniqueToB)console.log(` ${i}`)}console.log(`
|
|
438
|
+
Strategy: ${t.consolidationStrategy}`);return}if(e.mode==="target"){j.list(e.rows,t=>{let n=t.similarityBasis??"callees",i=n==="source-tokens"?"Shared source tokens":"Shared callees",r=n==="source-tokens"?"Only tokens in":"Only in",o=[`
|
|
439
|
+
${Math.round(t.similarity*100)}% similar:`,` A: ${t.shortNameA} (${t.fileA})`,` B: ${t.shortNameB} (${t.fileB})`,` Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})`,` Recommendation: ${t.recommendation}`,` ${i}: ${t.sharedCallees.join(", ")}`];return t.evidenceClassReasons.length&&o.push(` Evidence reasons: ${t.evidenceClassReasons.join("; ")}`),t.uniqueToA.length&&o.push(` ${r} A: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&o.push(` ${r} B: ${t.uniqueToB.join(", ")}`),o.join(`
|
|
440
|
+
`)});return}j.list(e.rows,t=>`
|
|
441
|
+
${Math.round(t.similarity*100)}% similar:
|
|
442
|
+
A: ${t.shortNameA} (${t.fileA})
|
|
443
|
+
B: ${t.shortNameB} (${t.fileB})
|
|
444
|
+
Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})
|
|
445
|
+
Recommendation: ${t.recommendation}
|
|
446
|
+
`+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
|
|
447
|
+
`:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
|
|
448
|
+
${e.rows.length} similar pair(s) found.`)}}),bm=Ye({commandName:"similar-files",query:({db:e,args:t,opts:n})=>Js(e,{minSimilarity:P(n,"minSimilarity",.5),limit:D(n,"limit",20),scope:$(n,"scope"),minDeps:J(n,"minDeps"),filePattern:W(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{j.list(e,t=>{let n=[`
|
|
449
|
+
${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(`
|
|
450
|
+
`)}),console.log(`
|
|
451
|
+
${e.length} similar pair(s) found.`)}}),Sm=Ye({commandName:"similar-chains",query:({db:e,opts:t})=>ea(e,{minSimilarity:P(t,"minSimilarity",.5),limit:D(t,"limit",15),scope:$(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(`
|
|
452
|
+
\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 i of n.divergencePoints)console.log(` [${i.index}] ${i.nodeA} \u2194 ${i.nodeB}`)}console.log(`
|
|
453
|
+
${e.length} similar chain pair(s) found.`)}}),vm=ve("drift",{query:({db:e,args:t,opts:n,budget:i})=>ua(e,{scope:W(t,0),minDeviation:P(n,"minDeviation",5),semantic:i.semantic,includePatternDeviations:b(n,"patterns"),includeArchitecture:b(n,"architecture"),limit:D(n,"limit",50)}),emptyMessage:e=>e.results.length===0&&!e.architecture?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{if(console.log(""),j.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="architecture-violation"||t.kind==="layer-violation"?"ARCH":"UNIQUE",i=t.policyBasis?`, policy: ${t.policyBasis}`:"",r=[` [${n}] ${t.description}`,` Tier: ${t.actionTier}${i}`,` Recommendation: ${t.recommendation}`,` Evidence: ${t.evidenceReasons.join("; ")}`];return t.detail&&r.push(` ${t.detail}`),r.join(`
|
|
454
|
+
`)},t=>t.file),e.architecture){let t=e.architecture,n=t.edges.filter(i=>i.policyStatus==="undeclared").length;if(console.log(`
|
|
455
|
+
Architecture context: ${t.coverage.mappedFiles}/${t.coverage.totalFiles} file(s) mapped; ${t.policyCoverage.declaredRows}/${t.policyCoverage.totalBoundaries} dependency row(s) declared; ${n} undeclared boundary edge(s).`),t.reciprocalPairs.length>0){console.log(` Reciprocal pairs (${t.reciprocalPairs.length}):`);for(let i of t.reciprocalPairs)console.log(` ${i.boundaries[0]} <-> ${i.boundaries[1]}`)}if(t.cycles.length>0){console.log(` Connected boundary groups (${t.cycles.length}):`);for(let i of t.cycles){let r=i.violatesPolicy?" [violates requireAcyclic]":" [signal]";console.log(` { ${i.boundaries.join(", ")} }${r}`)}}}console.log(`
|
|
456
|
+
${e.unusedImports} unused import(s), ${e.architectureViolations} declared architecture violation(s), ${e.patternDeviations} pattern deviation(s)${e.totalResults?` \u2014 showing ${e.results.length} of ${e.totalResults} (use -n to change)`:""}`)}}),xm=ve("convergence",{query:({db:e,args:t,budget:n})=>_a(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(`
|
|
457
|
+
${Math.round(e.similarity*100)}% callee overlap
|
|
458
|
+
`),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)
|
|
459
|
+
`),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
|
|
460
|
+
Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
|
|
461
|
+
Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
|
|
462
|
+
Strategy: ${e.consolidationStrategy}`)}}}),Rm=ue("similar-signatures",{query:({db:e,opts:t,budget:n})=>Va(e,{scope:$(t,"scope"),minLoc:P(t,"minLoc",3),maxShapeFrequency:P(t,"maxShapeFrequency",12),limit:D(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.exactBody?", exact bodies":"",n=`
|
|
463
|
+
Signature: ${e.signature} (${e.functions.length} functions, ${e.locBand} LOC${t})`,i=e.functions.map(r=>` ${_(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
|
|
464
|
+
`);return`${n}
|
|
465
|
+
${i}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
|
|
466
|
+
${e.length} group(s) found.`)}),km=ue("duplicate-bodies",{query:({db:e,opts:t,budget:n})=>la(e,{scope:$(t,"scope"),maxLoc:P(t,"maxLoc",15),minLoc:P(t,"minLoc",3),limit:D(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
|
|
467
|
+
Body hash: ${e.hash} (${e.functions.length} functions)`,n=e.functions.map((i,r)=>` ${(r===0?"canonical":"duplicate").padEnd(9)} ${_(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
|
|
468
|
+
`);return`${t}
|
|
469
|
+
${n}`},emptyMessage:()=>"No exact duplicate function bodies found.",heuristicLabel:"duplicate body candidates",after:e=>console.log(`
|
|
470
|
+
${e.length} group(s) found.`)}),wm=ue("twin-drift",{query:({db:e,opts:t,budget:n})=>da(e,{scope:$(t,"scope"),minSimilarity:P(t,"minSimilarity",.3),includeHomonyms:b(t,"includeHomonyms"),limit:D(t,"limit",20),scanLimit:n.scanLimit}),format:e=>{let t=`
|
|
471
|
+
${e.leaf} (${e.relationship}, ${e.members.length} functions, ${Math.round(e.maxDivergence*100)}% divergence)`,n=e.members.map(r=>` ${_(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
|
|
472
|
+
`),i=e.firstDivergentTokens?`
|
|
473
|
+
first divergent tokens: ${e.firstDivergentTokens}`:"";return`${t}
|
|
474
|
+
${n}${i}`},emptyMessage:()=>"No divergent twin groups found.",heuristicLabel:"twin drift candidates",after:e=>console.log(`
|
|
475
|
+
${e.length} group(s) found.`)}),$m=ue("not-implemented",{query:({db:e,opts:t,budget:n})=>Ra(e,{scope:$(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${_(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.stubKind}, reachability: ${e.reachability}${e.callerFanIn>0?`, callers: ${e.callerFanIn}`:""})
|
|
476
|
+
${e.stubText}`,emptyMessage:()=>"No reachable placeholder stubs found.",heuristicLabel:"reachable placeholder stubs",after:e=>console.log(`
|
|
477
|
+
${e.length} reachable placeholder stub(s).`)}),Cm=ue("decorative-checkers",{query:({db:e,opts:t,budget:n})=>ka(e,{scope:$(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${_(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(`
|
|
478
|
+
${e.length} decorative checker candidate(s).`)}),Pm=Q("test-quality",({db:e,args:t,opts:n,budget:i})=>{let r=wa(e,{scope:$(n,"scope"),limit:D(n,"limit",30),scanLimit:i.scanLimit,rotDays:J(n,"rotDays")});if(b(n,"json")){E("test-quality",t,n,r,{analysisBudget:i.analysisBudget});return}if(Ie("test-quality findings"),r.assertionFree.length+r.skipped.length+r.mockEcho.length===0){j.empty("No test-quality findings.");return}r.assertionFree.length>0&&(console.log(`
|
|
479
|
+
ASSERTION-FREE (${r.assertionFree.length})`),j.list(r.assertionFree,s=>` ${_(s.file,s.startLine,s.endLine)} "${s.title}" (severity: ${s.severity})`)),r.skipped.length>0&&(console.log(`
|
|
480
|
+
SKIPPED (${r.skipped.length})`),j.list(r.skipped,s=>` ${s.file}:${s.startLine+1} "${s.title}" (${s.blockKind}.${s.skipKind}, age: ${s.ageDays??"unknown"}d, ${s.rot})`)),r.mockEcho.length>0&&(console.log(`
|
|
481
|
+
MOCK-ECHO (${r.mockEcho.length})`),j.list(r.mockEcho,s=>` ${_(s.file,s.startLine,s.endLine)} "${s.title}" (echoed: ${s.echoedValue})`)),console.log(`
|
|
482
|
+
${r.assertionFree.length} assertion-free, ${r.skipped.length} skipped, ${r.mockEcho.length} mock-echo.`)}),Tm=Ye({commandName:"twin-ab",query:({db:e,args:t,opts:n})=>{let i=L(t,0),r=L(t,1),o=$(n,"out")??va(i,r),s=pe(e.config.projectRoot,o);if(!s)throw new Error(`twin-ab output path escapes the project root: ${o}`);let a=xa(e,i,r,s);if(!a.ok)throw new Error(`twin-ab refused: ${a.reason}`);let c=Gk(e.config.projectRoot,s);if(!b(n,"force")&&Vk(s))throw new Error(`refusing to overwrite ${c} (pass --force to replace twin-ab output)`);return Wk(Uk(s),{recursive:!0}),Hk(s,a.testSource),{...a,outPath:c}},render:e=>{console.log(`
|
|
483
|
+
Wrote behavioral A/B scaffold: ${e.outPath}`),console.log(` A: ${e.a.shortName} (${_(e.a.file,e.a.startLine,e.a.startLine)})`),console.log(` B: ${e.b.shortName} (${_(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(`
|
|
484
|
+
Fill in the TODO input table, then run: npx vitest run ${e.outPath}`)},toJson:e=>e}),Im=Q("cleanup-plan",({db:e,args:t,opts:n,budget:i})=>{let r=Ui(e,{scope:$(n,"scope"),minLoc:P(n,"minLoc",1),maxDepth:P(n,"maxDepth",5),scanLimit:i.scanLimit}),o=X(),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(r.batches.length===0){if(a){E("cleanup-plan",t,n,r,{analysisBudget:i.analysisBudget});return}return j.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=sr(r),d=c?ir(o,r):void 0;if(a){E("cleanup-plan",t,n,{result:r,verification:d},{analysisBudget:i.analysisBudget});return}if(s){let u=ar(d,l);if(u.length>0){for(let f of u)console.error(`error: ${f}`);process.exitCode=1;return}let m=Hc(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), ${r.totalLoc} LOC.`),console.log(m);return}console.log(`Cleanup plan: ${r.totalSymbols} symbol(s), ${r.totalLoc} LOC across ${r.batches.length} batch(es).`),console.log(`Apply one batch at a time; run your typecheck between batches.
|
|
485
|
+
`);for(let u of r.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(r.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let u of r.blocked)console.log(` ${u.shortName} (${u.file}) blocked by ${u.blockingFiles.join(", ")}`)}if(d){if(console.log(`
|
|
486
|
+
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=Jk(d.checkers),m=zk(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}`)}}}),Em=Q("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 i=b(t,"all"),r=J(t,"batch");if(i===(r!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=Ui(e,{scope:$(t,"scope"),minLoc:P(t,"minLoc",1),maxDepth:P(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){j.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=sr(o,{all:i,batch:r});if(s.length===0){console.error(`error: No cleanup batch ${r} exists.`),process.exitCode=1;return}let a=X(),c=ir(a,o),l=ar(c,s,{allowDirty:b(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}or(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 Jk(e){return e.join(", ")}function zk(e){return e.some(t=>/clj-kondo|ruff|compileall/i.test(t))?" -- lint-level or syntax-level check, not a type proof":""}var jm=Q("recent-duplicates",({db:e,args:t,opts:n,budget:i})=>{let r=b(n,"full"),o=$a(e,{windowCommits:P(n,"window",100),minSimilarity:J(n,"minSimilarity"),limit:D(n,"limit",30),scope:$(n,"scope"),scanLimit:i.scanLimit,semantic:i.semantic,historyMode:r?"full":"bounded"});if(b(n,"json")){E("recent-duplicates",t,n,o,{analysisBudget:i.analysisBudget});return}if(!o.available)return j.empty("No git history available (not a repository, or git missing).");if(o.findings.length===0)return j.empty(`No recent re-implementations found (window: last ${o.windowCommits} commits).`);Ie("recent re-implementation candidates"),console.log(`Recent re-implementations (window: last ${o.windowCommits} commits):
|
|
487
|
+
`);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(`
|
|
488
|
+
${o.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),Am=de(({db:e,args:t,opts:n})=>{let i=b(n,"full"),r=ca(e,{doc:t[0]===void 0?void 0:L(t,0),limit:D(n,"limit",20),minCoupling:P(n,"minCoupling",3),includeSnapshotExcluded:i,historyMode:i?"full":"bounded"});if(b(n,"json")){E("doc-drift",t,n,r);return}if(!r.available)return j.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return j.empty(`No drifting docs found across ${r.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);Ie("doc drift candidates"),console.log(`Docs whose referenced or co-changed code moved on without them (${r.docsScanned} docs scanned, ${r.commitsAnalyzed} commits analyzed):
|
|
489
|
+
`);for(let o of r.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: ${Nn(u)}`)}}console.log(`
|
|
490
|
+
Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),Lm=ue("unused-params",{query:({db:e,opts:t,budget:n})=>ba(e,{scope:$(t,"scope"),limit:D(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${_(e.file,e.startLine,e.endLine)} ${e.shortName}
|
|
491
|
+
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(`
|
|
492
|
+
${e.length} function(s) with trailing unused parameters.`)});var Dm=ve("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>zs(e,{minSimilarity:P(n,"minSimilarity",.62),minTokens:P(n,"minTokens",8),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:W(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{j.list(e,t=>{let n=[`
|
|
493
|
+
${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(`
|
|
494
|
+
`)}),console.log(`
|
|
495
|
+
${e.length} duplicated React component pair(s) found.`)}}),Om=ve("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:i})=>Ks(e,{minSimilarity:P(n,"minSimilarity",.45),minSharedBehaviors:P(n,"minSharedBehaviors",6),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:W(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{j.list(e,t=>{let n=[`
|
|
496
|
+
${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(`
|
|
497
|
+
`)}),console.log(`
|
|
498
|
+
${e.length} React hook candidate pair(s) found.`)}}),Fm=ve("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:i})=>Qs(e,{minComponentLines:P(n,"minComponentLines",300),minFileLines:P(n,"minFileLines",800),minJsxTokens:P(n,"minJsxTokens",80),minBehaviorTokens:P(n,"minBehaviorTokens",40),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:W(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{j.list(e,t=>[`
|
|
499
|
+
${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(`
|
|
500
|
+
`)),console.log(`
|
|
501
|
+
${e.length} large React component(s) found.`)}}),Nm=ve("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>Ys(e,{minSimilarity:P(n,"minSimilarity",.62),minTokens:P(n,"minTokens",8),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:W(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{j.list(e,t=>{let n=[`
|
|
502
|
+
${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(`
|
|
503
|
+
`)}),console.log(`
|
|
504
|
+
${e.length} duplicated Vue component pair(s) found.`)}}),Mm=ve("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:i})=>Xs(e,{minSimilarity:P(n,"minSimilarity",.45),minSharedBehaviors:P(n,"minSharedBehaviors",6),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:W(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{j.list(e,t=>{let n=[`
|
|
505
|
+
${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(`
|
|
506
|
+
`)}),console.log(`
|
|
507
|
+
${e.length} Vue composable candidate pair(s) found.`)}}),_m=ve("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:i})=>Zs(e,{minTotalLines:b(n,"reviewThresholds")&&$c(n,"minTotalLines")==="default"?300:P(n,"minTotalLines",800),minTemplateLines:P(n,"minTemplateLines",300),minScriptLines:P(n,"minScriptLines",300),minStyleLines:P(n,"minStyleLines",500),limit:D(n,"limit",20),scope:$(n,"scope"),scanLimit:i.scanLimit,filePattern:W(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{j.list(e,t=>{let n=[`
|
|
508
|
+
${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(`
|
|
509
|
+
`)}),console.log(`
|
|
510
|
+
${e.length} large Vue view pressure file(s) found.`)}});function re(e){return{docs:C("Cleanup"),...e}}function Z({heuristicLabel:e,...t}){return re({...t,heuristic:{label:e}})}var Di=[re({id:"unused-params",command:"unused-params",agent:R("Which trailing parameters are never read by their bodies?","candidate parameters with callable and file identities",[],"bounded","repository"),description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:T([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings",x,30),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:C("Cleanup",["scip-query unused-params -s src/services"]),handler:Lm}),re({id:"cleanup-plan",command:"cleanup-plan",agent:R("What code can be deleted safely, and in what dependency order?","ordered cleanup batches, evidence, and optional verification outcomes",[],"bounded","repository"),description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",x,1),p("--max-depth <n>","Maximum cascade depth",x,5),p("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),p("--patch","With --verify, print the compiler-verified deletion patch to stdout"),p("--json","Output as JSON for programmatic consumption"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:C("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:Im}),re({id:"cleanup-apply",command:"cleanup-apply",agent:R("Can a compiler-verified cleanup batch be applied to this working tree?","applied files, deletions, verification, and refusal reasons",[],"bounded","repository"),description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",x,1),p("--max-depth <n>","Maximum cascade depth",x,5),p("--verified","Required: verify the selected cleanup batch before applying it"),p("--batch <n>","Apply one batch depth",x),p("--all","Apply every compiler-verified batch in the plan"),p("--force-dirty","Allow applying when plan files already have working-tree edits"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:C("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:Em}),re({id:"recent-duplicates",command:"recent-duplicates",agent:R("Did recent code reimplement established code?","recent and established symbol pairs with similarity evidence",[],"bounded","repository"),description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:T([p("--window <n>",'How many commits back counts as "recent"',x,100),p("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",ge),p("-n, --limit <n>","Maximum findings",x,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:C("Cleanup",["scip-query recent-duplicates --window 50"]),handler:jm}),re({id:"doc-drift",command:"doc-drift [doc]",agent:R("Which documentation may be stale relative to changing code?","document paths, coupled code subjects, and history evidence",["path"],"bounded","repository"),description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:T([p("-n, --limit <n>","Maximum docs to report",x,20),p("--min-coupling <n>","Minimum historical co-changes to track a subject",x,3),p("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:C("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:Am}),re({id:"dead",command:"dead [scope]",agent:R("Which symbols have no repository use or only file-internal use?","symbol identities, ranges, liveness classes, and evidence",["path"],"bounded","repository"),description:"Find repository-dead code, file-internal symbols, and implicit-usage signals",options:T([p("--min-loc <n>","Only show symbols >= N lines",x,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:C("Cleanup",["scip-query dead --min-loc 10"]),handler:cm}),re({id:"unused-imports",command:"unused-imports <file>",agent:R("Which imports in this file are unused?","import symbol identities and source ranges",["file"],"bounded"),description:"Find imports not referenced in the same file",options:T([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:lm}),re({id:"isolated",command:"isolated",agent:R("Which symbols are disconnected from the repository reference graph?","isolated symbol identities and files",[],"bounded","repository"),description:"Find completely orphaned symbols (no references at all)",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum lines of code",x,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:dm}),Z({id:"similar",command:"similar [symbol] [other]",agent:R("Which callable resembles this one, or how similar are these two?","symbol pairs, similarity scores, and shared evidence",["symbol","symbol"],"bounded","repository"),description:"Find heuristic function similarity candidates from callee fingerprints",options:T([p("--min-similarity <n>","Minimum weighted-cosine similarity (0-1)",ge,.4),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-callees <n>","Minimum callees to consider",x,4),p("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),p("--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:ym}),Z({id:"similar-files",command:"similar-files [file]",agent:R("Which files have similar callable structure?","file pairs with similarity scores and shared symbols",["file"],"bounded","repository"),description:"Find heuristic similar-file candidates from dependency profiles",options:T([p("--min-similarity <n>","Minimum Jaccard similarity (0-1)",ge,.5),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-deps <n>","Minimum dependencies to consider",x),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:bm}),Z({id:"react-component-duplicates",command:"react-component-duplicates [file]",agent:R("Which React components appear to duplicate one another?","component pairs with structural similarity evidence",["file"],"bounded","repository"),description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:T([p("--min-similarity <n>","Minimum JSX structure similarity (0-1)",ge,.62),p("--min-tokens <n>","Minimum structural tokens to consider",x,8),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Dm}),Z({id:"react-hook-candidates",command:"react-hook-candidates [file]",agent:R("Which repeated React logic could become a custom hook?","component groups and shared hook-shaped behavior",["file"],"bounded","repository"),description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:T([p("--min-similarity <n>","Minimum behavior similarity (0-1)",ge,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Om}),Z({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",agent:R("Which React components have evidence of being too large or overloaded?","component identities with size and responsibility pressure",["file"],"bounded","repository"),description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:T([p("--min-component-lines <n>","Minimum component lines",x,300),p("--min-file-lines <n>","Minimum file lines",x,800),p("--min-jsx-tokens <n>","Minimum JSX structure tokens",x,80),p("--min-behavior-tokens <n>","Minimum behavior tokens",x,40),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Fm}),Z({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",agent:R("Which Vue components appear to duplicate one another?","component pairs with structural similarity evidence",["file"],"bounded","repository"),description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:T([p("--min-similarity <n>","Minimum template similarity (0-1)",ge,.62),p("--min-tokens <n>","Minimum structural tokens to consider",x,8),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Nm}),Z({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",agent:R("Which repeated Vue logic could become a composable?","component groups and shared composable-shaped behavior",["file"],"bounded","repository"),description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:T([p("--min-similarity <n>","Minimum behavior similarity (0-1)",ge,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Mm}),Z({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",agent:R("Which Vue views have evidence of being too large or overloaded?","view identities with size and responsibility pressure",["file"],"bounded","repository"),description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:T([p("--min-total-lines <n>","Minimum total component lines",x,800),p("--min-template-lines <n>","Minimum template lines",x,300),p("--min-script-lines <n>","Minimum script lines",x,300),p("--min-style-lines <n>","Minimum style lines",x,500),p("--review-thresholds","Use lower review thresholds without changing health scoring"),p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:_m}),Z({id:"similar-chains",command:"similar-chains",agent:R("Which transitive chains of similar symbols suggest repeated designs?","similarity-connected symbol chains and scores",[],"bounded","repository"),description:"Find heuristic similar-chain candidates from dependency flows",options:T([p("--min-similarity <n>","Minimum chain similarity (0-1)",ge,.5),p("-n, --limit <n>","Number of results",x,15),p("-s, --scope <path>","Limit to files matching path"),p("--min-length <n>","Minimum chain length",x,3),p("--max-length <n>","Maximum chain length",x,8),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Sm}),Z({id:"extract-candidates",command:"extract-candidates",agent:R("Which cohesive code regions are strong extraction candidates?","symbol identities with cohesion, reuse, and extraction evidence",[],"bounded","repository"),description:"Find heuristic extraction candidates from isolated callee clusters",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum function LOC",x,10),p("--min-callees <n>","Minimum callees to analyze",x,6),p("-n, --limit <n>","Number of results",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:um}),Z({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",agent:R("Which definitions live far from most of their consumers?","symbols, current homes, consumer locality, and suggested homes",[["symbol","file"]],"bounded","repository"),description:"Find directory-locality and ancestry candidates from consumer ownership",options:T([p("-s, --scope <path>","Limit scan mode to files matching path"),p("--min-consumers <n>","Minimum consumers in scan mode",x,1),p("-n, --limit <n>","Number of results",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:C("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:pm}),Z({id:"drift",command:"drift [module]",agent:R("Where has a module or abstraction drifted across parallel implementations?","drifted symbol families, files, and evidence",["module"],"bounded","repository"),description:"Detect drift candidates: unused imports and declared architecture violations; pass --architecture for boundary context",options:T([p("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",Ve,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("--architecture","Include boundary coverage, undeclared edges, reciprocal pairs, and connected groups",void 0,!1),p("-n, --limit <n>","Number of results",x,50),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:vm}),Z({id:"wrapper-candidates",command:"wrapper-candidates",agent:R("Which callables are unnecessary forwarding wrappers?","wrapper identities, targets, and forwarding evidence",[],"bounded","repository"),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:T([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",x,15),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:mm}),Z({id:"passthrough-candidates",command:"passthrough-candidates",agent:R("Which parameters are passed through layers without local use?","parameter paths across call chains",[],"bounded","repository"),description:"Find heuristic passthrough candidates that forward to one callee",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",x,15),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:fm}),Z({id:"stale-abstractions",command:"stale-abstractions",agent:R("Which abstractions no longer earn their indirection?","abstraction identities with usage, change, and replacement evidence",[],"bounded","repository"),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:T([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",x,3),p("-n, --limit <n>","Number of results",x,30),p("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:gm}),Z({id:"complexity-hotspots",command:"complexity-hotspots",agent:R("Which symbols combine high complexity with high change pressure?","ranked symbols with complexity and churn evidence",[],"bounded","repository"),description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",x,10),p("-n, --limit <n>","Number of results",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:hm}),re({id:"convergence",command:"convergence <symbol1> <symbol2>",agent:R("How should these two similar symbols converge?","deprecated alias result for a two-symbol similarity plan",["symbol","symbol"],"bounded"),evidence:"heuristic",description:"Deprecated alias for similar <symbol1> <symbol2> --plan",options:T([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:xm}),Wp({id:"redundant-reexports",command:"redundant-reexports",agent:R("Which re-exports add no useful API boundary?","re-export sites, original definitions, and consumer evidence",[],"bounded","repository"),description:"Find barrel re-exports that nobody imports through",options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded analysis on large indexes")],docs:C("Cleanup"),query:({db:e,opts:t})=>Ba(e,{scope:$(t,"scope"),limit:D(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
|
|
511
|
+
barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
|
|
512
|
+
Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
|
|
513
|
+
Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
|
|
514
|
+
${e.length} redundant re-export(s).`)}),re({id:"duplicate-bodies",command:"duplicate-bodies",agent:R("Which callable bodies are exact duplicates?","callable groups with exact normalized-body identity",[],"bounded","repository"),description:"Find exact duplicate small-body candidates across files",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC per function body",x,15),p("--min-loc <n>","Minimum body LOC (excludes single-statement forwarding boilerplate)",x,3),p("-n, --limit <n>","Number of groups",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"duplicate body candidates"},renderShape:"list",handler:km}),re({id:"twin-drift",command:"twin-drift",agent:R("Which same-concept twin implementations have drifted?","twin symbol pairs, history, and divergence evidence",[],"bounded","repository"),description:"Twin drift candidates: same-name (or near-name) functions across files with diverged bodies",options:T([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",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"twin drift candidates"},evidence:"heuristic",renderShape:"list",handler:wm}),Z({id:"not-implemented",command:"not-implemented",agent:R("Which callables are placeholders rather than real implementations?","callable identities and placeholder evidence",[],"bounded","repository"),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:T([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"reachable placeholder stubs",budget:"candidate-scan",renderShape:"list",docs:C("Cleanup",["scip-query not-implemented -s src/services"]),handler:$m}),Z({id:"decorative-checkers",command:"decorative-checkers",agent:R("Which validation checks cannot meaningfully fail?","checker identities, call sites, and decorative behavior evidence",[],"bounded","repository"),description:"Decorative checker candidates: validate*/verify*/check*/assert*/is*/has* callables with no reachable failure exit anywhere in their body",options:T([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",x,30),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"decorative checker candidates",budget:"candidate-scan",renderShape:"list",docs:C("Cleanup",["scip-query decorative-checkers -s src/services"]),handler:Cm}),re({id:"test-quality",command:"test-quality",agent:R("Which tests have weak assertions or poor production-code reach?","test identities with assertion and reachability evidence",[],"bounded","repository"),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:T([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings per sub-check",x,30),p("--rot-days <n>","Skips older than this many days are reported as rot",x,60),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"test-quality findings"},renderShape:"custom",docs:C("Cleanup",["scip-query test-quality -s tests/queries"]),handler:Pm}),re({id:"twin-ab",command:"twin-ab <symbolA> <symbolB>",agent:R("How do these two twin implementations differ in structure and behavior?","side-by-side symbol evidence and divergence classification",["symbol","symbol"],"complete"),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:T([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:C("Cleanup",["scip-query twin-ab src/a.ts/escapeRegex src/b.ts/escapeRegExp"]),handler:Tm}),re({id:"similar-signatures",command:"similar-signatures",agent:R("Which callables have suspiciously similar signatures?","callable pairs with signature similarity evidence",[],"bounded","repository"),description:"Find functions with near-identical type signatures (same shape)",options:T([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC per function",x,3),p("--max-shape-frequency <n>","Suppress noisy signature shapes above this frequency unless bodies match exactly",x,12),p("-n, --limit <n>","Number of groups",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:Rm})];var Kk=de(({db:e,args:t,opts:n})=>{let i=xt(e);if(b(n,"json")){E("stats",t,n,i);return}console.log(`Documents: ${i.documents}`),console.log(`Symbols: ${i.symbols}`),console.log(`Definitions: ${i.definitions}`),console.log(`References: ${i.references}`),console.log(`Index size: ${Be(i.indexSizeBytes)}`),i.lastBuilt&&console.log(`Last built: ${i.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Bm=[{id:"stats",command:"stats",description:"Show index statistics",agent:R("How large and fresh is the current index?","document, symbol, definition, reference, size, and build-time totals",[],"complete","repository"),options:[yc()],renderShape:"custom",docs:C("Core"),handler:Kk}];var Qk=_n("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>Ms(e,{limit:D(t,"limit",20),scope:$(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."}),Yk=de(({db:e,args:t,opts:n})=>{let i=W(t,0),r=D(n,"limit",30);if(i){let c=Es(e,i);if(b(n,"json")){E("fan-in",t,n,{mode:"symbol",symbol:i,rows:c});return}if(c.length===0)return j.empty(`No fan-in for ${i}.`);j.list(c,l=>` ${String(l.count).padStart(4)} files ${l.name}`);return}let o=As(e,{limit:r,scope:$(n,"scope")});if(b(n,"json")){E("fan-in",t,n,{mode:"top",rows:o});return}let s=new Map;for(let c of o)s.set(c.name,(s.get(c.name)??0)+1);let a=new Set([...s].filter(([,c])=>c>1).map(([c])=>c));j.table(["files","symbol"],o.map(c=>` ${String(c.count).padStart(5)} ${c.name}${a.has(c.name)?` [${c.definedIn}]`:""}`))}),Xk=de(({db:e,args:t,opts:n})=>{let i=W(t,0),r=D(n,"limit",30);if(i){let s=js(e,i);if(b(n,"json")){E("fan-out",t,n,{mode:"file",file:i,rows:s});return}if(s.length===0)return j.empty(`No fan-out for ${i}.`);j.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=Ls(e,{limit:r,scope:$(n,"scope")});if(b(n,"json")){E("fan-out",t,n,{mode:"top",rows:o});return}j.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),Zk=de(({db:e,args:t,opts:n})=>{let i=W(t,0),r=W(t,1),o=D(n,"limit",20);if(i&&r){let a=Ds(e,i,r);if(b(n,"json")){E("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=Os(e,{limit:o,scope:$(n,"scope")});if(b(n,"json")){E("coupling",t,n,{mode:"top",rows:s});return}j.table(["tier","risk","shared","file1 \u2192 file2"],s.map(a=>` ${a.actionTier.padEnd(6)} ${a.couplingKind.padEnd(22)} ${String(a.sharedSymbols).padStart(6)} ${a.file1} \u2192 ${a.file2}`))}),ew=Ye({commandName:"cycles",query:({db:e,opts:t})=>Fs(e,{scope:$(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(i=>i.kind==="real"),n=e.cycles.filter(i=>i.kind==="module-hierarchy");for(let i=0;i<t.length;i++){console.log(`
|
|
515
|
+
Cycle ${i+1} (${t[i].path.length-1} files):`);for(let r=0;r<t[i].path.length;r++){let o=r<t[i].path.length-1?" \u2192":" (cycle)";console.log(` ${t[i].path[r]}${o}`)}}t.length===0?console.log("No real circular dependencies found."):console.log(`
|
|
516
|
+
${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.)`)}}),tw=Ye({commandName:"architecture",query:({db:e,opts:t})=>Ns(e,{scope:$(t,"scope")}),emptyMessage:e=>e.configured?void 0:"No architecture boundaries configured. Add architecture.boundaries to .scipquery.json.",render:e=>{if(console.log(`Mapped ${e.coverage.mappedFiles}/${e.coverage.totalFiles} indexed file(s) across ${e.boundaries.length} boundary(ies); ${e.policyCoverage.declaredRows}/${e.policyCoverage.totalBoundaries} dependency row(s) declared.`),e.policyCoverage.missingRows.length>0){let t=e.policyCoverage.requiresCompletePolicy?" [violates requireCompletePolicy]":"";console.log(`Missing dependency rows: ${e.policyCoverage.missingRows.join(", ")}${t}`)}if(e.coverage.unmappedFiles.length>0&&console.log(`Unmapped files: ${e.coverage.unmappedFiles.length}`),e.coverage.ambiguousFiles.length>0){console.log(`Ambiguous files: ${e.coverage.ambiguousFiles.length}`);for(let t of e.coverage.ambiguousFiles.slice(0,5))console.log(` ${t.file} -> ${t.boundaries.join(", ")}`)}if(e.forbiddenEdges.length>0){console.log(`
|
|
517
|
+
Forbidden boundary edges (${e.forbiddenEdges.length}):`);for(let t of e.forbiddenEdges){console.log(` ${t.from} -> ${t.to}: ${t.fileEdgeCount} file edge(s), ${t.importerCount} importer(s), ${t.importedFileCount} imported file(s)`);for(let n of t.examples)console.log(` ${n.fromFile} -> ${n.toFile}`)}}else console.log(`
|
|
518
|
+
No declared boundary violations found.`);if(e.staleAllowances.length>0){console.log(`
|
|
519
|
+
Stale dependency allowances (${e.staleAllowances.length}): declared but unused, so the policy is wider than the code requires.`);for(let t of e.staleAllowances)console.log(` ${t.from} -> ${t.to}`)}if(e.boundaryLimits.length>0){console.log(`
|
|
520
|
+
Boundaries over configured limits (${e.boundaryLimits.length}):`);for(let t of e.boundaryLimits)console.log(` ${t.boundary}: ${t.kind} ${t.observed} exceeds limit ${t.limit}`)}if(e.testBoundaryViolations.length>0){console.log(`
|
|
521
|
+
Test boundary violations (${e.testBoundaryViolations.length}): a test reaches further than the boundary of the code it covers is allowed to reach.`);for(let t of e.testBoundaryViolations.slice(0,20)){let n=t.ownerBoundary??"(no subject found)";console.log(` ${t.testFile} [${n}] -> ${t.importedBoundary} (${t.importedFile})`)}e.testBoundaryViolations.length>20&&console.log(` ... +${e.testBoundaryViolations.length-20} more`)}if(e.fragileEdges.length>0){console.log(`
|
|
522
|
+
Single-import boundary edges (${e.fragileEdges.length} of ${e.edges.length}): the whole boundary dependency is carried by one file-level import. Breadth alone does not establish importance -- inspect before concluding either way.`);for(let t of e.fragileEdges.slice(0,10)){let n=t.examples[0];console.log(` ${t.from} -> ${t.to}${n?` (${n.fromFile} -> ${n.toFile})`:""}`)}e.fragileEdges.length>10&&console.log(` ... +${e.fragileEdges.length-10} more`)}if(e.coarseBoundaries.length>0){console.log(`
|
|
523
|
+
Boundaries too coarse to check (${e.coarseBoundaries.length}): these own an internal dependency cycle that the boundary graph cannot express, so requireAcyclic reports nothing about the code inside them.`);for(let t of e.coarseBoundaries){console.log(` ${t.boundary}: ${t.subUnits.join(" <-> ")}`);for(let n of t.narrowestEdges){console.log(` narrowest: ${n.from} -> ${n.to} (${n.fileEdgeCount} file edge(s))`);for(let i of n.examples.slice(0,3))console.log(` ${i.fromFile} -> ${i.toFile}`)}}}if(e.edges.length>0){console.log(`
|
|
524
|
+
Boundary graph (${e.edges.length} directed edge(s)):`);for(let t of e.edges)console.log(` ${t.from} -> ${t.to} ${t.policyStatus.padEnd(10)} ${t.fileEdgeCount} file edge(s)`)}if(e.reciprocalPairs.length>0){console.log(`
|
|
525
|
+
Reciprocal boundary pairs (${e.reciprocalPairs.length}):`);for(let t of e.reciprocalPairs)console.log(` ${t.boundaries[0]} <-> ${t.boundaries[1]} ${t.forward.fileEdgeCount}/${t.reverse.fileEdgeCount} file edge(s)`)}if(e.cycles.length>0){console.log(`
|
|
526
|
+
Strongly connected boundary groups (${e.cycles.length}):`);for(let t of e.cycles){let n=t.violatesPolicy?" [violates requireAcyclic]":"";console.log(` { ${t.boundaries.join(", ")} }${n}`);for(let i of t.narrowestEdges)console.log(` inspect ${i.from} -> ${i.to}: ${i.fileEdgeCount} file edge(s)`)}}}}),nw=Ye({commandName:"deep-chains",query:({db:e,opts:t})=>Vs(e,{limit:D(t,"limit",10),scope:$(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(`
|
|
527
|
+
Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].components){let i=n.length===1?n[0]:`{ ${n.join(", ")} } (cycle)`;console.log(` \u2192 ${i}`)}console.log(` Tier: ${e[t].actionTier} Risk: ${e[t].chainKind}`),console.log(` Recommendation: ${e[t].recommendation}`),console.log(` Evidence: ${e[t].evidenceReasons.join("; ")}`)}}}),qm=[Pi({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",agent:R("Which symbols are the largest reference choke points?","ranked symbol identities with reference and file counts",[],"bounded","repository"),options:[p("-n, --limit <n>","Number of results",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")],docs:C("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>$s(e,{limit:D(t,"limit",30),scope:$(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"Count files referencing an exact symbol; top JSON rows include exact symbol identity",agent:R("How many files reference this symbol, or which symbols have highest fan-in?","exact symbols with referencing-file counts",["symbol"],"bounded","repository"),options:T([p("-n, --limit <n>","Number of results for top mode",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:C("Graph"),handler:Yk},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",agent:R("How many external symbols does this file use, or which files have highest fan-out?","files with external-symbol counts",["file"],"bounded","repository"),options:T([p("-n, --limit <n>","Number of results for top mode",x,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:C("Graph"),handler:Xk},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",agent:R("How strongly are these files coupled, or which pairs are most coupled?","file pairs with coupling evidence and scores",["file","file"],"bounded","repository"),options:T([p("-n, --limit <n>","Number of results for top mode",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:C("Graph"),handler:Zk},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",agent:R("Which file dependency cycles exist?","dependency-cycle file chains",[],"bounded","repository"),options:T([p("-s, --scope <path>","Limit to files matching path"),p("--max-depth <n>","Bound DFS search depth",x,10)]),renderShape:"custom",docs:C("Graph"),handler:ew},{id:"architecture",command:"architecture",description:"Evaluate project-owned architectural boundaries and dependency rules",agent:R("Does the repository obey its declared architecture boundaries?","boundary coverage and dependency-rule violations",[],"complete","repository"),options:T([p("-s, --scope <path>","Limit to files matching path")]),evidence:"mixed",renderShape:"custom",docs:C("Graph",["scip-query architecture --json"]),handler:tw},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",agent:R("Which files are high-connectivity coupling hubs?","ranked files with fan-in and fan-out counts",[],"bounded","repository"),options:T([p("-n, --limit <n>","Number of results",x,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-fan-in <n>","Minimum fan-in",x,2),p("--min-fan-out <n>","Minimum fan-out",x,2),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:C("Graph"),handler:Qk},{id:"deep-chains",command:"deep-chains",description:"Find the longest condensed dependency-component chains",agent:R("Which dependency chains are deepest and riskiest?","ranked component chains with depth, risk, and recommendation",[],"bounded","repository"),options:T([p("-n, --limit <n>","Number of chains to show",x,10),p("-s, --scope <path>","Limit to files matching path"),p("--min-depth <n>","Minimum chain depth",x,3),p("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:C("Graph"),handler:nw},Ti({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",agent:R("Who calls this symbol and what does it call?","caller and callee symbol identities with files",["symbol"],"bounded"),options:[p("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:C("Graph"),query:({db:e,args:t,budget:n})=>Jt(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}
|
|
528
|
+
`))},toJson:(e,{db:t,args:n})=>xe(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 iw=Q("complexity",({db:e,args:t,opts:n,budget:i})=>{let r=L(t,0),o=Ca(e,r,{semantic:i.semantic});if(b(n,"json")){E("complexity",t,n,xe(e,r,o,"complexity"),{analysisBudget:i.analysisBudget});return}if(!o)return j.empty(ae(e,r,"Symbol not found."));se(e,r),console.log(`${_(o.relativePath,o.startLine,o.endLine)} ${o.shortName}
|
|
529
|
+
`),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}`)}),rw=de(({db:e,args:t,opts:n})=>{let i=qa(e,{samples:P(n,"samples",50),scope:$(n,"scope")});if(b(n,"json")){E("self-audit",t,n,i);return}if(!i.available)return j.empty("No semantic or source-backed oracle available to audit against.");let r=i.oracleKind==="source"?"source facts":"compiler semantics";console.log(`Sampled ${i.sampleSize} symbols; ${r} oracle answered ${Math.round(i.oracleCoverage*100)}%.
|
|
530
|
+
`),console.log(`Agreement with ${r} (file-level):`);for(let o of i.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(i.topDisagreements.length>0){console.log(`
|
|
531
|
+
Top disagreements (debugging targets):`);for(let o of i.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(", ")}`)}}),Vm=[{id:"self-audit",command:"self-audit",description:"Score cheap evidence paths against the best available semantic/source oracle on sampled symbols",agent:R("How accurate are the fast evidence paths on a sample?","sample coverage, agreement scores, and disagreements",[],"sampled","repository"),options:T([p("--samples <n>","Number of symbols to sample",x,50),p("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:C("Health",["scip-query self-audit --samples 100"]),handler:rw},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",agent:R("How structurally complex and connected is this symbol?","LOC, branch, complexity, callee, fan-in, and fan-out counts",["symbol"],"bounded"),options:T([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:C("Health"),handler:iw}];var ow=de(({db:e,args:t,opts:n})=>{let i=L(t,0),r=ia(e,i,{maxDepth:P(n,"maxDepth",5),scope:$(n,"scope")});if(b(n,"json")){E("affected",t,n,xe(e,i,r,"affected"));return}if(r.length===0)return j.empty(ae(e,i,"No affected symbols found."));se(e,i);let o=-1;for(let s of r)s.depth!==o&&(console.log(`
|
|
532
|
+
\u2500\u2500 Depth ${s.depth} \u2500\u2500`),o=s.depth),console.log(` ${s.file} ${s.shortName}`);console.log(`
|
|
533
|
+
${r.length} affected symbol(s) across ${new Set(r.map(s=>s.file)).size} files.`)}),sw=Q("co-change",({db:e,args:t,opts:n,budget:i})=>{let r=t[0]===void 0?void 0:L(t,0),o=b(n,"full"),s=oa(e,r,{minTogether:P(n,"minTogether",4),limit:D(n,"limit",30),includeLinked:n.all===!0,scanLimit:i.scanLimit,historyMode:o?"full":"bounded"});if(b(n,"json")){E("co-change",t,n,s,{analysisBudget:i.analysisBudget});return}if(!s.available)return j.empty("No git history available (not a repository, or git missing).");if(s.findings.length===0)return j.empty(r?`No co-change partners found for ${r} in ${s.commitsAnalyzed} commits.`:`No hidden coupling found in ${s.commitsAnalyzed} commits.`);Ie("co-change candidates"),console.log(r?`Co-change partners (${s.commitsAnalyzed} commits analyzed):
|
|
534
|
+
`:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${s.commitsAnalyzed} commits analyzed):
|
|
535
|
+
`),r&&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.
|
|
536
|
+
`);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 ${aw(a.lastTogetherAt)}`),console.log(` subjects: ${cw(a.subjectContext)}`),a.declaredCouplingSuggestion&&console.log(` declare coupling: ${a.declaredCouplingSuggestion.name} (${a.declaredCouplingSuggestion.reason})`)}console.log(`
|
|
537
|
+
${s.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function aw(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function cw(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",i=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(r=>`"${r}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${i}; external issue/PR labels ${e.externalIssueLabelStatus}`}var lw=Q("change-surface",({db:e,args:t,opts:n,budget:i})=>{let r=ra(e,L(t,0),{semantic:i.semantic});if(b(n,"json")){E("change-surface",t,n,r,{analysisBudget:i.analysisBudget});return}if(!r)return j.empty("File not found in index.");console.log(`File: ${r.file}`),console.log(`External consumers: ${r.totalExternalConsumers}
|
|
538
|
+
`),j.list(r.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}`})}),dw=Q("incomplete-migration",({db:e,args:t,opts:n,budget:i})=>{let r=ya(e,{base:$(n,"base"),minContainment:P(n,"minContainment",.7),maxHelpers:J(n,"maxHelpers"),limit:D(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(b(n,"json")){E("incomplete-migration",t,n,r,{analysisBudget:i.analysisBudget}),r.available&&r.findings.length>0&&(process.exitCode=1);return}if(!r.available)return j.empty("No git history available (not a repository, or git missing).");if(r.changedFiles.length===0)return j.empty(`No changes vs ${r.base}.`);console.log(`Incomplete migrations vs ${r.base}: ${r.changedFiles.length} changed file(s), ${r.helpersChecked} new helper(s) scored.`),r.note&&console.log(` note: ${r.note}`);for(let o of r.skipped)console.log(` skipped ${o.helperShortName} (${o.helperFile}): ${o.reason}`);if(r.findings.length===0){console.log(`
|
|
539
|
+
No incomplete migrations detected.`);return}Ie("incomplete migration candidates");for(let o of r.findings){console.log(`
|
|
540
|
+
${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(`
|
|
541
|
+
${r.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function uw(e){let t=Array.isArray(e)?e:[],n=t.filter(i=>!Gi.includes(i));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${Gi.join(", ")}`),process.exit(1)),t}var pw=de(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&Vn(jt()))return;let i=b(t,"full"),r=pc(e,"diff-gate",i,{quiet:n||b(t,"json")}),o={base:$(t,"base"),minTogether:P(t,"minTogether",6),maxEchoChecks:J(t,"maxEchoChecks"),maxHelpers:J(t,"maxHelpers"),includeBaseline:b(t,"baseline"),scanLimit:r.scanLimit,semantic:r.semantic,historyMode:i?"full":"bounded",skip:uw(t.skip)},s=Rt(e,o),a=Dn(s.findings),c=Ln(s),l=Kn(e,s,{replayGate:f=>Rt(e,{...o,base:f})});if(l.warning&&console.error(`note: ${l.warning}`),!n&&b(t,"json")){let f=a.length>0||c?1:0;E("diff-gate",[],t,{exitCode:f,...c?{gateError:"git diff unavailable - zero checks ran; the gate fails closed"}:{},advisoryFindingCount:s.findings.length-a.length,...r.analysisBudget?{analysisBudget:r.analysisBudget}:{},...s},{analysisBudget:r.analysisBudget,coverage:i&&!c?{complete:!0,totalKnown:!0,returned:s.findings.length,total:s.findings.length,omitted:0}:{complete:!1,totalKnown:!1,returned:s.findings.length},agentResult:{outcome:f===0?"pass":"fail",exitCode:f,changedFileCount:s.changedFiles.length,changedSymbolCount:s.changedSymbols,checksRun:s.checksRun,skippedChecks:s.skipped,blockingFindings:a.map(g=>({id:g.id,check:g.check,severity:g.severity,file:g.file,symbol:g.symbol,message:g.message,remediation:g.remediation})),advisoryFindingCount:s.findings.length-a.length}}),(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=Aa(f,g,h),S=La(f,s.checksRun),v=mc(r.analysisBudget),w=[...y?[y]:[],Qt(s),...S,...v?[v]:[]];console.error(w.join(`
|
|
542
|
+
`)),process.exitCode=2;return}if(c){console.error("FAIL (gate error): could not compute the git diff - zero checks ran; the gate fails closed. Check --base and repository state."),process.exitCode=1;return}if(s.changedFiles.length===0)return j.empty(s.note??`No changes vs ${s.base}.`);console.log(`Diff gate vs ${s.base}: ${s.changedFiles.length} file(s), ${s.changedSymbols} symbol(s) changed.`);let d=s.attributionNotes.filter(f=>f.method==="unattributed");if(d.length>0)for(let f of[...new Set(d.map(g=>g.file))]){let g=d.filter(h=>h.file===f).length;console.log(`note: ${g} changed line-range(s) in ${f} belong to no indexed symbol`)}console.log(`Checks: ${s.checksRun.join(", ")}
|
|
543
|
+
`);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}Ie("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: ${Nn(g)}`);f.declaredCouplingSuggestion&&console.log(` declare coupling: ${f.declaredCouplingSuggestion.name} (${f.declaredCouplingSuggestion.reason})`),console.log(` -> ${f.remediation}`)}if(a.length===0){console.log(`
|
|
544
|
+
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(`
|
|
545
|
+
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}),Wm=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",agent:R("Which downstream symbols could break if this symbol changes?","affected symbol identities, files, and traversal depths",["symbol"],"bounded"),options:T([p("--max-depth <n>","Maximum traversal depth",x,5),p("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:C("Impact"),handler:ow},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",agent:R("What public surface and consumers make this file risky to change?","defined symbols, external consumer counts, and risk levels",["file"],"bounded"),options:T([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:C("Impact"),handler:lw},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: architecture regressions plus echo, migration, coordination, doc-drift, unused-param, and new-dead candidates; exit 1 on blocking findings",options:[p("--base <ref>","Git ref to diff against (default: HEAD)"),p("--min-together <n>","Minimum historical co-changes for the partner check",x,6),p("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",x),p("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",x),p("--baseline","Also run the full health-baseline ratchet"),p("--full","Run unbounded semantic and git-history analysis on large indexes"),p("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, twin-partner, coverage-contract, architecture, doc-reference, unused-params, new-dead, baseline",at,[]),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"),p("--compact","Emit minified one-line JSON (use with --json)")],heuristic:{label:"diff gate candidates"},agent:{answers:["Does my current diff introduce something this repo blocks on?","What must I fix or explicitly accept before reporting the work done?"],returns:["blocking findings with check id, message, and remediation","advisory findings","root-cause groups","changed file and symbol counts","process exit status (1 when blocking findings exist)"],inputs:[],scope:"diff",coverage:"bounded",contrasts:[{command:"diff-impact",distinction:"diff-impact reports what the diff touches downstream; diff-gate judges the diff against repo policy and exits non-zero."}]},renderShape:"custom",docs:C("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:pw},{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",agent:R("Did this diff leave a helper extraction only partly migrated?","new helpers and similar unmigrated call sites",[],"bounded","diff"),options:T([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)",x),p("-n, --limit <n>","Maximum findings to report",x,20),p("--full","Run unbounded git-history analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:C("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:dw},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",agent:R("Which files repeatedly change together without a declared dependency?","file pairs, co-change counts, confidence, and history context",["file"],"bounded","repository"),options:T([p("--min-together <n>","Minimum commits where both files changed",x,4),p("-n, --limit <n>","Maximum pairs to report",x,30),p("--all","Include pairs that already have a dependency edge"),p("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:C("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:sw}];function mw(e){let t=[];for(let r of e.definitions){let o=r.signature?` \u2014 ${r.signature}`:"";t.push(` ${_(r.relativePath,r.startLine,r.endLine)}${o}`),r.source&&t.push(r.source.split(`
|
|
546
|
+
`).map((s,a)=>` ${qe(r.startLine+a)} ${s}`).join(`
|
|
547
|
+
`))}let n=[],i="";for(let r of e.referencedBy)r.relativePath!==i&&(i&&n.push(""),n.push(` ${r.relativePath}`),i=r.relativePath),n.push(` line ${qe(r.line)} in ${r.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var fw=ue("imports",{query:({db:e,args:t,budget:n})=>Cs(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)."}),gw=Q("dataflow",({db:e,args:t,opts:n,budget:i})=>{let r=L(t,0),o=Pa(e,r,{semantic:i.semantic});if(b(n,"json")){E("dataflow",t,n,xe(e,r,o,"dataflow"),{analysisBudget:i.analysisBudget});return}if(!o)return j.empty(ae(e,r,"No dataflow found."));if(se(e,r),console.log(`${o.shortName} (${o.relativePath})
|
|
548
|
+
`),o.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of o.definitionSites)console.log(` ${s.file}:${qe(s.line)}`)}if(o.usageSites.length>0){console.log(`
|
|
549
|
+
\u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of o.usageSites)console.log(` ${s.file}:${qe(s.line)} in ${s.enclosingShort}`)}if(o.producers.length>0){console.log(`
|
|
550
|
+
\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(`
|
|
551
|
+
\u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of o.consumers)console.log(` ${s.file} ${s.shortName}`)}}),hw=Q("slice",({db:e,args:t,opts:n,budget:i})=>{let r=L(t,0),o=b(n,"forward")?"forward":"backward",s=Ta(e,r,{direction:o,maxDepth:P(n,"depth",3),semantic:i.semantic});if(b(n,"json")){E("slice",t,n,xe(e,r,s,"slice"),{analysisBudget:i.analysisBudget});return}if(!s)return j.empty(ae(e,r,"No slice found."));if(se(e,r),console.log(`${s.direction} slice of ${s.shortName}
|
|
552
|
+
`),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}j.list(s.connectedSymbols,a=>` ${a.file} ${a.shortName}
|
|
553
|
+
${a.relationship}`),console.log(`
|
|
554
|
+
${s.connectedSymbols.length} connected symbol(s).`)}),Hm=[...Pc,je({id:"files",command:"files <pattern>",description:"Find files matching a pattern",agent:R("Which indexed files match this text pattern?","matching file paths",["pattern"],"complete"),docs:C("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>ys(e,L(t,0)),format:e=>e.relativePath}),je({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",agent:R("Which methods belong to this class?","method names and line ranges",["symbol"],"complete"),docs:C("Navigation"),query:({db:e,args:t})=>bs(e,L(t,0)),format:e=>` ${oe(e.startLine,e.endLine)} ${e.name}`}),Ti({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[p("--full","Run unbounded semantic analysis on large indexes"),Xi()],budget:"semantic",agent:{answers:["Where is this symbol defined, and everywhere is it referenced?"],returns:["definition sites with source and signature","referencing files with line numbers"],inputs:["symbol"],coverage:"bounded",contrasts:[{command:"refs",distinction:"refs returns reference sites only; trace adds the definition and its source."},{command:"call-graph",distinction:"trace lists reference sites flat; call-graph separates incoming callers from outgoing callees."}]},docs:C("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>Ss(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})=>({...Kt(t,L(n,0)),...e}),coverage:(e,{budget:t})=>{let n=e.definitions.length+e.referencedBy.length;return t.analysisBudget?{complete:!1,totalKnown:!1,returned:n}:{complete:!0,totalKnown:!0,returned:n,total:n,omitted:0}},agentResult:e=>({definitionCount:e.definitions.length,referenceCount:e.referencedBy.length,definitionIdentities:e.definitions.map(t=>`${t.relativePath}:${t.startLine}-${t.endLine}`),referenceIdentities:e.referencedBy.map(t=>`${t.relativePath}:${t.line}`)}),sections:mw}),je({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",agent:R("Which internal files does this file depend on?","dependency file paths",["file"],"complete"),docs:C("Navigation"),query:({db:e,args:t})=>vs(e,L(t,0)),format:e=>e.relativePath}),je({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",agent:R("Which internal files depend on this file?","reverse-dependency file paths",["file"],"complete"),docs:C("Navigation"),query:({db:e,args:t})=>xs(e,L(t,0)),format:e=>e.relativePath}),Hp({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",options:[Xi()],agent:{answers:["What is in this module?","What does this module depend on, and what depends on it?"],returns:["module file paths","exported symbols with line ranges","internal dependencies","reverse dependencies"],inputs:["module"],coverage:"complete",contrasts:[{command:"surface",distinction:"system lists everything the module exports; surface lists only what consumers actually use."},{command:"outline",distinction:"system is module-scoped; outline covers a single file."}]},docs:C("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>Rs(e,L(t,0)),coverage:e=>{let t=e.files.length+e.symbols.length+e.dependsOn.length+e.dependedOnBy.length;return{complete:!0,totalKnown:!0,returned:t,total:t,omitted:0}},agentResult:e=>({counts:{files:e.files.length,symbols:e.symbols.length,dependencies:e.dependsOn.length,consumers:e.dependedOnBy.length},files:e.files,dependsOn:e.dependsOn,dependedOnBy:e.dependedOnBy,detail:{location:"result",symbolUnits:"result.symbols contains every exported symbol with its line range"}}),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}`)}]}),je({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",agent:R("Which exported symbols do external consumers actually use?","consumer paths and consumed symbol identities",["module"],"complete"),docs:C("Navigation"),query:({db:e,args:t})=>ks(e,L(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",agent:R("Which symbols does this file import?","imported symbol identities and source files",["file"],"bounded"),options:[p("--full","Run unbounded semantic analysis on large indexes"),p("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:C("Navigation"),handler:fw},je({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",agent:R("Which files import this symbol?","importing file paths",["symbol"],"complete"),docs:C("Navigation"),query:({db:e,args:t})=>Ps(e,L(t,0)),format:e=>` ${e.fromFile}`}),je({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",agent:R("Which members or nested symbols belong to this symbol?","child symbol identities, kinds, and ranges",["symbol"],"complete"),docs:C("Navigation"),query:({db:e,args:t})=>Is(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})=>xe(t,L(n,0),e,"members")}),je({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",agent:R("Which symbols have this SCIP kind?","symbol identities, kinds, files, and ranges",["pattern"],"bounded"),options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",x,100),p("--full","Run unbounded analysis on large indexes")],docs:C("Navigation"),query:({db:e,args:t,opts:n})=>Bs(e,L(t,0),{scope:$(n,"scope"),limit:D(n,"limit",100)}),format:e=>` ${_(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(`
|
|
555
|
+
${e.length} symbol(s)`)}),Pi({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",agent:R("How many indexed symbols exist for each kind?","symbol-kind counts",[],"complete","repository"),options:[p("-s, --scope <path>","Limit to files matching path")],docs:C("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>qs(e,{scope:$(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),je({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",agent:R("What lexical ownership chain contains this symbol?","ancestor symbol identities and depths",["symbol"],"complete"),docs:C("Navigation"),query:({db:e,args:t})=>Ws(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})=>xe(t,L(n,0),e,"hierarchy")}),{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",agent:R("What defines, uses, produces, and consumes this symbol?","definition sites, usage sites, producer symbols, and consumer symbols",["symbol"],"bounded"),options:T([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:C("Navigation"),handler:gw},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",agent:R("What transitively affects this symbol, or what does it affect?","connected symbols with relationship and depth",["symbol"],"bounded"),options:T([p("--forward","Forward slice (what does this affect). Default is backward."),p("--depth <n>","Max transitive depth for backward slice",x,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:C("Navigation"),handler:hw}];var yw=Q("plan-context",({db:e,args:t,opts:n,budget:i})=>{let r=D(n,"limit",20),o=_e(e.config.projectRoot).gitContext?.headCommit,s=Ia(e,L(t,0),{semantic:i.semantic,impactDepth:P(n,"impactDepth",3),sliceDepth:P(n,"sliceDepth",3),scope:$(n,"scope"),...o?{gitHead:o}:{}});if(s.warnings.length===1&&s.warnings[0]==="No symbol, file, or module matched target."){if(b(n,"json")){E("plan-context",t,n,{...Kt(e,L(t,0)),...s},{analysisBudget:i.analysisBudget,coverage:Um(s),agentResult:Gm(s)});return}return j.empty(ae(e,L(t,0)))}if(b(n,"json")){E("plan-context",t,n,s.matched.symbol?{...Kt(e,L(t,0)),...s}:s,{analysisBudget:i.analysisBudget,coverage:Um(s),agentResult:Gm(s)});return}s.matched.symbol&&se(e,L(t,0));let a=[{title:"TARGET",rows:Sw(s)},{title:"DEFINITIONS",rows:vw(s,r),skipIfEmpty:!0},{title:"REFERENCES",rows:xw(s,r),skipIfEmpty:!0},{title:"CALL GRAPH",rows:Rw(s,r),skipIfEmpty:!0},{title:"DATAFLOW",rows:kw(s,r),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:ww(s,r),skipIfEmpty:!0},{title:"SURFACE",rows:$w(s,r),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:Cw(s,r),skipIfEmpty:!0},{title:"CHANGE RISK",rows:Pw(s,r),skipIfEmpty:!0},{title:"HISTORY",rows:Tw(s),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:Iw(s),skipIfEmpty:!0}];j.sectionedReport(a)}),Jm=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:bc([p("--impact-depth <n>","Maximum affected traversal depth",x,3),p("--slice-depth <n>","Maximum backward slice depth",x,3),p("-s, --scope <path>","Limit downstream impact to files matching path"),p("-n, --limit <n>","Rows per section",x,20),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",agent:{answers:["What must I know before editing this target?","Who consumes it, and what breaks if I change it?","Has this target historically changed together with anything else?"],returns:["definitions and references","callers and callees","dataflow producers and consumers","backward and forward slices","affected symbols","change-surface risk","dependencies and reverse dependencies","module files and exports","external surface use","complexity","churn","co-change partners","active suppressions"],inputs:[["symbol","file","module"]],coverage:"bounded",contrasts:[{command:"change-surface",distinction:"change-surface is the exports/consumers/risk briefing alone; plan-context embeds it alongside flow, slices, history, and reuse signals."}]},renderShape:"custom",docs:C("Planning",["scip-query plan-context parseSymbol"]),handler:yw}];function Um(e){return{complete:!1,totalKnown:!1,returned:bw(e)}}function bw(e){return e.trace.definitions.length+e.trace.referencedBy.length+(e.callGraph?.callers.length??0)+(e.callGraph?.callees.length??0)+(e.dataflow?.producers.length??0)+(e.dataflow?.consumers.length??0)+(e.dataflow?.usageSites.length??0)+(e.backwardSlice?.connectedSymbols.length??0)+(e.forwardSlice?.connectedSymbols.length??0)+e.affected.length+e.deps.length+e.rdeps.length+e.system.files.length+e.system.symbols.length+e.system.dependsOn.length+e.system.dependedOnBy.length+e.surface.length}function Gm(e){return{target:e.target,matched:e.matched,counts:{definitions:e.trace.definitions.length,references:e.trace.referencedBy.length,callers:e.callGraph?.callers.length??0,callees:e.callGraph?.callees.length??0,producers:e.dataflow?.producers.length??0,consumers:e.dataflow?.consumers.length??0,backwardSlice:e.backwardSlice?.connectedSymbols.length??0,forwardSlice:e.forwardSlice?.connectedSymbols.length??0,affected:e.affected.length,dependencies:e.deps.length,reverseDependencies:e.rdeps.length,moduleFiles:e.system.files.length,externalSurfaceUses:e.surface.length,coChangePartners:e.history.coChangePartners.length},warnings:e.warnings,changeSurface:e.changeSurface?{file:e.changeSurface.file,totalExternalConsumers:e.changeSurface.totalExternalConsumers,riskCounts:{high:e.changeSurface.symbols.filter(t=>t.riskLevel==="high").length,medium:e.changeSurface.symbols.filter(t=>t.riskLevel==="medium").length,low:e.changeSurface.symbols.filter(t=>t.riskLevel==="low").length}}:null,history:e.history}}function Sw(e){return[`Target: ${e.target}`,`Matched: symbol=${Ro(e.matched.symbol)} file=${Ro(e.matched.file)} module=${Ro(e.matched.module)}`]}function vw(e,t){let n=[];for(let i of e.trace.definitions){let r=i.signature?` -- ${i.signature}`:"";n.push(` ${_(i.relativePath,i.startLine,i.endLine)}${r}`),i.source&&n.push(...i.source.split(`
|
|
556
|
+
`).map((o,s)=>` ${String(qe(i.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(i=>` ${oe(i.startLine,i.endLine)} ${i.shortName}`)),it(n,t).rows}function xw(e,t){let n=e.trace.referencedBy.map(i=>` ${i.relativePath}:${qe(i.line)} in ${i.enclosingShort}`);return ht(it(n,t))}function Rw(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(r=>` caller ${r.file} ${r.shortName}`),i=e.callGraph.callees.map(r=>` callee ${r.file} ${r.shortName}`);return ht(it([...n,...i],t))}function kw(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(o=>` producer ${o.file} ${o.shortName}`),i=e.dataflow.consumers.map(o=>` consumer ${o.file} ${o.shortName}`),r=e.dataflow.usageSites.map(o=>` usage ${o.file}:${qe(o.line)} in ${o.enclosingShort}`);return ht(it([...n,...i,...r],t))}function ww(e,t){let n=[...e.deps.map(i=>` file depends on ${i.relativePath}`),...e.rdeps.map(i=>` file depended on by ${i.relativePath}`),...e.system.dependsOn.map(i=>` module depends on ${i}`),...e.system.dependedOnBy.map(i=>` module used by ${i}`)];return ht(it(n,t))}function $w(e,t){let n=[...e.system.files.map(i=>` file ${i}`),...e.system.symbols.map(i=>` export ${oe(i.startLine,i.endLine)} ${i.shortName}`),...e.surface.map(i=>` use ${i.consumer} -> ${i.shortName}`)];return ht(it(n,t))}function Cw(e,t){let n=[],i=-1;for(let r of e.affected)r.depth!==i&&(n.push(` -- Depth ${r.depth} --`),i=r.depth),n.push(` ${r.file} ${r.shortName}`);return ht(it(n,t))}function Pw(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(i=>{let r=i.riskLevel==="high"?" *** HIGH RISK ***":i.riskLevel==="medium"?" * medium risk *":"";return` ${oe(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${r}`}))),e.complexity&&(n.push(` Complexity: ${_(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}`)),ht(it(n,t))}function Tw(e){let t=e.history;if(!t.available||!t.file)return[];let n=[];if(t.churn){let i=t.churn.fixChanges>0?`, ${t.churn.fixChanges} in fix commits`:"";n.push(` Churn: ${t.churn.changes} change(s) in recent history${i}`)}for(let i of t.coChangePartners)n.push(` Usually changes with: ${i.file} (${i.together}x, ${Math.round(i.confidence*100)}%)`);return t.suppressionsInFile>0&&n.push(` Detector suppressions in file: ${t.suppressionsInFile} (accepted findings \u2014 read the reasons before refactoring)`),n}function Iw(e){let t=e.warnings.map(i=>` ${i}`);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(i=>i.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 it(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function ht(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function Ro(e){return e?"yes":"no"}import{existsSync as hn}from"fs";import{existsSync as Mw,mkdtempSync as _w,rmSync as Bw}from"fs";import{tmpdir as qw}from"os";import{dirname as wo,join as $o}from"path";import{performance as Ym}from"perf_hooks";import{spawnSync as Vw}from"child_process";import{createHash as Ew}from"crypto";import{existsSync as jw,mkdirSync as Aw,readFileSync as Lw,renameSync as Dw,writeFileSync as Ow}from"fs";import{homedir as Fw}from"os";import{dirname as Nw,join as ko}from"path";function zm(e){return Ew("sha256").update(e).digest("hex")}function Km(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?ko(t.XDG_CACHE_HOME,"scip-query"):ko(Fw(),".cache","scip-query"));return ko(n,e)}async function Qm(e){let{cachePath:t,url:n,expectedSha256:i}=e;if(jw(t)){let l=zm(Lw(t));if(l===i)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=zm(s);if(a!==i)throw new Error(`downloaded ${n} checksum mismatch: expected ${i}, got ${a}`);Aw(Nw(t),{recursive:!0});let c=`${t}.tmp-${process.pid}`;return Ow(c,s),Dw(c,t),{status:"downloaded",path:t,sha256:a}}var Ww=12e4,ef="v1.8.0",Hw=`https://github.com/tlaplus/tlaplus/releases/download/${ef}/tla2tools.jar`,Uw="237332bdcc79a35c7d26efa7b82c77c85c2744591c5598673a8a45085ff2a4fb";function Fi(e){let t=e.spawn??Vw,n=Gw(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 i=e.timeoutMs??Ww,r=Ym.now(),o;try{o=t(n.command[0],n.command.slice(1),{cwd:n.cwd,encoding:"utf8",timeout:i,maxBuffer:1024*1024*10})}finally{for(let l of n.cleanupPaths??[])Bw(l,{recursive:!0,force:!0})}let s=Math.round(Ym.now()-r),a=o.error?.name==="ETIMEDOUT"||o.signal==="SIGTERM"&&s>=i,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:Jw(c,o.stdout??"",o.stderr??""),stdout:o.stdout??"",stderr:o.stderr??""}}function Gw(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"&&Oe(Xm(e),t)){let o=Xm(e);return Oe(o,t)?{checker:"apalache",command:[o,"check",...e.configPath?[`--config=${e.configPath}`]:[],`--length=${e.length??10}`,e.specPath],cwd:wo(e.specPath)}:Oi("apalache",`Apalache binary is not available: ${o}`)}let i=Co(e),r=Oe("java",t);if(n==="sany"||n==="tlc"||n==="auto"){if(!i)return Oi(n==="sany"?"sany":"tlc","tla2tools.jar was not found; run 'scip-query tla fetch-tools' or set TLA_TOOLS_JAR");if(!r)return Oi(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",i,"tla2sany.SANY",e.specPath],cwd:wo(e.specPath)};let s=e.metaDir??_w($o(qw(),"scip-tla-tlc-"));return{checker:o,command:["java","-cp",i,"tlc2.TLC","-metadir",s,...e.configPath?["-config",e.configPath]:[],e.specPath],cwd:wo(e.specPath),cleanupPaths:e.metaDir?[]:[s]}}return Oi("none",`unknown checker mode: ${n}`)}function Xm(e){return e.apalacheBin??process.env.APALACHE_BIN??"apalache-mc"}function Co(e){let t=e.env??process.env;return[e.tlaToolsJar,t.TLA_TOOLS_JAR,tf(t),$o(e.projectRoot,"tla2tools.jar"),$o(e.projectRoot,"tools","tla2tools.jar")].filter(i=>typeof i=="string"&&i.length>0).find(i=>Mw(i))??null}function tf(e=process.env){return Km("tla2tools.jar",e)}async function nf(e={}){let t=e.cachePath??tf(e.env),n=e.expectedSha256??Uw,i=e.version??ef,r=e.url??Hw;return{...await Qm({cachePath:t,url:r,expectedSha256:n,fetchImpl:e.fetchImpl}),version:i,url:r}}function Jw(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 i=[...Zm(n),...Zm(t)].slice(0,20);return i.length===0?[{severity:"error",message:"model checker failed without diagnostics"}]:i.map(r=>({severity:"error",message:r}))}function Zm(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean)}function Oi(e,t){return{checker:e,command:["<missing>"],cwd:process.cwd(),missing:t}}import{createHash as zw}from"crypto";import{readFileSync as of}from"fs";import{join as sf}from"path";var af=new Set(["add","clear","delete","pop","push","reverse","set","shift","sort","splice","unshift"]),cf=new Set(["writeFileSync","rmSync","renameSync","mkdirSync","unlinkSync"]),lf=new Set(["readFileSync","existsSync","statSync"]),Kw=/^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i,Qw=/^\s*SELECT\b/i;function df(e){return Kw.test(e)?"write":Qw.test(e)?"read":null}var Yw=/^\s*(?:export\s+)?(?:const|let|var)\s+/;function Xw(e,t){let n=e.match(Yw);if(!n)return!1;let i=e.slice(n[0].length);return new RegExp(`^${De(t)}\\b`).test(i)}function uf(e,t,n,i=[],r=[]){let o=[],s=t$(e,t,o),a=s.aliases,c=n$(t),l=i$(t),d=r$(t),u=a$(e,t,o),m=l$(e,t,o);n&&d$(t,n,r,o);let f=new Map((n?.actions??[]).map(v=>[v.name,v])),g=new Set(u.flatMap(v=>v.referents.map(w=>w.match?.symbol).filter(Boolean))),h=new Set((m?.referents??[]).map(v=>v.match?.symbol).filter(Boolean)),y=u$(e,t,u,a,c,l,d,g,h,o,f),S=f$(e,u,a,c,l,d,o,f);return h$(e,u,o),y$(t,i,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:To(u.flatMap(v=>v.referents))+To(s.referents)+To(m?.referents??[]),staticWrites:y,staticReads:S,waivers:N$(t),checkedInvariants:[...r],traceStepsChecked:i.length,findings:o,findingGroups:Zw(o)}}function Zw(e){let t=new Map;for(let n of e){let i=`${n.category}:${n.modelElement??"-"}`,r=t.get(i);r||(r={groupKey:i,category:n.category,modelElement:n.modelElement,severity:n.severity,count:0,findingIds:[]},t.set(i,r)),r.count+=1,r.findingIds.push(n.id),r.severity=e$(r.severity,n.severity)}return[...t.values()].sort((n,i)=>i.count-n.count||Ni(i.severity)-Ni(n.severity)||n.groupKey.localeCompare(i.groupKey))}function e$(e,t){return Ni(t)>Ni(e)?t:e}function Ni(e){return e==="error"?2:e==="warning"?1:0}function t$(e,t,n){let i=[],r=[];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=Bi(e,l,n,o);r.push(d);let u=d.match;if(!u){c||n.push(U("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}j$(e,o,l,u,n,c),s.aliases.length===0&&a.add(Ho(u.symbol))}for(let l of a)i.push({variable:o,alias:l})}return{aliases:F$(i),referents:r}}function n$(e){let t=[];for(let[n,i]of Object.entries(e.variables))i.resource&&t.push({variable:n,path:i.resource.path});return t}function i$(e){let t=[];for(let[n,i]of Object.entries(e.variables))for(let r of i.statements??[])t.push({variable:n,pattern:r.pattern,regex:new RegExp(r.pattern)});return t}function r$(e){let t=[];for(let[n,i]of Object.entries(e.variables))for(let r of i.ormCalls??[]){let{write:o,read:s}=yo(r);t.push({variable:n,table:r.table,writeMethods:new Set(o),readMethods:new Set(s)})}return t}function o$(e,t,n,i,r,o){return pf(e,t,(s,a,c)=>yt(e,s,a,c,n,i,r,o))}function s$(e,t,n,i,r,o){return pf(e,t,(s,a,c)=>_i(e,s,a,c,n,i,r,o))}function pf(e,t,n){let i=Jt(e,t,{semantic:!1});if(!i)return[];let r=[],o=new Set;for(let s of i.callees){if(o.has(s.symbol))continue;o.add(s.symbol);let a=wn(e,s.symbol).match;if(a)for(let c of n(a.relativePath,a.startLine,a.endLine))r.push({...c,via:s.shortName})}return r}function a$(e,t,n){return Object.entries(t.actions).map(([i,r])=>{let o=r.code.map(s=>{let a=bo(s),c="error"in a?s:a.ref,d=Bi(e,c,n,i).match;return d?(A$(e,i,s,d,n),"error"in a||!a.window?{ref:s,match:d}:c$(a.window,d)?(n.push(U("invalid-line-window","error","compiler-symbol",{modelElement:i,codeRef:s,file:d.relativePath,startLine:d.startLine,endLine:d.endLine,message:`TLA+ action ${i} codeRef line window L${a.window.startLine}-L${a.window.endLine} falls outside ${Y(d.symbol)}'s actual span L${d.startLine+1}-L${d.endLine+1} in ${d.relativePath}.`,why:[`${s} resolves to ${Y(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.${i}.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(U("missing-referent","error","compiler-symbol",{modelElement:i,codeRef:s,message:`TLA+ action ${i} 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.${i}.code to a live function or method symbol.`})),{ref:s,match:null})});return{name:i,mapping:r,referents:o}})}function c$(e,t){return e.startLine-1<t.startLine||e.endLine-1>t.endLine}function l$(e,t,n){let i=t.init;if(!i)return;let r=!!i.waive,o=i.codeRefs.map(s=>{let a=Bi(e,s,n,"Init"),c=a.match;return c?L$(e,s,c,n,r):r||n.push(U("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:i,referents:o}}function d$(e,t,n,i){let r=new Set(t.variables),o=new Set(t.operators),s=new Set(n);for(let a of Object.keys(e.variables))r.has(a)||i.push(U("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)||i.push(U("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&&(rf({action:a.name,field:"writes",modelValues:a.writes,mappingValues:c.writes,missingInMappingCategory:"model-mapping-write",missingInModelCategory:"model-mapping-write",findings:i,file:t.path,isWaived:l=>!!c.waive?.writes.includes(l)}),rf({action:a.name,field:"reads",modelValues:a.reads,mappingValues:c.reads,missingInMappingCategory:"model-mapping-read",missingInModelCategory:"model-mapping-read",findings:i,file:t.path}))}for(let a of e.invariants)s.has(a)||i.push(U("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 rf(e){let t=new Set(e.modelValues),n=new Set(e.mappingValues),i=e.isWaived??(()=>!1);for(let r of t)n.has(r)||i(r)||e.findings.push(U(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"} ${r}, but the mapping does not declare that ${e.field.slice(0,-1)}.`,why:[`SANY-derived model facts list ${r} in ${e.action}.${e.field}, while the mapping omits it.`],remediation:`Add ${r} to actions.${e.action}.${e.field}, or update the TLA+ model if the ${e.field.slice(0,-1)} is unintended.`}));for(let r of n)t.has(r)||i(r)||e.findings.push(U(e.missingInModelCategory,e.field==="writes"?"error":"warning","model-text",{modelElement:e.action,file:e.file,message:`Mapping declares ${e.action}.${e.field} includes ${r}, but the SANY model facts do not.`,why:[`The mapping says ${e.action} ${e.field==="writes"?"writes":"reads"} ${r}, but the parsed TLA+ action does not show that model-side fact.`],remediation:`Update the TLA+ action to ${e.field==="writes"?"prime":"reference"} ${r}, remove the mapping declaration, or add a waiver if static evidence cannot represent the model boundary.`}))}function u$(e,t,n,i,r,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=yt(e,h.match.relativePath,y.startLine,y.endLine,i,r,o,s);g.push(...S),u.push(...S);let v=new Set(f.mapping.writes),w=o$(e,h.match.symbol,i,r,o,s).filter(k=>v.has(k.variable));g.push(...w),u.push(...w)}m$(f,g,l,d.get(f.name))}let m=t.unmappedWriteScope==="actions"?[]:T$(e,t);for(let f of m)for(let g of yt(e,f,0,Number.POSITIVE_INFINITY,i,r,o,s))u.push(g),p$(g)&&(g.enclosingSymbol&&(a.has(g.enclosingSymbol)||c.has(g.enclosingSymbol))||l.push(U("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 jo(u)}function p$(e){return e.kind!=="declaration"&&e.kind!=="object-field"}function m$(e,t,n,i){let r=new Set(e.mapping.writes),o=new Set(t.map(a=>a.variable)),s=new Set(i?.writes??[]);for(let a of t)i&&!s.has(a.variable)&&!fn(e,"write",a.variable)&&n.push(U("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}${Mi(a.via)}.`,`SANY-derived model facts for ${e.name} list writes: ${i.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.`})),!r.has(a.variable)&&!fn(e,"write",a.variable)&&n.push(U("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}${Mi(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 r)!o.has(a)&&!fn(e,"write",a)&&n.push(U("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 f$(e,t,n,i,r,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=_i(e,u.match.relativePath,m.startLine,m.endLine,n,i,r,o);d.push(...f),c.push(...f);let g=new Set(l.mapping.reads),h=s$(e,u.match.symbol,n,i,r,o).filter(y=>g.has(y.variable));d.push(...h),c.push(...h)}g$(l,d,s,a.get(l.name))}return Ao(c)}function g$(e,t,n,i){let r=new Set(e.mapping.reads),o=new Set(t.map(a=>a.variable)),s=new Set(i?.reads??[]);for(let a of t)i&&!s.has(a.variable)&&n.push(U("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}${Mi(a.via)}.`,`SANY-derived model facts for ${e.name} list reads: ${i.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.`})),!r.has(a.variable)&&!fn(e,"read",a.variable)&&n.push(U("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}${Mi(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 r)!o.has(a)&&!fn(e,"read",a)&&n.push(U("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 h$(e,t,n){for(let i of t){if(i.mapping.calls.length===0)continue;let r=i.mapping.calls.map(s=>Bi(e,s,n,i.name));for(let s of r)s.match||n.push(U("missing-referent","error","compiler-symbol",{modelElement:i.name,codeRef:s.ref,message:`actions.${i.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.${i.name}.calls to a live symbol or remove the stale call expectation.`}));let o=new Set(r.map(s=>s.match?.symbol).filter(Boolean));for(let s of i.referents){if(!s.match)continue;let a=Jt(e,s.match.symbol),c=new Set(a?.callees.map(l=>l.symbol)??[]);for(let l of o)c.has(l)||n.push(U("missing-call","error","compiler-symbol",{modelElement:i.name,codeRef:s.ref,file:s.match.relativePath,startLine:s.match.startLine,endLine:s.match.endLine,message:`TLA+ action ${i.name} no longer calls ${Y(l)} from ${s.ref}.`,why:["The mapping declares a call dependency that is absent from the current compiler-resolved call graph."],remediation:`Update actions.${i.name}.calls, update the TLA+ action, or restore the code path if the call is required.`}))}}}function y$(e,t,n){for(let[i,r]of t.entries()){let o=e.actions[r.action];if(!o){n.push(U("trace","error","trace",{modelElement:r.action,codeRef:r.code,message:`Trace step ${i} uses action ${r.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.${r.action} to the mapping, or fix the trace action name.`}));continue}let s=O$(r),a=new Set(o.writes);for(let c of s)a.has(c)||n.push(U("trace","error","trace",{modelElement:r.action,codeRef:r.code,message:`Trace step ${i} changed ${c}, but action ${r.action} does not declare that write.`,why:["The runtime trace observed a state change outside the action write set."],remediation:`Update actions.${r.action}.writes, update the TLA+ model, or investigate the code path that changed ${c}.`}))}}function yt(e,t,n,i,r,o=[],s=[],a=[]){let c=b$(e,t,n,i,r,o,s,a);return c||C$(e,t,n,i,r,o,s,a)}function _i(e,t,n,i,r,o=[],s=[],a=[]){let c=S$(e,t,n,i,r,o,s,a);return c||P$(e,t,n,i,r,o,s,a)}function b$(e,t,n,i,r,o=[],s=[],a=[]){let c=Wi(e,t);if(!c)return null;let l=[],d=u=>{if(!(u.startPosition.row>i||u.endPosition.row<n)){v$(e,t,u,r,l),mf(e,t,u,o,"write",l),ff(e,t,u,s,"write",l),gf(e,t,u,a,"write",l);for(let m of u.children)d(m)}};return d(c.rootNode),jo(l)}function S$(e,t,n,i,r,o=[],s=[],a=[]){let c=Wi(e,t);if(!c)return null;let l=[],d=u=>{if(!(u.startPosition.row>i||u.endPosition.row<n)){k$(e,t,u,r,l),mf(e,t,u,o,"read",l),ff(e,t,u,s,"read",l),gf(e,t,u,a,"read",l);for(let m of u.children)d(m)}};return d(c.rootNode),Ao(l)}function v$(e,t,n,i,r){if(n.type==="assignment_expression"||n.type==="augmented_assignment_expression"){let o=n.childForFieldName("left")??n.namedChild(0);o&&mn(e,t,o,"assignment",i,r);return}if(n.type!=="variable_declarator"){if(n.type==="pair"){let o=n.childForFieldName("key")??n.namedChild(0);o&&mn(e,t,o,"object-field",i,r);return}if(n.type==="update_expression"){let o=n.namedChildren.find(s=>s.type!=="++"&&s.type!=="--")??n.namedChild(0);o&&mn(e,t,o,"update",i,r);return}if(n.type==="unary_expression"&&/^\s*delete\b/.test(n.text)){let o=n.namedChild(0);o&&mn(e,t,o,"delete",i,r);return}if(n.type==="call_expression"){let o=n.childForFieldName("function")??n.namedChild(0);if(!o||!yf(o))return;mn(e,t,o,"mutation-call",i,r)}}}function mf(e,t,n,i,r,o){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?Io(s):null;if(!a||!(r==="write"?cf:lf).has(a))return;let d=n.childForFieldName("arguments")?.namedChild(0);if(!d)return;let u=d.text;for(let m of i){if(!u.includes(m.path))continue;let f=Ae(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?Y(f.symbol):void 0})}}function Io(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 ff(e,t,n,i,r,o){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("arguments");if(s)for(let a of s.namedChildren){let c=x$(a);if(c!==null&&df(c)===r)for(let l of i){if(!l.regex.test(c))continue;let d=Ae(e,t,n.startPosition.row),u=n.childForFieldName("function")??n.namedChild(0),m=(u&&Io(u))??"call";o.push({variable:l.variable,alias:l.pattern,file:t,line:n.startPosition.row,target:`${m}(${R$(c)})`,kind:"statement",enclosingSymbol:d?.symbol,enclosingShort:d?Y(d.symbol):void 0})}}}function x$(e){return e.type!=="string"&&e.type!=="template_string"?null:e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("")}function R$(e){let t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}\u2026`:t}function gf(e,t,n,i,r,o){if(i.length===0||n.type!=="call_expression")return;let s=n.childForFieldName("function")??n.namedChild(0),a=s?Io(s):null;if(!a)return;let l=n.childForFieldName("arguments")?.namedChild(0);if(!l)return;let d=l.text.trim();for(let u of i){if(!hf(u,a,d,r))continue;let m=Ae(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?Y(m.symbol):void 0})}}function hf(e,t,n,i){return n!==e.table?!1:i==="write"?e.writeMethods.has(t):e.readMethods.has(t)||t==="from"&&e.readMethods.has("select")}function k$(e,t,n,i,r){if(!(!w$(n)||$$(n)))for(let o of i){if(n.text!==o.alias)continue;let s=Ae(e,t,n.startPosition.row);r.push({variable:o.variable,alias:o.alias,file:t,line:n.startPosition.row,target:n.text,kind:"identifier",enclosingSymbol:s?.symbol,enclosingShort:s?Y(s.symbol):void 0})}}function w$(e){return e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"}function $$(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&&Po(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&&Po(n,e))}if(t.type==="call_expression"){let n=t.childForFieldName("function")??t.namedChild(0);if(n&&yf(n)&&Po(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 Po(e,t){return e.startIndex<=t.startIndex&&e.endIndex>=t.endIndex}function yf(e){if(e.type!=="member_expression")return!1;let t=e.namedChild(e.namedChildCount-1);return!!(t&&af.has(t.text))}function mn(e,t,n,i,r,o){for(let s of r){if(!D$(s.alias,n.text))continue;let a=Ae(e,t,n.startPosition.row);o.push({variable:s.variable,alias:s.alias,file:t,line:n.startPosition.row,target:n.text,kind:i,enclosingSymbol:a?.symbol,enclosingShort:a?Y(a.symbol):void 0})}}function C$(e,t,n,i,r,o=[],s=[],a=[]){let l=of(sf(e.config.projectRoot,t),"utf8").split(/\r?\n/),d=[],u=Number.isFinite(i)?Math.min(l.length-1,i):l.length-1;for(let m=Math.max(0,n);m<=u;m+=1){let f=l[m]??"";for(let g of r){if(Xw(f,g.alias))continue;let h=De(g.alias);if(!new RegExp(`(?:\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=)|\\b${h}\\b\\s*\\.\\s*(?:${[...af].join("|")})\\s*\\(|\\b${h}\\b\\s*\\[[^\\]]+\\]\\s*=)`).test(f))continue;let S=Ae(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?Y(S.symbol):void 0})}bf(e,t,m,f,o,cf,d),Sf(e,t,m,f,s,"write",d),vf(e,t,m,f,a,"write",d)}return jo(d)}function P$(e,t,n,i,r,o=[],s=[],a=[]){let l=of(sf(e.config.projectRoot,t),"utf8").split(/\r?\n/),d=[],u=Number.isFinite(i)?Math.min(l.length-1,i):l.length-1;for(let m=Math.max(0,n);m<=u;m+=1){let f=l[m]??"";for(let g of r){let h=De(g.alias);if(!new RegExp(`\\b${h}\\b`).test(f)||new RegExp(`\\b${h}\\b\\s*(?:=|\\+=|-=|\\*=|/=|%=|\\.|\\[)`).test(f))continue;let y=Ae(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?Y(y.symbol):void 0})}bf(e,t,m,f,o,lf,d),Sf(e,t,m,f,s,"read",d),vf(e,t,m,f,a,"read",d)}return Ao(d)}function bf(e,t,n,i,r,o,s){if(r.length!==0)for(let a of o){let c=i.indexOf(`${a}(`);if(c===-1)continue;let l=i.slice(c+a.length);for(let d of r){if(!l.includes(d.path))continue;let u=Ae(e,t,n);s.push({variable:d.variable,alias:d.path,file:t,line:n,target:i.trim(),kind:"resource",enclosingSymbol:u?.symbol,enclosingShort:u?Y(u.symbol):void 0})}}}function Sf(e,t,n,i,r,o,s){if(r.length!==0&&df(i)===o)for(let a of r){if(!a.regex.test(i))continue;let c=Ae(e,t,n);s.push({variable:a.variable,alias:a.pattern,file:t,line:n,target:i.trim(),kind:"statement",enclosingSymbol:c?.symbol,enclosingShort:c?Y(c.symbol):void 0})}}function vf(e,t,n,i,r,o,s){if(r.length!==0)for(let a of i.matchAll(/\.([A-Za-z_$][\w$]*)\s*\(\s*([^,)\s][^,)]*?)\s*\)/g)){let c=a[1],l=a[2].trim();for(let d of r){if(!hf(d,c,l,o))continue;let u=Ae(e,t,n);s.push({variable:d.variable,alias:d.table,file:t,line:n,target:i.trim(),kind:"orm-call",enclosingSymbol:u?.symbol,enclosingShort:u?Y(u.symbol):void 0})}}}function T$(e,t){let n=t.scope??[];return n.length===0?[]:e.all("SELECT relative_path FROM documents ORDER BY relative_path").map(r=>r.relative_path).filter(r=>n.some(o=>r.includes(o)))}function Bi(e,t,n,i){let r=wn(e,t),o=r.match??(t.includes("#")?wn(e,t.replace("#","/")).match:null);return r.match&&r.total>1&&!I$(t)&&n.push(U("ambiguous-referent","warning","compiler-symbol",{modelElement:i,codeRef:t,file:r.match.relativePath,startLine:r.match.startLine,endLine:r.match.endLine,message:`Mapping referent ${t} resolved ambiguously to ${Y(r.match.symbol)}.`,why:[`${r.total} indexed definitions share this lookup shape.`,E$(r.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 I$(e){return/[/#:]/.test(e)}function E$(e){return e.length===0?"":`Other candidates: ${e.slice(0,3).map(t=>`${t.shortName} at ${t.relativePath}:${t.startLine+1}`).join(", ")}.`}function j$(e,t,n,i,r,o=!1){let s=Eo(e,i);if(s===null||M$.has(s)||o)return;let a=Lo.has(s);r.push(U("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:i.relativePath,startLine:i.startLine,endLine:i.endLine,message:a?`TLA+ variable ${t} referent is a type; map the runtime state it describes.`:`TLA+ variable ${t} referent is ${Ht(s)}; map the runtime state it describes.`,why:[`${n} resolves to ${Y(i.symbol)} with SCIP kind ${Ht(s)}.`],remediation:`Map variables.${t}.code to a value-like symbol such as a const, let, field, or property that holds runtime state.`}))}function A$(e,t,n,i,r){let o=Eo(e,i);o===null||xf.has(o)||Lo.has(o)&&r.push(U("invalid-referent-kind","error","compiler-symbol",{modelElement:t,codeRef:n,file:i.relativePath,startLine:i.startLine,endLine:i.endLine,message:`TLA+ action ${t} referent is a type; map the runtime transition code it describes.`,why:[`${n} resolves to ${Y(i.symbol)} with SCIP kind ${Ht(o)}.`],remediation:`Map actions.${t}.code to a function or method that performs the transition.`}))}function L$(e,t,n,i,r){let o=Eo(e,n);o===null||xf.has(o)||r||Lo.has(o)&&i.push(U("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 ${Y(n.symbol)} with SCIP kind ${Ht(o)}.`],remediation:"Map init.codeRefs to a function or method that performs the initialization."}))}function Eo(e,t){return e.get("SELECT kind FROM global_symbols WHERE id = ?",t.symbolId)?.kind??null}function Ae(e,t,n){return kn(e,t).filter(r=>r.startLine<=n&&r.endLine>=n).sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine))[0]??null}function D$(e,t){return new RegExp(`(^|[^A-Za-z0-9_$])${De(e)}([^A-Za-z0-9_$]|$)`).test(t)}function O$(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 jo(e){let t=new Set,n=[];for(let i of e){let r=`${i.variable}:${i.file}:${i.line}:${i.target}:${i.enclosingSymbol??""}`;t.has(r)||(t.add(r),n.push(i))}return n}function Ao(e){let t=new Set,n=[];for(let i of e){let r=`${i.variable}:${i.file}:${i.line}:${i.target}:${i.enclosingSymbol??""}`;t.has(r)||(t.add(r),n.push(i))}return n}function F$(e){let t=new Set;return e.filter(n=>{let i=`${n.variable}:${n.alias}`;return t.has(i)?!1:(t.add(i),!0)})}function To(e){return e.filter(t=>t.match).length}function Mi(e){return e?` (via ${e}, one call hop from the mapped referent)`:""}function fn(e,t,n){return!!(t==="read"?e.mapping.waive?.reads:e.mapping.waive?.writes)?.includes(n)}function N$(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}]:[]}),i=e.init?.waive,r=i?[{kind:"referent",variable:"Init",reason:i.reason,legacy:!1}]:[];return[...t,...n,...r]}var Lo=new Set(zo()),xf=new Set(Jo()),M$=new Set(Ko());function U(e,t,n,i){let r=JSON.stringify({category:e,evidence:n,...i});return{id:`TLA${zw("sha1").update(r).digest("hex").slice(0,10).toUpperCase()}`,category:e,severity:t,evidence:n,...i}}import{readFileSync as _$}from"fs";import{basename as B$,join as Rf}from"path";var Do=/^[A-Za-z_][A-Za-z0-9_]*$/;function kf(e,t,n={}){let i=[],r=kn(e,t,{includeClassMemberFallbacks:!0});if(r.length===0)throw new Error(`no indexed definitions found for ${t}; run 'scip-query reindex' or check the path`);let s=_$(Rf(e.config.projectRoot,t),"utf8").split(/\r?\n/),a=I=>I.symbol.trimEnd().endsWith("()."),c=r.filter(I=>!a(I)&&!I.isTypeLike&&I.parentTypeName===null&&Do.test(I.leaf)),l=c.map(I=>({variable:I.leaf,alias:I.leaf})),d=l.length>0?yt(e,t,0,Number.POSITIVE_INFINITY,l):[],u=new Set(d.map(I=>I.variable)),m=c.filter(I=>u.has(I.leaf)?!0:W$(s,I)),f=null,g;if(m.length>0)g=r.filter(I=>a(I)&&I.parentTypeName===null);else{if(f=q$(e,t,r,a),!f){let I=r.some(F=>!a(F)&&!F.isTypeLike&&F.parentTypeName!==null&&Do.test(F.leaf));throw new Error(`no mutable state discovered in ${t} \u2014 the static write scan found no writes to top-level variables, no top-level let declarations exist, and `+(I?"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,i.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(I=>H$(I,s,t,i,f?.className)),y=h.map(I=>({variable:I.name,alias:I.leaf})),S=[],v=new Set;for(let I of g){let F=yt(e,t,I.startLine,I.endLine,y);if(F.length===0)continue;let ee=_i(e,t,I.startLine,I.endLine,y),N=z$(wf(I.leaf),v);S.push({name:N,leaf:I.leaf,codeRef:V$(t,I,f?.className),startLine:I.startLine,writes:[...new Set(F.map(H=>H.variable))].sort(),reads:[...new Set(ee.map(H=>H.variable))].sort()})}S.length===0&&i.push("no top-level callable writes the discovered state; the generated Next relation is empty and the model cannot step. State may be mutated through methods, callbacks, or other files \u2014 narrow or widen the target.");let w=n.moduleName??K$(t),k=n.specDir??Rf("specs",w),O=Q$(w,h,S,t),q=Y$(),K=X$(w,k,t,h,S);return{moduleName:w,file:t,variables:h,actions:S,warnings:i,spec:O,cfg:q,map:K}}function q$(e,t,n,i){let r=new Map;for(let s of n){if(i(s)||s.isTypeLike||s.parentTypeName===null||!Do.test(s.leaf))continue;let a=r.get(s.parentTypeName);a?a.push(s):r.set(s.parentTypeName,[s])}let o=null;for(let[s,a]of r){let c=n.filter(m=>i(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 yt(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 V$(e,t,n){return n?`${e}/${n}#${t.leaf}`:`${e}/${t.leaf}`}function W$(e,t){let n=e[t.startLine]??"";return/^\s*(export\s+)?let\s/.test(n)}function H$(e,t,n,i,r){let o=U$(t,e),s=e.leaf.replace(/[^A-Za-z0-9_]/g,"_"),{domainTla:a,domainBasis:c,initTla:l}=G$(e.leaf,o);return a||i.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||i.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:r?`${n}/${r}#${e.leaf}`:`${n}/${e.leaf}`,declarationLine:e.startLine,initTla:l,domainTla:a,domainBasis:c}}function U$(e,t){return e.slice(t.startLine,t.startLine+3).join(" ").trim()}function G$(e,t){let i=t.match(new RegExp(`\\b${Z$(e)}\\s*:\\s*([^=;]+)`))?.[1]?.trim()??null,o=t.match(/=\s*([^;]+)/)?.[1]?.trim()??null,s=null,a="todo";if(i){let l=J$(i);l?(s=`{${l.map(d=>`"${d}"`).join(", ")}}`,a="union-literal"):/^boolean\b/.test(i)?(s="BOOLEAN",a="boolean"):(/\[\]\s*$/.test(i)||/^(Array|ReadonlyArray)</.test(i))&&(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 J$(e){let t=e.split("|").map(i=>i.trim());if(t.length<2)return null;let n=[];for(let i of t){let r=i.match(/^['"]([^'"]*)['"]$/);if(!r)return null;n.push(r[1])}return n}function wf(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return t.charAt(0).toUpperCase()+t.slice(1)}function z$(e,t){let n=e,i=2;for(;t.has(n);)n=`${e}${i++}`;return t.add(n),n}function K$(e){let n=B$(e).replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_]/g,"");return wf(n||"Model")}function Q$(e,t,n,i){let r=t.map(s=>s.name),o=[];o.push(`---- MODULE ${e} ----`),o.push(`\\* Scaffolded by 'scip-query tla scaffold ${i}'.`),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 ${r.join(", ")}`),o.push(""),o.push(`vars == <<${r.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=r.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(`
|
|
557
|
+
`)}function Y$(){return["SPECIFICATION Spec","INVARIANT TypeOK",""].join(`
|
|
558
|
+
`)}function X$(e,t,n,i,r){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(i.map(s=>[s.name,{code:[s.codeRef],aliases:[s.leaf]}])),actions:Object.fromEntries(r.map(s=>[s.name,{code:[s.codeRef],reads:s.reads,writes:s.writes,calls:[]}])),invariants:["TypeOK"],traces:[]};return`${JSON.stringify(o,null,2)}
|
|
559
|
+
`}function Z$(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $f(e,t){let n=Object.keys(t.variables),i=Object.entries(t.actions).map(([r,o])=>{let s=o.code[0]??"",a=s?Go(e,s):null;return{action:r,codeRef:s,file:a?.relativePath??null,line:a?a.startLine+1:null,writes:o.writes}});return{recorderSource:eC(n),wiring:i,variables:n}}function eC(e){return`/**
|
|
560
|
+
* Generated by 'scip-query tla instrument'. Dependency-free trace recorder.
|
|
561
|
+
*
|
|
562
|
+
* Usage inside a mapped action (record the model-visible slice around the
|
|
563
|
+
* mutation):
|
|
564
|
+
*
|
|
565
|
+
* import { tlaRecord } from './scip-tla-recorder.js';
|
|
566
|
+
* export function enqueue(job: string) {
|
|
567
|
+
* const before = snapshot();
|
|
568
|
+
* queue.push(job);
|
|
569
|
+
* tlaRecord('Enqueue', before, snapshot());
|
|
570
|
+
* }
|
|
571
|
+
*
|
|
572
|
+
* where snapshot() projects the mapped variables to JSON scalars \u2014 fill in
|
|
573
|
+
* each field with the real runtime value, e.g.
|
|
574
|
+
* const snapshot = () => ({ ${e.map(t=>`${t}: undefined`).join(", ")} }); // fill in each field
|
|
575
|
+
*
|
|
576
|
+
* Recording is enabled only when SCIP_TLA_TRACE names an output path, so the
|
|
577
|
+
* wiring is safe to leave in place. The output is a JSON array compatible
|
|
578
|
+
* with 'scip-query tla trace-check --trace <path>'.
|
|
579
|
+
*/
|
|
580
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
581
|
+
|
|
582
|
+
interface TlaTraceStep {
|
|
583
|
+
action: string;
|
|
584
|
+
before: Record<string, unknown>;
|
|
585
|
+
after: Record<string, unknown>;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
const tracePath = process.env['SCIP_TLA_TRACE'];
|
|
589
|
+
|
|
590
|
+
export function tlaRecord(action: string, before: Record<string, unknown>, after: Record<string, unknown>): void {
|
|
591
|
+
if (!tracePath) return;
|
|
592
|
+
let steps: TlaTraceStep[] = [];
|
|
593
|
+
try {
|
|
594
|
+
steps = JSON.parse(readFileSync(tracePath, 'utf8')) as TlaTraceStep[];
|
|
595
|
+
if (!Array.isArray(steps)) steps = [];
|
|
596
|
+
} catch {
|
|
597
|
+
steps = [];
|
|
598
|
+
}
|
|
599
|
+
steps.push({ action, before, after });
|
|
600
|
+
writeFileSync(tracePath, JSON.stringify(steps, null, 2));
|
|
601
|
+
}
|
|
602
|
+
`}import{copyFileSync as tC,mkdtempSync as nC,readdirSync as iC,rmSync as rC,writeFileSync as Cf}from"fs";import{tmpdir as oC}from"os";import{basename as sC,dirname as aC,join as gn}from"path";function qi(e,t){let n=new Map;for(let i of t)n.set(i.action,(n.get(i.action)??0)+1);return e.map(i=>({action:i,stepsObserved:n.get(i)??0}))}function cC(e,t,n,i="Next"){if(n.length===0)return{error:"trace has no steps"};let r=[],o=n[0];if(!o.before)return{error:"trace step 0 must include a full `before` state"};let s=[],a={...o.before},c=h=>{let y={};for(let[S,v]of Object.entries(h)){if(!t.includes(S))continue;let w=dC(v);w!==void 0&&(y[S]=w)}return y};s.push(c(a));for(let h of n){if(h.before)for(let[y,S]of Object.entries(h.before))y in a||(a[y]=S);Object.assign(a,h.after??{}),s.push(c(a))}let l=t.filter(h=>s.every(y=>h in y)),d=t.filter(h=>!l.includes(h));if(l.length===0)return{error:"no mapped variable had a scalar-encodable value in every trace state"};d.length>0&&r.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} |-> ${Tf(h[y])}`).join(", ")}]`).join(`,
|
|
603
|
+
`),f=[`---- MODULE ${u} ----`,"\\* Generated trace-validation harness. Checks that the recorded execution",`\\* is a behavior of ${e}!${i}. 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",` /\\ ${i}`,...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(`
|
|
604
|
+
`),g=["SPECIFICATION TraceSpec","INVARIANT TraceProgress",""].join(`
|
|
605
|
+
`);return{moduleName:u,moduleText:f,cfgText:g,variables:l,skippedVariables:d,states:s.length,warnings:r}}function Pf(e){let t=e.mappedActions??[],n=cC(e.baseModuleName,e.mappedVariables,e.steps,e.nextOperator);if("error"in n)return{status:"invalid-trace",states:0,detail:n.error,actionCoverage:qi(t,[])};let i=nC(gn(oC(),"scip-tla-trace-"));try{let r=aC(e.specPath);for(let d of iC(r))d.endsWith(".tla")&&tC(gn(r,d),gn(i,d));let o=gn(i,`${n.moduleName}.tla`),s=gn(i,`${n.moduleName}.cfg`);Cf(o,n.moduleText),Cf(s,n.cfgText);let a=Fi({...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:qi(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:qi(t,e.steps)};let c=lC(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:qi(t,l)}}finally{rC(i,{recursive:!0,force:!0})}}function lC(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 i=n-1,r=t[i];return{divergedAtState:n,divergedStep:{index:i,action:r?.action??"unknown"}}}function dC(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 Tf(e){return typeof e=="string"?`"${e.replace(/"/g,'\\"')}"`:typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="number"?String(e):`<<${e.map(t=>Tf(t)).join(", ")}>>`}function If(e){return sC(e).replace(/\.tla$/i,"")}import{mkdirSync as jf,writeFileSync as Af}from"fs";import{dirname as uC,join as _t}from"path";var pC=async(...e)=>{let{args:t,opts:n}=Cc(e),i=L(t,0);if(i==="fetch-tools"){let o=await nf();if(b(n,"json")){E("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(i==="scaffold"){let o=W(t,1);if(!o)throw new Error("tla scaffold requires a target source file");le(s=>mC(s,t,n,o));return}if(i==="instrument"){let o=W(t,1);le(s=>fC(s,t,n,o));return}if(i==="trace-check"){let o=W(t,1);if(!o)throw new Error("tla trace-check requires a spec path");le(s=>gC(s,t,n,o));return}if(i!=="verify")throw new Error(`unknown tla operation: ${i}. Supported operations: verify, scaffold, instrument, trace-check, fetch-tools`);let r=W(t,1);if(!r)throw new Error("tla verify requires a spec path");le(o=>bC(o,t,n,r))};function mC(e,t,n,i){let r=e.config.projectRoot,o=kf(e,i,{moduleName:$(n,"moduleName"),specDir:$(n,"out")}),s=$(n,"out")??_t("specs",o.moduleName),a=pe(r,s);if(!a)throw new Error(`scaffold output dir escapes the project root: ${s}`);let c=b(n,"force"),l=[{path:_t(a,`${o.moduleName}.tla`),body:o.spec},{path:_t(a,`${o.moduleName}.cfg`),body:o.cfg},{path:_t(a,`${o.moduleName}.scip-tla.json`),body:o.map}];for(let d of l)if(!c&&hn(d.path))throw new Error(`refusing to overwrite ${d.path} (pass --force to replace scaffold output)`);jf(a,{recursive:!0});for(let d of l)Af(d.path,d.body);if(b(n,"json")){E("tla",t,n,{operation:"scaffold",moduleName:o.moduleName,target:i,written:l.map(d=>d.path),variables:o.variables,actions:o.actions,warnings:o.warnings});return}console.log(`Scaffolded ${o.moduleName} from ${i} (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 ${_t(s,`${o.moduleName}.tla`)}'.`)}function fC(e,t,n,i){let r=e.config.projectRoot,o=$(n,"map")??(i?Ai(i):void 0);if(!o)throw new Error("tla instrument requires --map <mapping.json> (or a spec path to derive it from)");let s=ji(r,o);if(!s.loaded)throw new Error(s.errors.join(`
|
|
606
|
+
`));let{contract:a,mapDir:c}=s.loaded,l=$f(e,a),d=$(n,"out")??_t(c,"scip-tla-recorder.ts"),u=pe(r,d);if(!u)throw new Error(`instrument output escapes the project root: ${d}`);if(!b(n,"force")&&hn(u))throw new Error(`refusing to overwrite ${u} (pass --force to replace the recorder)`);if(jf(uC(u),{recursive:!0}),Af(u,l.recorderSource),b(n,"json")){E("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 gC(e,t,n,i){let r=e.config.projectRoot,o=pe(r,i);if(!o||!hn(o))throw new Error(`TLA+ spec not found: ${i}`);let s=$(n,"map")??Ai(i),a=ji(r,s);if(!a.loaded)throw new Error(a.errors.join(`
|
|
607
|
+
`));let{contract:c}=a.loaded,l=Pt(n,"trace"),u=vo(r,[...c.traces,...l]).flatMap(g=>So(r,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=Pf({specPath:o,baseModuleName:If(o),mappedVariables:Object.keys(c.variables),mappedActions:Object.keys(c.actions),steps:u,nextOperator:$(n,"next"),toolOptions:{projectRoot:r,tlaToolsJar:$(n,"tlaTools"),timeoutMs:J(n,"timeoutMs")}}),f=m.status==="accepted"||m.status==="unavailable"&&b(n,"allowUnknown")?0:1;if(b(n,"json")){E("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")&&hC(m.actionCoverage),process.exitCode=f}function hC(e){if(e.length===0)return;let t=e.filter(i=>i.stepsObserved>0),n=e.filter(i=>i.stepsObserved===0);console.log(`Action coverage: ${t.length}/${e.length} mapped action(s) exercised by this trace.`);for(let i of t)console.log(` - ${i.action}: ${i.stepsObserved} step(s)`);n.length>0&&console.log(` Unexercised: ${n.map(i=>i.action).join(", ")} \u2014 classify each as a pure modeling abstraction (no code twin, expected) or a real coverage gap (record another trace).`)}function yC(e,t,n,i){let r=$(i,"map");if(r)return{mapArg:r};let o=Ai(t),s=pe(e,o);if(s&&hn(s))return{mapArg:o};let a=am(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 bC(e,t,n,i){let r=e.config.projectRoot,o=pe(r,i);if(!o||!hn(o))throw new Error(`TLA+ spec not found: ${i}`);let{mapArg:s,mappingDiscoveredBy:a}=yC(r,i,o,n),c=ji(r,s);if(!c.loaded)throw new Error(c.errors.join(`
|
|
608
|
+
`));let{contract:l,mapPath:d,mapDir:u}=c.loaded,m=$(n,"config")??l.config,f=nm(r,u,m),g=vC($(n,"checker")??"auto"),h=$(n,"tlaTools"),y=SC(r,i,o,h)??im(r,i),S=om(f),v=Pt(n,"trace"),k=vo(r,[...l.traces,...v]).map(N=>({tracePath:N,...So(r,N)})),O=k.flatMap(N=>N.steps),q=new Set(v),K=k.filter(N=>q.has(N.tracePath)).flatMap(N=>N.errors),I=uf(e,l,y,O,S);for(let N of[...c.errors,...K])I.findings.push({id:`TLA-CONTRACT-${I.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 F=Fi({projectRoot:r,specPath:o,configPath:f??void 0,checker:g,tlaToolsJar:h,apalacheBin:$(n,"apalache"),length:P(n,"length",10),timeoutMs:J(n,"timeoutMs")});F.status==="skipped"&&g!=="none"&&I.findings.push({id:"TLA-MODEL-CHECKER-UNAVAILABLE",severity:"warning",evidence:"unknown",category:"contract",message:F.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 ee={operation:"verify",specPath:o,mapPath:d,...a?{mappingDiscoveredBy:a}:{},...f?{configPath:f}:{},checker:F,conformance:I,exitCode:xC(F,I,b(n,"allowUnknown"))};if(b(n,"json")){E("tla",t,n,ee),process.exitCode=ee.exitCode;return}RC(ee,b(n,"full")),process.exitCode=ee.exitCode}function SC(e,t,n,i){let r=Co({projectRoot:e,specPath:n,tlaToolsJar:i,checker:"sany"});if(!r)return null;let o=Gp({specPath:n,jarPath:r});return o?rm(e,t,o):null}var Lf=[{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",agent:R("Does this TLA+ model and code mapping agree, or can the requested model artifact be generated?","checker status, conformance findings, trace coverage, or generated artifact paths",["action","path"],"bounded","repository"),options:T([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",x,10),p("--timeout-ms <n>","Model checker subprocess timeout in milliseconds (verify and trace-check; default 120000)",Ve),p("--trace <file>","Runtime trace JSON file to check against the mapping (repeatable; verify and trace-check both merge and dedupe with contract.traces)",at,[]),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:C("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:pC}];function vC(e){if(!tm(e))throw new Error(`unknown checker mode: ${e}`);return e}function xC(e,t,n){return e.status==="failed"||e.status==="timed-out"||t.findings.some(i=>i.severity==="error")||!n&&t.findings.some(i=>i.evidence==="unknown")?1:0}var Ef=3;function RC(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"),i=e.conformance.findings.filter(o=>o.evidence==="unknown"),r=wC(e);console.log(`
|
|
609
|
+
Conformance: ${e.conformance.mappedVariables} variable(s), ${e.conformance.mappedActions} action(s), ${e.conformance.resolvedReferents} resolved referent(s).`),console.log(`Proof: ${r}`);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), ${i.length} unknown(s), ${e.conformance.findings.length} total.`),t){for(let o of e.conformance.findings)Df(o);return}kC(e.conformance)}function kC(e){let t=new Map(e.findings.map(n=>[n.id,n]));console.log(`
|
|
610
|
+
Finding groups (${e.findingGroups.length}) \u2014 pass --full for every finding ungrouped:`);for(let n of e.findingGroups){console.log(`
|
|
611
|
+
[${n.severity}] ${n.category}${n.modelElement?` (${n.modelElement})`:""} \u2014 ${n.count} finding(s)`);for(let r of n.findingIds.slice(0,Ef)){let o=t.get(r);o&&Df(o)}let i=n.count-Ef;i>0&&console.log(` ... and ${i} more in this group (use --full to show all)`)}}function wC(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,i=e.conformance.waivers.filter(s=>s.kind==="read").length,r=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, ${i} waived`,`calls: ${o===0?"checked":`${o} missing`}`,`traces: ${e.conformance.traceStepsChecked} steps (key-diff; 'tla trace-check' proves acceptance)`,...r>0?[`referents: ${r} waived`]:[]].join(" | ")}function $C(e){let t=[],n=e.conformance.waivers.filter(r=>r.kind==="write").length,i=e.conformance.waivers.filter(r=>r.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."),i>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 Df(e){let t=e.file&&e.startLine!==void 0&&e.endLine!==void 0?` ${_(e.file,e.startLine,e.endLine)}`:e.file?` ${e.file}`:"";console.log(`
|
|
612
|
+
[${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 Of=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","architecture","bottlenecks","isolated","by-kind","kind-counts","deep-chains","hierarchy","call-graph","similar","similar-files","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","similar-chains","extract-candidates","locality-candidates","affected","change-surface","cleanup-plan","cleanup-apply","co-change","recent-duplicates","doc-drift","unused-params","diff-gate","incomplete-migration","tla","plan-context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","dataflow","slice","redundant-reexports","duplicate-bodies","twin-drift","twin-ab","not-implemented","decorative-checkers","test-quality","similar-signatures"],CC=[Bm,Hm,qm,Di,Wm,Jm,Lf,Vm],Ff=CC.flat(),PC=new Map(Ff.map(e=>[e.id,e]));for(let e of Ff)if(!Of.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Bt=Of.map(e=>TC(e));function TC(e){let t=PC.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var IC=Bt.slice(0,Oo("plan-context")),EC=Bt.slice(Vi("drift"),Oo("self-audit")),jC=Bt.slice(Vi("convergence"),Oo("slice")),AC=Bt.slice(Vi("redundant-reexports")),hO=[{id:"reindex",command:"reindex",agent:R("Can the repository index be refreshed, and which language shards succeeded?","index generation, shard statuses, reuse diagnostics, and failures",[],"complete","repository"),description:"Index the codebase and convert to SQLite",options:[p("-l, --language <lang>","Index only this language (can be repeated)",at,[]),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",Ve),p("--json","Output as JSON, including per-shard reuse diagnostics")],renderShape:"custom",docs:C("Indexing",["scip-query reindex"]),handler:lp},{id:"augment-sources",command:"augment-sources",agent:R("Can source files omitted by upstream indexers be added to the index?","added document counts and augmentation status",[],"complete","repository"),description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:C("Indexing"),handler:dp},{id:"augment-vue",command:"augment-vue",agent:R("Can Vue SFC references be compiler-resolved and added to the index?","Vue augmentation counts, project, and diagnostics",[],"complete","repository"),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:C("Indexing"),handler:up},...IC,{id:Yi,command:Yi,description:"Internal diff-impact batch worker",hidden:!0,options:[p("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:pp},{id:"diff-impact",command:"diff-impact",agent:R("Which symbols changed in this diff and which downstream consumers are affected?","changed symbols, downstream consumer identities, and impact paths",[],"bounded","diff"),description:"Compute changed symbols and downstream consumers from current git diff",options:T([p("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:C("Impact"),handler:mp},...EC,{id:Qi,command:Qi,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:fp},{id:"health",command:"health",agent:R("What are the highest-priority verified health problems in this codebase?","health score, findings, priorities, baselines, and coverage notes",[],"bounded","repository"),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:C("Health",["scip-query health --json","scip-query health --baseline"]),handler:gp},{id:"bench",command:"bench",agent:R("How fast are indexing and selected commands under this benchmark matrix?","timings, command outcomes, environment, and optional profiles",[],"sampled","repository"),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)",at,[]),p("--timeout-ms <n>","Per-command timeout in milliseconds",Ve,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:C("Maintenance",["scip-query bench","scip-query bench --json --cold-index"]),handler:hp},{id:"work-audit",command:"work-audit <profile>",agent:R("Which repeated computations in this profile waste the most measured time?","ranked repeated-work groups, counts, and avoidable duration",["path"],"bounded"),description:"Rank exact repeated computations in a profiling JSONL file by measured avoidable time",options:[p("--top <n>","Maximum repeated-work groups to show",Ve,20),p("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",docs:C("Maintenance",["scip-query work-audit profile.jsonl","scip-query work-audit profile.jsonl --json"]),handler:yp},{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",Ve),p("--max-mismatches <n>","Maximum mismatch details to include in output",Ct),p("--full","Compare every indexed TypeScript-like definition"),p("--json","Output as JSON for programmatic consumption")],evidence:"mixed",renderShape:"custom",handler:bp},...jC,{id:"install-skills",command:"install-skills",agent:R("Which scip-query skills were installed, updated, skipped, or conflicted?","skill target paths and install outcomes",[],"complete","repository"),description:`Install skills (${ei.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:C("Maintenance"),handler:xp},{id:"setup-hooks",command:"setup-hooks",agent:R("Were project-local agent hooks installed or removed safely?","hook config targets, changes, skips, and warnings",[],"complete","repository"),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:C("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:Rp},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:vl},{id:"hook-pretool",command:"hook-pretool",description:"Internal Claude PreToolUse evidence-integrity guard",hidden:!0,renderShape:"custom",handler:xl},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:kl},{id:"check-deps",command:"check-deps",agent:R("Which scip-query and language-indexer dependencies are runnable?","dependency readiness statuses and remediation",[],"complete","repository"),description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:C("Maintenance"),handler:kp},{id:"capabilities",command:"capabilities",agent:R("Which evidence and verification capabilities are available here?","capability matrix with availability and reasons",[],"complete","repository"),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:C("Maintenance"),handler:wp},{id:"capability-matrix",command:"capability-matrix",agent:R("Which evidence and verification capabilities are available here?","deprecated alias of the capability matrix",[],"complete","repository"),description:"Deprecated alias for capabilities --matrix",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:C("Maintenance"),handler:$p},...AC,{id:"init",command:"init",agent:R("Can a starter scip-query configuration be created for this project?","configuration path and creation outcome",[],"complete","repository"),description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:C("Maintenance"),handler:Pp},{id:"config-validate",command:"config-validate",agent:R("Is this project configuration valid and internally consistent?","validation diagnostics with config paths",[],"complete","repository"),description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:C("Maintenance",["scip-query config-validate"]),handler:Tp},{id:"suppress",command:"suppress <id>",agent:R("Can this accepted finding be recorded with an auditable reason?","suppression identity, path, scope, and expiry",["finding"],"complete"),description:"Record an accepted finding as a file under .scipquery/suppressions/ with a required reason",options:T([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:C("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:Ip},{id:"effectiveness",command:"effectiveness",agent:R("Which diff-gate checks catch actionable findings with verified outcomes?","per-check caught, fixed, suppressed, unresolved, and precision counts",[],"complete","repository"),description:"Per-check effectiveness from the committed outcome ledger: caught, comparison-verified fixes, suppressed, unverified disappearances, and precision",options:T([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:C("Maintenance",["scip-query effectiveness --since 30d","scip-query effectiveness --check echo --json"]),handler:Ep},{id:"doctor",command:"doctor",agent:R("Why is scip-query unhealthy or unavailable in this project?","config, freshness, dependency, and capability diagnostics",[],"complete","repository"),description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:C("Maintenance"),handler:jp},{id:"setup",command:"setup",agent:R("Can scip-query be bootstrapped end to end in this project?","setup step outcomes, files, capabilities, smoke tests, and warnings",[],"complete","repository"),description:"Bootstrap this project: enable automatic indexing, install agent skills, refresh the index, verify capabilities, and report health",options:T([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:C("Maintenance",["scip-query setup","scip-query setup --json"]),handler:Dp},{id:"setup-agent",command:"setup-agent",agent:R("Can project agent guidance and optional git enforcement be seeded?","written, unchanged, and skipped agent files or hooks",[],"complete","repository"),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:C("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:Lp},{id:"setup-ci",command:"setup-ci",agent:R("Can a CI workflow enforce reindex and diff-gate on pull requests?","workflow path, rendered content, and write outcome",[],"complete","repository"),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:C("Maintenance",["scip-query setup-ci"]),handler:Op},{id:"uninstall",command:"uninstall",agent:R("Which scip-query-owned integrations can be removed without touching user-owned files?","removed, retained, skipped, and dry-run targets",[],"complete","repository"),description:"Remove scip-query-owned skill links, project hooks, and managed agent setup blocks",options:T([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:C("Maintenance",["scip-query uninstall --dry-run","scip-query uninstall --project"]),handler:Fp},{id:"watch",command:"watch",agent:R("What is the watcher doing, or can its background service be started or stopped?","watcher/service state, generation, activity, and errors",[],"complete","repository"),description:"Watch in the foreground or manage the per-project background refresh service",options:T([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)",Ct),p("--cooldown <ms>","Min ms between reindexes; 0 disables spacing (default: 0)",Ct),p("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",Ct),p("--idle-timeout <ms>","Ms before clean-idle daemon exit; 0 keeps it running (default: 600000)",Ct)]),renderShape:"custom",docs:C("Maintenance",["scip-query watch","scip-query watch --daemon","scip-query watch --status --json","scip-query watch --stop"]),handler:Np},{id:"status",command:"status",agent:R("Is the index fresh, complete, and usable for this project?","freshness, generation, language shards, watcher, and optional capabilities",[],"complete","repository"),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:C("Maintenance"),handler:Bp}];function Vi(e){let t=Bt.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function Oo(e){return Vi(e)+1}export{hO as commandDescriptors};
|
|
613
|
+
//# sourceMappingURL=command-descriptors-N2TL4XM2.js.map
|