scip-query 0.10.8 → 0.10.11
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/README.md +3 -1
- package/dist/chunk-2KHTSEIL.js +102 -0
- package/dist/chunk-3VD3JMK2.js +2 -0
- package/dist/{chunk-MEKSFV6H.js → chunk-4UZO3XCV.js} +2 -2
- package/dist/{chunk-BJWNO6BU.js → chunk-54KGX7EX.js} +2 -2
- package/dist/chunk-5GOLFJEO.js +8 -0
- package/dist/chunk-5OST6GYB.js +2 -0
- package/dist/{chunk-C6BYNIH4.js → chunk-65AU3HFZ.js} +2 -2
- package/dist/{chunk-E2CCBFLR.js → chunk-6GN7FXCH.js} +2 -2
- package/dist/{chunk-RHKMQNFI.js → chunk-6IR2AOBM.js} +2 -2
- package/dist/{chunk-6EO3E3IP.js → chunk-6JRV4MY2.js} +2 -2
- package/dist/{chunk-5SMUKUV5.js → chunk-6LJHXREW.js} +2 -2
- package/dist/chunk-6QSOCTZT.js +18 -0
- package/dist/{chunk-6TDOT7B3.js → chunk-72KY2ZFO.js} +2 -2
- package/dist/{chunk-LGX2Y4BA.js → chunk-7B6LP46R.js} +2 -2
- package/dist/chunk-7GO4EQF5.js +2 -0
- package/dist/chunk-7IVSJJZU.js +7 -0
- package/dist/{chunk-EBIQY3RK.js → chunk-7TWLSZK5.js} +2 -2
- package/dist/{chunk-X3Z4MLVL.js → chunk-AVWPHM2Q.js} +2 -2
- package/dist/{chunk-GZQID3FS.js → chunk-BASVXNY3.js} +2 -2
- package/dist/{chunk-BJG67TCR.js → chunk-BFXPG2VN.js} +2 -2
- package/dist/chunk-BSN22NRK.js +9 -0
- package/dist/{chunk-ZDR4VTOP.js → chunk-BVRS7RKQ.js} +2 -2
- package/dist/{chunk-ANIOISCE.js → chunk-C5CTSJ6X.js} +2 -2
- package/dist/{chunk-VXT7WVIN.js → chunk-CO5GJRP7.js} +2 -2
- package/dist/chunk-CW5YFOCP.js +5 -0
- package/dist/chunk-E35O7UCB.js +2 -0
- package/dist/{chunk-LWTML2AN.js → chunk-EXDQ35NN.js} +2 -2
- package/dist/{chunk-Q34NWRPP.js → chunk-EY43NV4M.js} +2 -2
- package/dist/chunk-FAYI6KZ5.js +2 -0
- package/dist/{chunk-ZL52RLDK.js → chunk-FDEQIPPK.js} +2 -2
- package/dist/{chunk-5G5VI7J4.js → chunk-FFVIFETB.js} +2 -2
- package/dist/{chunk-JUIAOOK7.js → chunk-FKCGBZAC.js} +2 -2
- package/dist/{chunk-JRUKS66S.js → chunk-FXNWFMKW.js} +2 -2
- package/dist/chunk-G5UPYQGL.js +4 -0
- package/dist/chunk-GQBMH2TQ.js +2 -0
- package/dist/{chunk-VFLHKRTW.js → chunk-GRJY65YT.js} +2 -2
- package/dist/chunk-HF25DFSC.js +3 -0
- package/dist/chunk-HHN2B5KA.js +2 -0
- package/dist/{chunk-7KJBH4IP.js → chunk-IHUETYFW.js} +2 -2
- package/dist/{chunk-BEUQVBE3.js → chunk-JATUZIEH.js} +2 -2
- package/dist/chunk-JCLDUKT6.js +38 -0
- package/dist/{chunk-B4EHYG6M.js → chunk-JGN2ZFJR.js} +2 -2
- package/dist/{chunk-L4QKEQ4S.js → chunk-JME7OWD3.js} +2 -2
- package/dist/chunk-KDFONWTW.js +40 -0
- package/dist/{chunk-VMPB52FG.js → chunk-LPL4MA6R.js} +2 -2
- package/dist/{chunk-FGTHPJON.js → chunk-LSET2TXH.js} +2 -2
- package/dist/chunk-LZHUWKGD.js +2 -0
- package/dist/{chunk-JYSAYZNX.js → chunk-M4COR2H6.js} +2 -2
- package/dist/{chunk-QDGKE5HN.js → chunk-NOJAM5ZV.js} +2 -2
- package/dist/chunk-O6ZH6C6Y.js +2 -0
- package/dist/{chunk-3LQFMQPY.js → chunk-OBGRLXWF.js} +2 -2
- package/dist/chunk-OLTESY4K.js +3 -0
- package/dist/chunk-P4KYUPBD.js +4 -0
- package/dist/chunk-P5RYBRIO.js +4 -0
- package/dist/{chunk-6N6QTGSD.js → chunk-P753MDDE.js} +2 -2
- package/dist/{chunk-NWFSC356.js → chunk-P7AL7Y37.js} +2 -2
- package/dist/chunk-QLAUCRDJ.js +2 -0
- package/dist/{chunk-FHWEEQVO.js → chunk-QPU7EXAW.js} +2 -2
- package/dist/{chunk-AA7L7GKI.js → chunk-QYB5P7GL.js} +2 -2
- package/dist/chunk-RNM6LMCF.js +2 -0
- package/dist/chunk-RVWSAMTT.js +2 -0
- package/dist/{chunk-T633QLYF.js → chunk-TK7O5ER5.js} +2 -2
- package/dist/chunk-TQ5W2H3S.js +4 -0
- package/dist/chunk-USPV3T5K.js +2 -0
- package/dist/{chunk-FKUCFCLU.js → chunk-VCQYSG2M.js} +2 -2
- package/dist/{chunk-2YI45TNM.js → chunk-VUKC6F77.js} +2 -2
- package/dist/{chunk-N7F5UM6J.js → chunk-W6BVEKYC.js} +2 -2
- package/dist/{chunk-63MSELOP.js → chunk-WUCEKFQC.js} +2 -2
- package/dist/chunk-XUGQU7PM.js +41 -0
- package/dist/{chunk-KZYHFI2X.js → chunk-Y5NBHMQX.js} +2 -2
- package/dist/{chunk-6BNOACLT.js → chunk-YCOFCT4B.js} +2 -2
- package/dist/{chunk-SHM5D3DQ.js → chunk-YWYFU2V3.js} +2 -2
- package/dist/{chunk-BWL2ECGQ.js → chunk-Z3YYR4OS.js} +2 -2
- package/dist/{chunk-3FYGJ2GY.js → chunk-Z4HICZGY.js} +2 -2
- package/dist/{chunk-24S6MYOC.js → chunk-ZQDIXAF5.js} +2 -2
- package/dist/cli.js +298 -244
- package/dist/{db-BAVwb4Pb.d.ts → db-Djj3Nqrb.d.ts} +2 -0
- package/dist/{health-B17sVFYf.d.ts → health-D5J42g4D.d.ts} +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -3
- package/dist/queries/affected.d.ts +1 -1
- package/dist/queries/affected.js +1 -1
- package/dist/queries/bottlenecks.d.ts +1 -1
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +1 -1
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +1 -1
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +1 -1
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +1 -1
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +1 -1
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +1 -1
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +1 -1
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +1 -1
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.d.ts +1 -1
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +1 -1
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +1 -1
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +1 -1
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +1 -1
- package/dist/queries/dead.js +1 -1
- package/dist/queries/deep-chains.d.ts +1 -1
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/deps.d.ts +1 -1
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-gate.d.ts +1 -1
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.d.ts +1 -1
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +1 -1
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +2 -1
- package/dist/queries/drift.js +1 -1
- package/dist/queries/extract-candidates.d.ts +1 -1
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +1 -1
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +1 -1
- package/dist/queries/health.d.ts +2 -2
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +1 -1
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +1 -1
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +1 -1
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +1 -1
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +3 -3
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +1 -1
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.d.ts +1 -1
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.d.ts +1 -1
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +1 -1
- package/dist/queries/methods.js +1 -1
- package/dist/queries/outline.d.ts +1 -1
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +1 -1
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +1 -1
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +2 -1
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +2 -1
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +1 -1
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.d.ts +1 -1
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +1 -1
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +1 -1
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.d.ts +1 -1
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.d.ts +1 -1
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.d.ts +1 -1
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.d.ts +1 -1
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +13 -2
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.d.ts +1 -1
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.d.ts +1 -1
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/stats.d.ts +1 -1
- package/dist/queries/surface.d.ts +1 -1
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.d.ts +1 -1
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +1 -1
- package/dist/queries/system.js +1 -1
- package/dist/queries/trace.d.ts +1 -1
- package/dist/queries/trace.js +1 -1
- package/dist/queries/unused-imports.d.ts +1 -1
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.d.ts +1 -1
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.d.ts +2 -1
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.d.ts +2 -1
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.d.ts +1 -1
- package/dist/queries/wrapper-candidates.d.ts +1 -1
- package/dist/queries/wrapper-candidates.js +1 -1
- package/docs/COMMAND_REFERENCE.md +1 -1
- package/docs/analyzer-inventory.md +29 -0
- package/docs/analyzer-validation-ledger.md +32 -1
- package/package.json +1 -1
- package/skills/scip-hyper-optimization/SKILL.md +153 -24
- package/skills/scip-hyper-optimization/agents/openai.yaml +3 -3
- package/dist/chunk-2H57MJLI.js +0 -2
- package/dist/chunk-4TMJDHC6.js +0 -5
- package/dist/chunk-5GVOJOBL.js +0 -2
- package/dist/chunk-7XWXGANX.js +0 -4
- package/dist/chunk-AETMKBZR.js +0 -40
- package/dist/chunk-BTCASU5J.js +0 -3
- package/dist/chunk-C6ROZBJA.js +0 -32
- package/dist/chunk-COUFCH64.js +0 -2
- package/dist/chunk-EKECQP6Z.js +0 -2
- package/dist/chunk-FVA3NH4P.js +0 -2
- package/dist/chunk-I274B3B3.js +0 -7
- package/dist/chunk-J6ADQKQA.js +0 -2
- package/dist/chunk-K7VBTWNR.js +0 -2
- package/dist/chunk-KLXVEBVC.js +0 -2
- package/dist/chunk-KRGBLZT2.js +0 -7
- package/dist/chunk-P3K7LX7M.js +0 -4
- package/dist/chunk-PVZMPG5I.js +0 -2
- package/dist/chunk-RSKOYTSY.js +0 -3
- package/dist/chunk-RY7CAOJF.js +0 -4
- package/dist/chunk-S7YOLFLX.js +0 -2
- package/dist/chunk-SOGKYB5I.js +0 -8
- package/dist/chunk-VAXDTQHE.js +0 -18
- package/dist/chunk-X3BJUFSN.js +0 -62
- package/dist/chunk-XPOZO76D.js +0 -2
- package/dist/chunk-XWC67C3Q.js +0 -2
- package/dist/chunk-YNSVAJR6.js +0 -2
- package/dist/chunk-ZMU6IWDK.js +0 -38
package/dist/cli.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{program as
|
|
2
|
+
import{program as ua}from"commander";import{realpathSync as lS}from"fs";import{fileURLToPath as UH}from"url";import{spawn as PA}from"child_process";import{createRequire as NA}from"module";import{availableParallelism as EA}from"os";import{fileURLToPath as Fl}from"url";import{statSync as dS}from"fs";function Ue(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:i,references:r,...mS(e.config.dbPath)}}function mS(e){try{let t=dS(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function B(e,t={}){let n=t.scope?"AND relative_path LIKE ?":"",i=t.like?"AND relative_path LIKE ?":"",r=[...t.scope?[`%${t.scope}%`]:[],...t.like?[t.like]:[]],o=e.all(`SELECT relative_path
|
|
3
3
|
FROM documents
|
|
4
4
|
WHERE 1 = 1
|
|
5
5
|
${e.pathExclusionsFor("documents")}
|
|
6
6
|
${n}
|
|
7
|
-
${
|
|
8
|
-
ORDER BY relative_path`,...
|
|
9
|
-
`):[]})}var
|
|
10
|
-
`).length}function
|
|
11
|
-
`).length-1):0;return{kind:n,ownerPath:t,sourcePath:c,external:!0,src:s,attrs:
|
|
12
|
-
`.repeat(
|
|
7
|
+
${i}
|
|
8
|
+
ORDER BY relative_path`,...r).map(a=>a.relative_path),s=t.extensions?o.filter(a=>t.extensions.some(c=>a.toLowerCase().endsWith(c.toLowerCase()))):o;return t.includeIgnored===!1?s.filter(a=>!e.isIgnored(a)):s}function pS(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function da(e,t){let n=pS(t);return B(e,{like:n,includeIgnored:!1}).map(i=>({relativePath:i}))}import{extname as ku}from"path";var fS={".rs":"rust",".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".java":"java",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".sc":"scala",".rb":"ruby",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".hxx":"cpp",".cs":"csharp",".php":"php",".vb":"vb"};function K(e){return fS[ku(e).toLowerCase()]??null}function Nt(e){return ku(e).toLowerCase()===".vue"}var wu=[];function Vt(e){e.groups.length>0&&wu.push(e)}function ma(e,t){let n=new Set(t.groups);for(let i of wu)i.groups.some(r=>n.has(r))&&(t.file!==void 0&&i.clearFile?i.clearFile(e,t.file):i.clearAll(e))}function Iu(){let e=new WeakMap;return{cache:e,ensure(t){let n=e.get(t);return n||(n=new Map,e.set(t,n)),n}}}function U(e,t){let{cache:n,ensure:i}=Iu(),r={get(o,s,a){let c=i(o);if(c.has(s))return c.get(s);let l=a();return c.set(s,l),l},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)},size(o){return n.get(o)?.size??0}};return Vt({name:e,groups:t.clearGroups,clearAll:o=>r.invalidateAll(o),clearFile:(o,s)=>r.invalidate(o,s)}),r}function re(e,t){let n=new WeakMap,i={get(r,o){let s=n.get(r);if(s)return s.value;let a=o();return n.set(r,{value:a}),a},invalidate(r){n.delete(r)},has(r){return n.has(r)}};return Vt({name:e,groups:t.clearGroups,clearAll:r=>i.invalidate(r)}),i}var gS={clearGroups:["whole-project","source-file"]};function qt(e){return dn(e,gS)}function dn(e,t){let{cache:n,ensure:i}=Iu(),r={get(o,s,a,c){let l=i(o),u=l.get(s);if(u&&u.source===a)return u.value;let d=c();return l.set(s,{source:a,value:d}),d},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)}};return Vt({name:e,groups:t.clearGroups,clearAll:o=>r.invalidateAll(o),clearFile:(o,s)=>r.invalidate(o,s)}),r}import{createRequire as hS}from"module";var Ae=hS(import.meta.url),uo=null,Lu=!1;function yS(){if(Lu)return null;if(uo)return uo;try{return uo=Ae("tree-sitter"),uo}catch{return Lu=!0,null}}var Du=new Map,pa=new Set;function bS(e){if(pa.has(e))return null;let t=Du.get(e);if(t)return t;let n;try{switch(e){case"rust":n=Ae("tree-sitter-rust");break;case"typescript":n=Ae("tree-sitter-typescript").typescript;break;case"tsx":n=Ae("tree-sitter-typescript").tsx;break;case"javascript":n=Ae("tree-sitter-javascript");break;case"python":n=Ae("tree-sitter-python");break;case"java":n=Ae("tree-sitter-java");break;case"kotlin":n=Ae("tree-sitter-kotlin");break;case"scala":n=Ae("tree-sitter-scala");break;case"ruby":n=Ae("tree-sitter-ruby");break;case"c":n=Ae("tree-sitter-c");break;case"cpp":n=Ae("tree-sitter-cpp");break;case"csharp":n=Ae("tree-sitter-c-sharp");break;case"php":n=Ae("tree-sitter-php").php;break;case"vb":{let i=Ae("tree-sitter-vb-dotnet");n=i.language??i;break}}}catch{return pa.add(e),null}return Du.set(e,n),n}var Pu=new Map;function SS(e){let t=Pu.get(e);if(t)return t;let n=bS(e);if(!n)return null;let i=yS();if(!i)return null;let r=new i;try{r.setLanguage(n)}catch{return pa.add(e),null}return Pu.set(e,r),r}function xS(e,t){return e.parse(i=>i>=t.length?null:t.slice(i,Math.min(t.length,i+16384)))}function Yi(e,t){let n=SS(e);if(!n)return null;try{return xS(n,t)}catch{return null}}import{readFileSync as CS}from"fs";import{join as vS}from"path";var RS=U("source-text",{clearGroups:["whole-project","source-file"]}),kS=U("source-lines",{clearGroups:["whole-project","source-file"]});function F(e,t){let n=t.replace(/\\/g,"/");return RS.get(e,n,()=>{let i=vS(e.config.projectRoot,n);try{return CS(i,"utf-8")}catch(r){if(wS(r))return"";throw r}})}function wS(e){return typeof e=="object"&&e!==null&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function Ke(e,t){let n=t.replace(/\\/g,"/");return kS.get(e,n,()=>{let i=F(e,n);return i?i.split(`
|
|
9
|
+
`):[]})}var IS=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar))?\b/i;function Zi(e){let t=IS.exec(e);return t?t[1]??"":null}function mo(e,t,n){if(n<=0)return!1;let i=Ke(e,t);if(i.length===0)return!1;for(let r=n-1;r>=0&&r>=n-5;r-=1){let o=(i[r]??"").trim();if(o!==""){if(Zi(o)!==null)return!0;if(!o.startsWith("//")&&!o.startsWith("*")&&!o.startsWith("/*")&&!o.startsWith("@")&&!o.startsWith("#"))return!1}}return!1}import{parse as TS}from"@vue/compiler-sfc";import{posix as fa}from"path";import{parse as LS}from"@vue/compiler-sfc";var DS=qt("vue-sfc-units");function fo(e,t){let n=Tu(t),i=F(e,n);return DS.get(e,n,i,()=>PS(e,n,i))}function Tu(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function ga(e){let t=e?.toLowerCase();return!t||t==="js"||t==="javascript"||t==="jsx"?"javascript":t==="ts"||t==="typescript"?"typescript":t==="tsx"?"tsx":null}function mn(e){return!e||e.body.length===0?0:e.body.split(`
|
|
10
|
+
`).length}function PS(e,t,n){let i={relativePath:t,template:null,scripts:[],styles:[],customBlocks:[],errors:[]};if(!n)return i;let r;try{r=LS(n,{filename:t})}catch(s){return i.errors.push(Eu(s)),i}i.errors.push(...r.errors.map(Eu));let{descriptor:o}=r;return o.template&&(i.template=po(e,t,"template",o.template)),o.script&&i.scripts.push(Nu(e,t,o.script,!1)),o.scriptSetup&&i.scripts.push(Nu(e,t,o.scriptSetup,!0)),i.styles=o.styles.map(s=>po(e,t,"style",s)),i.customBlocks=o.customBlocks.map(s=>po(e,t,"custom",s)),i.errors.push(...[i.template,...i.scripts,...i.styles,...i.customBlocks].flatMap(s=>s?.errors??[])),i}function Nu(e,t,n,i){let r=po(e,t,"script",n);return{...r,kind:"script",setup:i,astLanguage:ga(r.lang)}}function po(e,t,n,i){let r=ES(i.attrs),o=typeof r.lang=="string"?r.lang:null,s=typeof r.src=="string"?r.src:typeof i.src=="string"?i.src:void 0;if(s){let c=NS(t,s);if(!c)return{kind:n,ownerPath:t,sourcePath:t,external:!0,src:s,attrs:r,lang:o,body:"",startLine:0,endLine:0,errors:[`Could not resolve Vue ${n} block source: ${s}`]};let l=F(e,c),u=l?Math.max(0,l.split(`
|
|
11
|
+
`).length-1):0;return{kind:n,ownerPath:t,sourcePath:c,external:!0,src:s,attrs:r,lang:o,body:l,startLine:0,endLine:u,errors:l?[]:[`Vue ${n} block source not found: ${c}`]}}let a=Math.max(0,i.loc.start.line-1);return{kind:n,ownerPath:t,sourcePath:t,external:!1,attrs:r,lang:o,body:i.content,startLine:a,endLine:Math.max(a,i.loc.end.line-1),errors:[]}}function NS(e,t){let n=t.split(/[?#]/,1)[0];if(!n||n.startsWith("/")||n.includes("://"))return null;let i=Tu(fa.normalize(fa.join(fa.dirname(e),n)));return i===".."||i.startsWith("../")?null:i}function ES(e){return{...e}}function Eu(e){return e instanceof Error?e.message:String(e)}function go(e){let t=TS(e),n=t.descriptor.scriptSetup??t.descriptor.script;if(!n||n.src)return null;let i=ga(n.lang??null);return i?{body:n.content,startLine:Math.max(0,n.loc.start.line-1),language:i}:null}var Fu=dn("ast-trees",{clearGroups:["whole-project","source-file"]});function ke(e,t){if(Nt(t))return FS(e,t);let n=K(t);if(!n)return null;let i=F(e,t);return i?Fu.get(e,t,i,()=>Yi(n,i)):null}function FS(e,t){let n=F(e,t);return n?Fu.get(e,t,n,()=>{let i=go(n);if(!i)return null;let r=`
|
|
12
|
+
`.repeat(i.startLine)+i.body;return Yi(i.language,r)}):null}function ti(e,t){let n=_S(e,t);if(!n)return null;let i=ei(n);return i?{calleeLeaf:i,memberAccess:AS(n),line:e.startPosition.row}:null}function _S(e,t){if(t==="rust")return e.type==="call_expression"?e.childForFieldName("function")??e.namedChild(0):e.type==="macro_invocation"?e.childForFieldName("macro")??e.namedChild(0):null;if(t==="python")return e.type!=="call"?null:e.childForFieldName("function")??e.namedChild(0);if(t==="typescript"||t==="tsx"||t==="javascript"){if(e.type==="call_expression")return e.childForFieldName("function")??e.namedChild(0);if(e.type==="new_expression")return e.childForFieldName("constructor")??e.namedChild(0)}return null}function AS(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function ei(e){switch(e.type){case"identifier":case"type_identifier":case"property_identifier":case"shorthand_property_identifier":return e.text;case"field_expression":case"member_expression":case"attribute":{let t=e.namedChild(e.namedChildCount-1);return t?ei(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?ei(t):null}case"super":case"self":case"this":return null;default:return null}}import{createHash as $S}from"crypto";import{readFileSync as MS}from"fs";import{dirname as _u,join as Au}from"path";import OS from"better-sqlite3";var jS="evidence.db",ho=new WeakMap,BS=U("evidence-content-hash",{clearGroups:["whole-project","source-file"]}),HS=U("evidence-project-fingerprint",{clearGroups:["whole-project"]}),ni="evidence-v1",ha="version NOT LIKE 'evidence-%'";function ii(e){return $S("sha256").update(e).digest("hex")}function Z(e,t,n){return BS.get(e,t,()=>ii(n))}function er(e){return HS.get(e,"current",()=>{try{let t=JSON.parse(MS(Au(_u(e.config.dbPath),"meta.json"),"utf-8"));if(t.version!==2&&t.version!==3||t.status!=="complete"||t.fingerprint===void 0)return null;let n=Array.isArray(t.indexedLanguages)?[...t.indexedLanguages].sort():[];return ii(JSON.stringify({fingerprint:t.fingerprint,indexedLanguages:n}))}catch(t){return ya("project fingerprint unavailable",t),null}})}function ya(e,t){process.env.SCIP_QUERY_DEBUG&&console.error(`evidence-cache: ${e}: ${t instanceof Error?t.message:String(t)}`)}function ri(e){if(ho.has(e))return ho.get(e)??null;let t=null;try{let n=new OS(Au(_u(e.config.dbPath),jS));n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),n.pragma("synchronous = NORMAL"),n.exec(`
|
|
13
13
|
CREATE TABLE IF NOT EXISTS file_evidence (
|
|
14
14
|
kind TEXT NOT NULL,
|
|
15
15
|
relative_path TEXT NOT NULL,
|
|
@@ -35,20 +35,29 @@ import{program as Js}from"commander";import{realpathSync as Rb}from"fs";import{f
|
|
|
35
35
|
payload TEXT NOT NULL,
|
|
36
36
|
PRIMARY KEY (relative_path, symbol)
|
|
37
37
|
);
|
|
38
|
-
`),t={evidence:n,readFileEvidence:n.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),
|
|
39
|
-
WHERE
|
|
38
|
+
`),t={evidence:n,readFileEvidence:n.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),readLegacyFileEvidence:n.prepare(`SELECT payload FROM file_evidence
|
|
39
|
+
WHERE kind = ? AND relative_path = ? AND content_hash = ? AND ${ha}
|
|
40
|
+
ORDER BY version DESC
|
|
41
|
+
LIMIT 1`),writeFileEvidence:n.prepare("INSERT OR REPLACE INTO file_evidence (kind, relative_path, content_hash, version, payload) VALUES (?, ?, ?, ?, ?)"),readCallees:n.prepare(`SELECT payload FROM semantic_callees
|
|
42
|
+
WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND version = ?`),readLegacyCallees:n.prepare(`SELECT payload FROM semantic_callees
|
|
43
|
+
WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND ${ha}
|
|
44
|
+
ORDER BY version DESC
|
|
45
|
+
LIMIT 1`),writeCallees:n.prepare(`INSERT OR REPLACE INTO semantic_callees
|
|
40
46
|
(relative_path, symbol, content_hash, deps_digest, version, payload) VALUES (?, ?, ?, ?, ?, ?)`),dropStaleCallees:n.prepare("DELETE FROM semantic_callees WHERE relative_path = ? AND content_hash != ?"),readReferences:n.prepare(`SELECT payload FROM semantic_references
|
|
41
|
-
|
|
42
|
-
(relative_path, symbol, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)`),dropStaleReferences:n.prepare("DELETE FROM semantic_references WHERE project_fingerprint != ?")}}catch(n){na("disabled (open failed)",n)}return Qi.set(e,t),t}function Kn(e,t,n){na(`disabled (${t})`,n),Qi.set(e,null)}function Mt(e,t,n,r){let i=Jn(e);if(!i)return null;try{return i.readFileEvidence.get(t,n,r,Gn)?.payload??null}catch(o){return Kn(e,"file_evidence read",o),null}}function jt(e,t,n,r,i){let o=Jn(e);if(o)try{o.writeFileEvidence.run(t,n,r,Gn,i)}catch(s){Kn(e,"file_evidence write",s)}}function gu(e,t,n,r,i){let o=Jn(e);if(!o)return null;try{return o.readCallees.get(t,n,r,i,Gn)?.payload??null}catch(s){return Kn(e,"semantic_callees read",s),null}}function hu(e,t,n,r){let i=Jn(e);if(!i)return null;try{return i.readReferences.get(t,n,r,Gn)?.payload??null}catch(o){return Kn(e,"semantic_references read",o),null}}function yu(e,t){if(t.length===0)return;let n=Jn(e);if(n)try{n.evidence.transaction(()=>{let r=new Set;for(let i of t){let o=`${i.relativePath}\0${i.contentHash}`;r.has(o)||(r.add(o),n.dropStaleCallees.run(i.relativePath,i.contentHash)),n.writeCallees.run(i.relativePath,i.symbol,i.contentHash,i.depsDigest,Gn,i.payload)}})()}catch(r){Kn(e,"semantic_callees write",r)}}function bu(e,t){if(t.length===0)return;let n=Jn(e);if(n)try{n.evidence.transaction(()=>{let r=new Set;for(let i of t)r.has(i.projectFingerprint)||(r.add(i.projectFingerprint),n.dropStaleReferences.run(i.projectFingerprint)),n.writeReferences.run(i.relativePath,i.symbol,i.projectFingerprint,Gn,i.payload)})()}catch(r){Kn(e,"semantic_references write",r)}}function Hr(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var oS=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function Yi(e,t){let n=aS(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:Cu(n.functionNode),params:Su(n.functionNode),paramsEndLine:xu(n.functionNode),isLiteralPassthrough:vu(n.functionNode,t)};if(!sS(e.type,t))return null;let r=e.childForFieldName("name")??e.namedChildren.find(i=>i.type==="identifier"||i.type==="property_identifier");return r?{name:r.text,startLine:e.startPosition.row,endLine:e.endPosition.row,paramCount:Cu(e),params:Su(e),paramsEndLine:xu(e),isLiteralPassthrough:vu(e,t)}:null}function Ru(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function Su(e){let t=Ru(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(Hr(r))continue;if(r.type==="identifier"){n.push({name:r.text,simple:!0});continue}let i=r.namedChildren.some(a=>a.type.endsWith("_modifier"))||/^\s*(?:public|private|protected|readonly|override)\b/.test(r.text),o=r.childForFieldName("pattern");if(!i&&o&&o.type==="identifier"){n.push({name:o.text,simple:!0});continue}let s=r.namedChildren.find(a=>a.type==="identifier");n.push({name:o?.type==="identifier"?o.text:s?.text??"",simple:!1})}return n}function xu(e){let t=Ru(e);return t?t.endPosition.row:e.startPosition.row}function sS(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?oS.has(e):!1}function aS(e,t){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript")return null;if(e.type==="variable_declarator"){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);return!n||!r||r.type!=="arrow_function"&&r.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:r}}if(e.type==="public_field_definition"){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);return!n||!r||r.type!=="arrow_function"&&r.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:r}}return null}function Cu(e){let t=e.namedChildren.find(r=>r.type==="parameters"||r.type==="formal_parameters");if(!t)return 0;let n=0;for(let r of t.namedChildren)Hr(r)||(n+=1);return n}function vu(e,t){let n=e.namedChildren.find(d=>d.type==="block"||d.type==="statement_block");if(!n)return!1;let r=n.namedChildren.filter(d=>!Hr(d));if(r.length!==1)return!1;let i=r[0],o=null;if(i.type==="return_statement"||i.type==="expression_statement"?o=i.namedChild(0)??null:t==="rust"&&(i.type==="call_expression"||i.type==="macro_invocation")&&(o=i),!o)return!1;let s=t==="python"?"call":"call_expression";if(o.type!==s)return!1;let a=o.namedChildren.find(d=>d.type==="arguments"||d.type==="argument_list");if(!a)return!1;let c=a.namedChildren.filter(d=>!Hr(d)),l=e.namedChildren.find(d=>d.type==="parameters"||d.type==="formal_parameters");if(!l)return!1;let u=[];for(let d of l.namedChildren){if(d.type==="identifier"){u.push(d.text);continue}let m=d.namedChildren.find(f=>f.type==="identifier");m&&u.push(m.text)}if(c.length!==u.length)return!1;for(let d=0;d<u.length;d+=1){let m=c[d];if(m.type!=="identifier"||m.text!==u[d])return!1}return!0}var cS=new Set(["identifier","type_identifier","field_identifier"]),lS=new Set(["identifier"]),uS=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),dS=new Set(["rust","python"]),mS=/\{([^{}]*)\}/g,pS=/\b([A-Za-z_][\w]*)\b/g;function ku(e,t){return fS(t).has(e.type)}function wu(e,t){return dS.has(t)&&e.type==="string_content"}function ra(e){let t=0;for(let r of e.values()){let i=r[r.length-1];i!==void 0&&i>t&&(t=i)}let n=new Array(t+1);for(let r=0;r<=t;r+=1)n[r]=new Set;for(let[r,i]of e)for(let o of i)n[o].add(r);return n}function fS(e){return e==="rust"?cS:e==="python"?lS:uS}function Lu(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(mS)){let i=r[1]??"";for(let o of i.matchAll(pS))o[1]&&t(o[1],n)}}var gS=[/\bdefault\s*=\s*"([^"]+)"/g,/\bwith\s*=\s*"([^"]+)"/g,/\bserialize_with\s*=\s*"([^"]+)"/g,/\bdeserialize_with\s*=\s*"([^"]+)"/g,/\bskip_serializing_if\s*=\s*"([^"]+)"/g,/\bgetter\s*=\s*"([^"]+)"/g,/\brename_all_with\s*=\s*"([^"]+)"/g,/\bschema_with\s*=\s*"([^"]+)"/g],hS=/^#!?\[\s*serde\s*\(/,yS=/^#!?\[\s*schemars\s*\(/,bS=/^#!?\[\s*validate\s*\(/,SS=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function Iu(e,t,n){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript"||e.type!=="call_expression")return;let r=e.childForFieldName("function")??e.namedChild(0);if(!r)return;let i=Un(r);if(!i||!SS.has(i))return;let o=e.namedChildren.find(c=>c.type==="arguments");if(!o)return;let s=o.namedChild(0);if(!s||s.type!=="string")return;let a=s.namedChildren.find(c=>c.type==="string_fragment");a&&n.add(a.text)}function Du(e,t){let n=hS.test(e),r=yS.test(e),i=bS.test(e);if(!(!n&&!r&&!i))for(let o of gS){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;){let a=s[1],c=a.split("::").pop()??a;c==="is_none"&&/\bOption\b/.test(a)||c==="is_empty"&&/\b(String|Vec|HashMap|BTreeMap|HashSet|BTreeSet)\b/.test(a)||c&&t.add(c)}}}function Pu(e,t){let n=new Map,r=(s,a)=>{if(s===a)return;let c=n.get(s);c||(c=new Set,n.set(s,c)),c.add(a)},i=t==="python"?new Set(["identifier"]):new Set(["type_identifier"]),o=(s,a)=>{let c=l=>{i.has(l.type)&&l.text!==a&&r(l.text,a);for(let u of l.children)c(u)};for(let l of s.children)c(l)};if(t==="rust")for(let s of e.rootNode.descendantsOfType(["struct_item","enum_item","union_item","type_item"])){let a=s.namedChildren.find(l=>l.type==="type_identifier")?.text;if(!a)continue;let c=s.namedChildren.find(l=>l.type==="field_declaration_list"||l.type==="enum_variant_list"||l.type==="ordered_field_declaration_list");c&&o(c,a),s.type==="type_item"&&o(s,a)}else if(t==="python")for(let s of e.rootNode.descendantsOfType("class_definition")){let a=s.namedChildren.find(l=>l.type==="identifier")?.text;if(!a)continue;let c=s.namedChildren.find(l=>l.type==="block");if(c)for(let l of c.descendantsOfType("type"))for(let u of l.descendantsOfType("identifier"))u.text!==a&&r(u.text,a)}else for(let s of e.rootNode.descendantsOfType(["interface_declaration","type_alias_declaration","class_declaration"])){let a=s.namedChildren.find(c=>c.type==="type_identifier")?.text;a&&o(s,a)}return n}var xS=rn("source-facts",{clearGroups:["whole-project","source-file"]});function ae(e,t){let n=F(e,t);if(!n)return null;let r=CS(t,n);return r?xS.get(e,t,n,()=>vS(e,t,r,n)):null}function CS(e,t){return Rt(e)?Xi(t)?.language??null:W(e)}function vS(e,t,n,r){let i=Ye(e,t,r),o=Mt(e,"source-facts",t,i);if(o){let c=kS(o);if(c&&c.language===n)return c}let s=fe(e,t);if(!s)return null;let a=LS(s,n);return jt(e,"source-facts",t,i,RS(a)),a}function RS(e){let t={language:e.language,callables:e.callables,callSites:e.callSites,typeContainerMap:[...e.typeContainerMap.entries()].map(([n,r])=>[n,[...r]]),identifierLineMap:[...e.identifierLineMap.entries()],rustAttrReferencedNames:[...e.rustAttrReferencedNames],crossLanguageDispatchNames:[...e.crossLanguageDispatchNames]};return JSON.stringify(t)}function kS(e){try{let t=JSON.parse(e),n=new Map(t.identifierLineMap);return{language:t.language,callables:t.callables,callSites:t.callSites,typeContainerMap:new Map(t.typeContainerMap.map(([r,i])=>[r,new Set(i)])),identifierLineMap:n,identifiersByLine:ra(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function ia(e,t,n,r){let i=ae(e,t);return i?wS(i,n,r)?.isLiteralPassthrough??!0:!0}function wS(e,t,n){return e.callables.find(r=>r.startLine===t&&r.endLine===n)??null}function LS(e,t){let n=[],r=[],i=new Set,o=new Set,s=new Map,a=(l,u)=>{let d=s.get(l);if(!d){s.set(l,[u]);return}d[d.length-1]!==u&&d.push(u)},c=l=>{let u=Yi(l,t);u&&n.push(u);let d=Wn(l,t);d&&r.push(d),Iu(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&Du(l.text,i),ku(l,t)&&a(l.text,l.startPosition.row),wu(l,t)&&Lu(l,a);for(let m of l.children)c(m)};return c(e.rootNode),{language:t,callables:n,callSites:r,typeContainerMap:Pu(e,t),identifierLineMap:s,identifiersByLine:ra(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:i,crossLanguageDispatchNames:o}}var Nu=new Set(["rust","typescript","tsx","javascript","python"]);function oa(e,t){let n=ae(e,t);return!n||!Nu.has(n.language)?null:n.callables.map(r=>({name:r.name,startLine:r.startLine,endLine:r.endLine}))}function Xn(e,t){let n=ae(e,t);return!n||!Nu.has(n.language)?null:n.callSites}function sa(e,t){return ae(e,t)?.typeContainerMap??new Map}import{ElementTypes as IS,NodeTypes as Tu,parse as DS}from"@vue/compiler-dom";import{parse as pH}from"@vue/compiler-sfc";function Zi(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var PS=At("vue-template-facts"),NS=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),ES=new Set(["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","link","main","map","mark","menu","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","search","section","select","slot","small","source","span","strong","style","sub","summary","sup","svg","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr"]),TS=new Set(["div","span","template"]),_S=new Set(["as","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","false","finally","for","from","function","if","import","in","instanceof","let","new","null","of","return","super","switch","this","throw","true","try","typeof","undefined","var","void","while","with","yield"]);function _u(e,t){let n=t.replace(/\\/g,"/"),r=F(e,n);return PS.get(e,n,r,()=>FS(n,Ki(e,n).template))}function FS(e,t){let n={relativePath:e,template:t?{startLine:t.startLine,endLine:t.endLine}:null,componentTags:[],nativeTags:[],builtinTags:[],props:[],events:[],directives:[],slots:[],expressionIdentifiers:[],structuralTokens:[]};if(!t)return n;let r;try{r=DS(t.body,{comments:!1})}catch{return n}let i=new Set,o=s=>{s.trim()&&i.add(s)};return Fu(r.children,t.startLine,n,o),n.structuralTokens=[...i].sort(),n}function Fu(e,t,n,r){for(let i of e)i.type===Tu.ELEMENT&&($S(i,t,n,r),Fu(i.children,t,n,r))}function $S(e,t,n,r){let i=qS(e.tag),o={tag:e.tag,normalized:i,kind:VS(e),startLine:Qn(t,e.loc.start.line),endLine:Qn(t,e.loc.end.line)};o.kind==="component"?(n.componentTags.push(o),r(`component:${i}`)):o.kind==="builtin"?(n.builtinTags.push(o),r(`builtin:${i}`)):(n.nativeTags.push(o),TS.has(e.tag)||r(`native:${e.tag}`));for(let s of e.props)AS(s,t,n,r)}function AS(e,t,n,r){if(e.type===Tu.ATTRIBUTE){let a=e.value?.content??null,c=Eu("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),r(`prop:${e.name}`);return}let i=jS(e),o=$u(e.exp),s=Eu(MS(e.name),i,o,t,e.loc.start.line,e.loc.end.line);switch(s.kind){case"prop":n.props.push(s),r(`prop:${i}`);break;case"event":n.events.push(s),r(`event:${i}`);break;case"slot":n.slots.push(s),r(`slot:${i}`);break;case"directive":n.directives.push(s),r(`directive:${i}`);break}o&&OS(o,t,e.loc.start.line,n,r)}function Eu(e,t,n,r,i,o){return{kind:e,name:t,value:n,startLine:Qn(r,i),endLine:Qn(r,o)}}function MS(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function jS(e){let t=$u(e.arg);return t||e.name}function $u(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function OS(e,t,n,r,i){for(let o of BS(e)){let s={name:o,startLine:Qn(t,n),endLine:Qn(t,n)};r.expressionIdentifiers.push(s),i(`id:${o}`)}}function BS(e){let t=new Set,n=HS(e),r=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,i;for(;i=r.exec(n);){let o=i[0];_S.has(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function HS(e){return e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/`(?:\\[\s\S]|\$\{([^}]*)\}|[^`\\])*`/g,(t,n)=>n??" ").replace(/'(?:\\[\s\S]|[^'\\])*'/g," ").replace(/"(?:\\[\s\S]|[^"\\])*"/g," ")}function VS(e){let t=e.tag;return e.tagType===IS.COMPONENT?"component":NS.has(t)?"builtin":ES.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function qS(e){return Zi(e,/[-_:]/)}function Qn(e,t){return e+Math.max(0,t-1)}import{readdirSync as US}from"fs";import{execFileSync as WS}from"child_process";import{extname as eo,join as GS}from"path";var aa=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],Au=[".vue"],Mu=[".tsx",".jsx"],ju=[".vue"],zS=[...Mu,...ju],JS=new Set(Mu),KS=new Set(ju),Ou=new Set(aa.map(e=>e.toLowerCase())),XS=[...Ou].sort().join(","),ca=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function Ie(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(c=>c.toLowerCase()),o=i?new Set(i):Ou,s=i?[...o].sort().join(","):XS,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return QS.get(e,a,()=>{let c=new Set;if(n)for(let l of j(e,{includeIgnored:!1}))o.has(eo(l).toLowerCase())&&c.add(l);if(r)for(let l of YS(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}function to(e,t={}){let n=!1,r=!1;for(let i of Ie(e,{extensions:zS})){if(t.scope&&!i.includes(t.scope))continue;let o=eo(i).toLowerCase();if(n||=JS.has(o),r||=KS.has(o),n&&r)break}return{react:n,vue:r}}var QS=U("source-files",{clearGroups:[]});function YS(e,t){return ZS(e,t)??ex(e,t)}function ZS(e,t){try{let n=WS("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}),r=new Set;for(let i of n.split(`
|
|
43
|
-
|
|
44
|
-
`).length:0,u=on(r.template),d=o.lineCount,m=r.styles.reduce((h,g)=>h+on(g),0),f=r.customBlocks.reduce((h,g)=>h+on(g),0);return{file:t,sfc:r,templateFacts:i,scriptFacts:o,templateTokens:new Set(i.structuralTokens),behaviorTokens:bx(i,o,a),templateBindingNames:a,templateLocalNames:s,componentNames:c,sfcLines:l,totalLines:l+o.externalLineCount,templateLines:u,scriptLines:d,styleLines:m,externalScriptLines:o.externalLineCount,externalScriptPaths:o.externalScriptPaths,customBlockLines:f}}function hx(e){let t=yx(e.scriptFacts);return{...e,scriptFacts:t,templateTokens:new Set(e.templateTokens),behaviorTokens:new Set(e.behaviorTokens),templateBindingNames:[...e.templateBindingNames],templateLocalNames:[...e.templateLocalNames],componentNames:[...e.componentNames],externalScriptPaths:t.externalScriptPaths}}function yx(e){return{...e,imports:e.imports.map(t=>({...t})),functions:e.functions.map(t=>({...t})),calls:e.calls.map(t=>({...t,categories:[...t.categories]})),composables:[...e.composables],stores:[...e.stores],reactivity:[...e.reactivity],lifecycle:[...e.lifecycle],requests:[...e.requests],macros:[...e.macros],externalScriptPaths:[...e.externalScriptPaths],unresolvedScripts:e.unresolvedScripts.map(t=>({...t}))}}function bx(e,t,n){let r=new Set;for(let i of t.composables)r.add(`composable:${i}`);for(let i of t.stores)r.add(`store:${i}`);for(let i of t.reactivity)r.add(`reactivity:${i}`);for(let i of t.lifecycle)r.add(`lifecycle:${i}`);for(let i of t.requests)r.add(`request:${i}`);for(let i of t.macros)r.add(`macro:${i}`);for(let i of t.functions){if(mx.has(i.name))continue;r.add(`function:${i.name}`);let o=/^[a-z]+/.exec(i.name)?.[0]??null;o&&o.length>2&&o!==i.name&&r.add(`function-verb:${o}`)}for(let i of e.events)r.add(`template-event:${i.name}`);for(let i of n)r.add(`template-binding:${i}`);return r}function Sx(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let r of xx(n.value))t.add(r);for(let n of e.slots)if(n.value)for(let r of qu(n.value))t.add(r);return[...t].sort()}function xx(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?qu(t[1]??""):[]}function qu(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];dx.has(r)||t.push(r)}return t}import{extname as Cx}from"path";var vx=[".tsx",".jsx"],Uu=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),Rx=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),kx=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),wx=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),Lx=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),Ix=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),Dx=new Set(["children","className","false","key","null","style","true","undefined"]),Px=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]),Nx=At("react-component-behavior-profiles");function er(e,t={}){let n=Ie(e,{extensions:vx}).filter(i=>!t.scope||i.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).flatMap(i=>Ex(e,i)).filter(i=>(t.minJsxTokens===void 0||i.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function Ex(e,t){let n=t.replace(/\\/g,"/"),r=F(e,n);return Nx.get(e,n,r,()=>Tx(e,n)).map(_x)}function Tx(e,t){let n=Fx(t);if(!n)return[];let r=fe(e,t);if(!r)return[];let i=Qe(e,t).length;return $x(r.rootNode,n).filter(s=>s.kind==="hook"||Ku(s.bodyNode)).map(s=>{let a=Bx(s.bodyNode),c=Wx(s.bodyNode,n);return{file:t,name:s.name,kind:s.kind,startLine:s.node.startPosition.row,endLine:s.node.endPosition.row,loc:Math.max(1,s.node.endPosition.row-s.node.startPosition.row+1),fileLines:i,jsxTokens:a.tokens,behaviorTokens:c.tokens,componentNames:kt(a.componentNames),nativeTags:kt(a.nativeTags),propNames:kt(a.propNames),eventNames:kt(a.eventNames),hookNames:kt(c.hookNames),requestNames:kt(c.requestNames),stateNames:kt(c.stateNames),effectNames:kt(c.effectNames),handlerNames:kt(c.handlerNames)}})}function _x(e){return{...e,jsxTokens:new Set(e.jsxTokens),behaviorTokens:new Set(e.behaviorTokens),componentNames:[...e.componentNames],nativeTags:[...e.nativeTags],propNames:[...e.propNames],eventNames:[...e.eventNames],hookNames:[...e.hookNames],requestNames:[...e.requestNames],stateNames:[...e.stateNames],effectNames:[...e.effectNames],handlerNames:[...e.handlerNames]}}function Fx(e){let t=Cx(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:W(e)}function $x(e,t){let n=[],r=new Set,i=o=>{let s=Ax(o);if(s&&!jx(o)){let a=`${s.name}:${s.node.startIndex}:${s.node.endIndex}`;r.has(a)||(r.add(a),n.push(s));return}for(let a of o.namedChildren)i(a)};return(t==="tsx"||t==="javascript")&&i(e),n}function Ax(e){if(e.type==="function_declaration"){let o=Ju(e);return!o||!Wu(o)?null:{name:o,kind:Gu(o),node:e,bodyNode:e}}if(e.type!=="variable_declarator")return null;let t=e.childForFieldName("name")??e.namedChild(0),n=e.childForFieldName("value")??e.namedChild(1),r=Vr(t);if(!r||!n||!Wu(r))return null;let i=Mx(n);return i?{name:r,kind:Gu(r),node:e,bodyNode:i}:null}function Wu(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function Gu(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function Mx(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=Ox(e);return t!=="memo"&&t!=="forwardRef"?null:e.namedChildren.find(i=>i.type==="arguments")?.namedChildren.find(i=>i.type==="arrow_function"||i.type==="function_expression")??null}function jx(e){let t=e.parent;for(;t;){if(t.type==="function_declaration"||t.type==="function_expression"||t.type==="arrow_function"||t.type==="method_definition")return!0;t=t.parent}return!1}function Ju(e){return Vr(e.childForFieldName("name")??e.namedChild(0))}function Ox(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function Ku(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(Ku)}function Bx(e){let t={tokens:new Set,componentNames:new Set,nativeTags:new Set,propNames:new Set,eventNames:new Set},n=r=>{r.type==="jsx_opening_element"||r.type==="jsx_self_closing_element"?Hx(r,t):r.type==="jsx_expression"?Vx(r,t):r.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let i of r.namedChildren)n(i)};return n(e),t}function Hx(e,t){let n=qx(e),r=!1;if(n){let i=zu(n);r=Xx(i),r?(t.componentNames.add(i),t.tokens.add(`component:${i}`)):(t.nativeTags.add(i),t.tokens.add(`native:${i}`))}for(let i of e.namedChildren)if(i.type==="jsx_attribute"){let o=Ux(i);if(!o)continue;let s=zu(o);if(s.startsWith("on")&&s.length>2){let a=s.slice(2).replace(/^[A-Z]/,c=>c.toLowerCase());t.eventNames.add(a),t.tokens.add(`event:${a}`)}else Px.has(s)||(t.propNames.add(s),t.tokens.add(`${r?"prop":"native-prop"}:${s}`))}else i.type==="jsx_spread_attribute"&&t.tokens.add("prop:spread")}function Vx(e,t){let n=e.text;(n.includes("&&")||n.includes("?"))&&t.tokens.add("jsx:conditional"),(n.includes(".map(")||n.includes(".flatMap("))&&t.tokens.add("jsx:list");for(let r of Qx(n))Dx.has(r)||t.tokens.add(`binding:${r}`)}function qx(e){for(let t of e.namedChildren)if(t.type==="identifier"||t.type==="jsx_identifier"||t.type==="property_identifier"||t.type==="member_expression"||t.type==="jsx_member_expression")return t.text;return/^<\s*([A-Za-z][\w$.]*)/.exec(e.text)?.[1]??null}function Ux(e){for(let t of e.namedChildren)if(t.type==="property_identifier"||t.type==="identifier"||t.type==="jsx_identifier")return t.text;return/^([A-Za-z_$][\w$:-]*)/.exec(e.text)?.[1]??null}function Wx(e,t){let n={tokens:new Set,hookNames:new Set,requestNames:new Set,stateNames:new Set,effectNames:new Set,handlerNames:new Set},r=i=>{if(i.type==="call_expression"){let o=Wn(i,t);o&&Gx(o.calleeLeaf,n)}else if(i.type==="variable_declarator")Jx(i,n);else if(i.type==="function_declaration"){let o=Ju(i);o&&Xu(o,n)}for(let o of i.namedChildren)r(o)};return r(e),n}function Gx(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!Uu.has(e)&&!wx.has(e)&&t.tokens.add(`hook:${e}`)),Uu.has(e)&&t.tokens.add(`react-hook:${e}`),Rx.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),kx.has(e)&&t.tokens.add(`state-hook:${e}`),zx(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function zx(e){if(Lx.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function Jx(e,t){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);if(n?.type==="array_pattern"&&r?.text.includes("useState")){let o=n.namedChildren.find(a=>Vr(a)),s=Vr(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let i=Vr(n);i&&Xu(i,t)}function Xu(e,t){let n=Kx(e);!n||!Ix.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function Kx(e){let t=e.startsWith("handle")&&e.length>6?e.slice(6).replace(/^[A-Z]/,n=>n.toLowerCase()):e;return/^[a-z]+/.exec(t)?.[0]??null}function Xx(e){return/^[A-Z]/.test(e)||e.includes(".")}function zu(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function Vr(e){return e&&(e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"||/^[A-Za-z_$][\w$]*$/.test(e.text))?e.text:null}function Qx(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];t.includes(r)||t.push(r)}return t}function kt(e){return[...e].sort()}function sn(e,t,n={}){let r=ae(e,t);if(!r)return[];let i=[];if(n.includeCrossLanguageDispatchNames)for(let o of r.crossLanguageDispatchNames)i.push({name:o,kind:"cross-language-dispatch",occurrences:1});if(n.includeRustAttributeNames&&r.language==="rust")for(let o of r.rustAttrReferencedNames)i.push({name:o,kind:"rust-attribute",occurrences:1});return i}var Yx={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function ge(e){if(e.startsWith("local "))return{kind:"local",id:e.slice(6),raw:e};let t=e.split(" ");if(t.length<4)return{scheme:t[0]??"",manager:t[1]??"",packageName:t[2]??"",version:"",descriptors:[],raw:e};let n=t[0],r=t[1],i=e.slice(n.length+1+r.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let s,a=i.indexOf(" ");a===-1?(s=i,i=""):(s=i.slice(0,a),i=i.slice(a+1));let c=Zx(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function lt(e){let t=ge(e);if("kind"in t)return null;for(let n=t.descriptors.length-2;n>=0;n--){let r=t.descriptors[n];if(r?.suffix==="type")return r.name}return null}function Zx(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="["){let o=e.indexOf("]",n+1);if(o===-1){t.push({name:e.slice(n+1),suffix:"type-param"});break}t.push({name:e.slice(n+1,o),suffix:"type-param"}),n=o+1;continue}if(e[n]==="("&&(t.length===0||n===0||Qu(e[n-1]))){let o=e.indexOf(")",n+1);if(o!==-1&&e[o+1]!=="."){t.push({name:e.slice(n+1,o),suffix:"parameter"}),n=o+1;continue}}let r;if(e[n]==="`"){let o=e.indexOf("`",n+1);if(o===-1){r=e.slice(n+1),t.push({name:r,suffix:"term"});break}r=e.slice(n+1,o),n=o+1}else{let o=n;for(;n<e.length&&!Qu(e[n]);)n++;r=e.slice(o,n)}if(n>=e.length){r&&t.push({name:r,suffix:"term"});break}let i=e[n];if(i==="("){let o=e.indexOf(")",n+1);o!==-1&&e[o+1]==="."?(t.push({name:r,suffix:"method"}),n=o+2):o!==-1?(t.push({name:r,suffix:"method"}),n=o+1):(t.push({name:r,suffix:"term"}),n++)}else{let o=Yx[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function Qu(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function b(e){let t=ge(e);if("kind"in t&&t.kind==="local")return`local:${t.id}`;let n=t;if(n.descriptors.length===0)return n.raw;let r=[];for(let i of n.descriptors){let o=eC(i);o&&r.push(o)}return r.join(":")}function eC(e){let t=e.suffix==="namespace"?tC(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function tC(e){return e.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/,"").replace(/\.(py|pyi)$/,"").replace(/\.(rs)$/,"").replace(/\.(java|scala|kt|kts)$/,"").replace(/\.(rb)$/,"").replace(/\.(go)$/,"").replace(/\.(cs|vb)$/,"").replace(/\.(dart)$/,"").replace(/\.(php)$/,"").replace(/\.(c|cc|cpp|cxx|h|hpp)$/,"")}function $(e){let t=ge(e);if("kind"in t&&t.kind==="local")return t.id;let n=t;return n.descriptors.length===0?"":n.descriptors[n.descriptors.length-1].name}function ee(e){let t=ge(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function Ce(e){return e.endsWith("().")||ee(e)==="method"}function ce(e){let t=ee(e);return t==="method"||t==="term"}function Ot(e){return ee(e)==="namespace"}var nC=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function ro(e){return nC.test(e)}var rC=new Set(["test","tests","_tests"]);function tr(e){let t=ge(e);if("kind"in t)return!1;for(let n=0;n<t.descriptors.length-1;n+=1){let r=t.descriptors[n];if(r?.suffix==="namespace"&&r.name&&rC.has(r.name))return!0}return!1}function Yu(e,t){let n=ge(e),r=ge(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,o=r.descriptors;if(o.length!==i.length+1)return!1;for(let s=0;s<i.length;s++){let a=i[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function Zu(e,t){let n=ge(e),r=ge(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,o=r.descriptors;if(o.length<=i.length)return!1;for(let s=0;s<i.length;s++){let a=i[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function nr(e,t){return e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name, gs.documentation
|
|
47
|
+
WHERE relative_path = ? AND symbol = ? AND project_fingerprint = ? AND version = ?`),readLegacyReferences:n.prepare(`SELECT payload FROM semantic_references
|
|
48
|
+
WHERE relative_path = ? AND symbol = ? AND project_fingerprint = ? AND ${ha}
|
|
49
|
+
ORDER BY version DESC
|
|
50
|
+
LIMIT 1`),writeReferences:n.prepare(`INSERT OR REPLACE INTO semantic_references
|
|
51
|
+
(relative_path, symbol, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)`),dropStaleReferences:n.prepare("DELETE FROM semantic_references WHERE project_fingerprint != ?")}}catch(n){ya("disabled (open failed)",n)}return ho.set(e,t),t}function oi(e,t,n){ya(`disabled (${t})`,n),ho.set(e,null)}function ae(e,t,n,i){let r=ri(e);if(!r)return null;try{return(r.readFileEvidence.get(t,n,i,ni)??r.readLegacyFileEvidence.get(t,n,i))?.payload??null}catch(o){return oi(e,"file_evidence read",o),null}}function ce(e,t,n,i,r){let o=ri(e);if(o)try{o.writeFileEvidence.run(t,n,i,ni,r)}catch(s){oi(e,"file_evidence write",s)}}function $u(e,t,n,i,r){let o=ri(e);if(!o)return null;try{return(o.readCallees.get(t,n,i,r,ni)??o.readLegacyCallees.get(t,n,i,r))?.payload??null}catch(s){return oi(e,"semantic_callees read",s),null}}function Mu(e,t,n,i){let r=ri(e);if(!r)return null;try{return(r.readReferences.get(t,n,i,ni)??r.readLegacyReferences.get(t,n,i))?.payload??null}catch(o){return oi(e,"semantic_references read",o),null}}function Ou(e,t){if(t.length===0)return;let n=ri(e);if(n)try{n.evidence.transaction(()=>{let i=new Set;for(let r of t){let o=`${r.relativePath}\0${r.contentHash}`;i.has(o)||(i.add(o),n.dropStaleCallees.run(r.relativePath,r.contentHash)),n.writeCallees.run(r.relativePath,r.symbol,r.contentHash,r.depsDigest,ni,r.payload)}})()}catch(i){oi(e,"semantic_callees write",i)}}function ju(e,t){if(t.length===0)return;let n=ri(e);if(n)try{n.evidence.transaction(()=>{let i=new Set;for(let r of t)i.has(r.projectFingerprint)||(i.add(r.projectFingerprint),n.dropStaleReferences.run(r.projectFingerprint)),n.writeReferences.run(r.relativePath,r.symbol,r.projectFingerprint,ni,r.payload)})()}catch(i){oi(e,"semantic_references write",i)}}function tr(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var VS=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function yo(e,t){let n=US(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:Vu(n.functionNode),params:Bu(n.functionNode),paramsEndLine:Hu(n.functionNode),isLiteralPassthrough:qu(n.functionNode,t)};if(!qS(e.type,t))return null;let i=e.childForFieldName("name")??e.namedChildren.find(r=>r.type==="identifier"||r.type==="property_identifier");return i?{name:i.text,startLine:e.startPosition.row,endLine:e.endPosition.row,paramCount:Vu(e),params:Bu(e),paramsEndLine:Hu(e),isLiteralPassthrough:qu(e,t)}:null}function Uu(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function Bu(e){let t=Uu(e);if(!t)return[];let n=[];for(let i of t.namedChildren){if(tr(i))continue;if(i.type==="identifier"){n.push({name:i.text,simple:!0});continue}let r=i.namedChildren.some(a=>a.type.endsWith("_modifier"))||/^\s*(?:public|private|protected|readonly|override)\b/.test(i.text),o=i.childForFieldName("pattern");if(!r&&o&&o.type==="identifier"){n.push({name:o.text,simple:!0});continue}let s=i.namedChildren.find(a=>a.type==="identifier");n.push({name:o?.type==="identifier"?o.text:s?.text??"",simple:!1})}return n}function Hu(e){let t=Uu(e);return t?t.endPosition.row:e.startPosition.row}function qS(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?VS.has(e):!1}function US(e,t){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript")return null;if(e.type==="variable_declarator"){let n=e.childForFieldName("name")??e.namedChild(0),i=e.childForFieldName("value")??e.namedChild(1);return!n||!i||i.type!=="arrow_function"&&i.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:i}}if(e.type==="public_field_definition"){let n=e.childForFieldName("name")??e.namedChild(0),i=e.childForFieldName("value")??e.namedChild(1);return!n||!i||i.type!=="arrow_function"&&i.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:i}}return null}function Vu(e){let t=e.namedChildren.find(i=>i.type==="parameters"||i.type==="formal_parameters");if(!t)return 0;let n=0;for(let i of t.namedChildren)tr(i)||(n+=1);return n}function qu(e,t){let n=e.namedChildren.find(d=>d.type==="block"||d.type==="statement_block");if(!n)return!1;let i=n.namedChildren.filter(d=>!tr(d));if(i.length!==1)return!1;let r=i[0],o=null;if(r.type==="return_statement"||r.type==="expression_statement"?o=r.namedChild(0)??null:t==="rust"&&(r.type==="call_expression"||r.type==="macro_invocation")&&(o=r),!o)return!1;let s=t==="python"?"call":"call_expression";if(o.type!==s)return!1;let a=o.namedChildren.find(d=>d.type==="arguments"||d.type==="argument_list");if(!a)return!1;let c=a.namedChildren.filter(d=>!tr(d)),l=e.namedChildren.find(d=>d.type==="parameters"||d.type==="formal_parameters");if(!l)return!1;let u=[];for(let d of l.namedChildren){if(d.type==="identifier"){u.push(d.text);continue}let m=d.namedChildren.find(p=>p.type==="identifier");m&&u.push(m.text)}if(c.length!==u.length)return!1;for(let d=0;d<u.length;d+=1){let m=c[d];if(m.type!=="identifier"||m.text!==u[d])return!1}return!0}var WS=new Set(["identifier","type_identifier","field_identifier"]),zS=new Set(["identifier"]),GS=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),JS=new Set(["rust","python"]),KS=/\{([^{}]*)\}/g,QS=/\b([A-Za-z_][\w]*)\b/g;function Wu(e,t){return XS(t).has(e.type)}function zu(e,t){return JS.has(t)&&e.type==="string_content"}function ba(e){let t=0;for(let i of e.values()){let r=i[i.length-1];r!==void 0&&r>t&&(t=r)}let n=new Array(t+1);for(let i=0;i<=t;i+=1)n[i]=new Set;for(let[i,r]of e)for(let o of r)n[o].add(i);return n}function XS(e){return e==="rust"?WS:e==="python"?zS:GS}function Gu(e,t){let n=e.startPosition.row;for(let i of e.text.matchAll(KS)){let r=i[1]??"";for(let o of r.matchAll(QS))o[1]&&t(o[1],n)}}var YS=[/\bdefault\s*=\s*"([^"]+)"/g,/\bwith\s*=\s*"([^"]+)"/g,/\bserialize_with\s*=\s*"([^"]+)"/g,/\bdeserialize_with\s*=\s*"([^"]+)"/g,/\bskip_serializing_if\s*=\s*"([^"]+)"/g,/\bgetter\s*=\s*"([^"]+)"/g,/\brename_all_with\s*=\s*"([^"]+)"/g,/\bschema_with\s*=\s*"([^"]+)"/g],ZS=/^#!?\[\s*serde\s*\(/,ex=/^#!?\[\s*schemars\s*\(/,tx=/^#!?\[\s*validate\s*\(/,nx=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function Ju(e,t,n){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript"||e.type!=="call_expression")return;let i=e.childForFieldName("function")??e.namedChild(0);if(!i)return;let r=ei(i);if(!r||!nx.has(r))return;let o=e.namedChildren.find(c=>c.type==="arguments");if(!o)return;let s=o.namedChild(0);if(!s||s.type!=="string")return;let a=s.namedChildren.find(c=>c.type==="string_fragment");a&&n.add(a.text)}function Ku(e,t){let n=ZS.test(e),i=ex.test(e),r=tx.test(e);if(!(!n&&!i&&!r))for(let o of YS){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;){let a=s[1],c=a.split("::").pop()??a;c==="is_none"&&/\bOption\b/.test(a)||c==="is_empty"&&/\b(String|Vec|HashMap|BTreeMap|HashSet|BTreeSet)\b/.test(a)||c&&t.add(c)}}}function Qu(e,t){let n=new Map,i=(s,a)=>{if(s===a)return;let c=n.get(s);c||(c=new Set,n.set(s,c)),c.add(a)},r=t==="python"?new Set(["identifier"]):new Set(["type_identifier"]),o=(s,a)=>{let c=l=>{r.has(l.type)&&l.text!==a&&i(l.text,a);for(let u of l.children)c(u)};for(let l of s.children)c(l)};if(t==="rust")for(let s of e.rootNode.descendantsOfType(["struct_item","enum_item","union_item","type_item"])){let a=s.namedChildren.find(l=>l.type==="type_identifier")?.text;if(!a)continue;let c=s.namedChildren.find(l=>l.type==="field_declaration_list"||l.type==="enum_variant_list"||l.type==="ordered_field_declaration_list");c&&o(c,a),s.type==="type_item"&&o(s,a)}else if(t==="python")for(let s of e.rootNode.descendantsOfType("class_definition")){let a=s.namedChildren.find(l=>l.type==="identifier")?.text;if(!a)continue;let c=s.namedChildren.find(l=>l.type==="block");if(c)for(let l of c.descendantsOfType("type"))for(let u of l.descendantsOfType("identifier"))u.text!==a&&i(u.text,a)}else for(let s of e.rootNode.descendantsOfType(["interface_declaration","type_alias_declaration","class_declaration"])){let a=s.namedChildren.find(c=>c.type==="type_identifier")?.text;a&&o(s,a)}return n}var ix=dn("source-facts",{clearGroups:["whole-project","source-file"]});function ye(e,t){let n=F(e,t);if(!n)return null;let i=rx(t,n);return i?ix.get(e,t,n,()=>ox(e,t,i,n)):null}function rx(e,t){return Nt(e)?go(t)?.language??null:K(e)}function ox(e,t,n,i){let r=Z(e,t,i),o=ae(e,"source-facts",t,r);if(o){let c=ax(o);if(c&&c.language===n)return c}let s=ke(e,t);if(!s)return null;let a=lx(s,n);return ce(e,"source-facts",t,r,sx(a)),a}function sx(e){let t={language:e.language,callables:e.callables,callSites:e.callSites,typeContainerMap:[...e.typeContainerMap.entries()].map(([n,i])=>[n,[...i]]),identifierLineMap:[...e.identifierLineMap.entries()],rustAttrReferencedNames:[...e.rustAttrReferencedNames],crossLanguageDispatchNames:[...e.crossLanguageDispatchNames]};return JSON.stringify(t)}function ax(e){try{let t=JSON.parse(e),n=new Map(t.identifierLineMap);return{language:t.language,callables:t.callables,callSites:t.callSites,typeContainerMap:new Map(t.typeContainerMap.map(([i,r])=>[i,new Set(r)])),identifierLineMap:n,identifiersByLine:ba(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function Sa(e,t,n,i){let r=ye(e,t);return r?cx(r,n,i)?.isLiteralPassthrough??!0:!0}function cx(e,t,n){return e.callables.find(i=>i.startLine===t&&i.endLine===n)??null}function lx(e,t){let n=[],i=[],r=new Set,o=new Set,s=new Map,a=(l,u)=>{let d=s.get(l);if(!d){s.set(l,[u]);return}d[d.length-1]!==u&&d.push(u)},c=l=>{let u=yo(l,t);u&&n.push(u);let d=ti(l,t);d&&i.push(d),Ju(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&Ku(l.text,r),Wu(l,t)&&a(l.text,l.startPosition.row),zu(l,t)&&Gu(l,a);for(let m of l.children)c(m)};return c(e.rootNode),{language:t,callables:n,callSites:i,typeContainerMap:Qu(e,t),identifierLineMap:s,identifiersByLine:ba(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:r,crossLanguageDispatchNames:o}}var Xu=new Set(["rust","typescript","tsx","javascript","python"]);function xa(e,t){let n=ye(e,t);return!n||!Xu.has(n.language)?null:n.callables.map(i=>({name:i.name,startLine:i.startLine,endLine:i.endLine}))}function si(e,t){let n=ye(e,t);return!n||!Xu.has(n.language)?null:n.callSites}function Ca(e,t){return ye(e,t)?.typeContainerMap??new Map}import{ElementTypes as ux,NodeTypes as Zu,parse as dx}from"@vue/compiler-dom";import{parse as ZV}from"@vue/compiler-sfc";function bo(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var mx=qt("vue-template-facts"),px=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),fx=new Set(["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","link","main","map","mark","menu","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","search","section","select","slot","small","source","span","strong","style","sub","summary","sup","svg","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr"]),gx=new Set(["div","span","template"]),hx=new Set(["as","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","false","finally","for","from","function","if","import","in","instanceof","let","new","null","of","return","super","switch","this","throw","true","try","typeof","undefined","var","void","while","with","yield"]);function ed(e,t){let n=t.replace(/\\/g,"/"),i=F(e,n);return mx.get(e,n,i,()=>yx(n,fo(e,n).template))}function yx(e,t){let n={relativePath:e,template:t?{startLine:t.startLine,endLine:t.endLine}:null,componentTags:[],nativeTags:[],builtinTags:[],props:[],events:[],directives:[],slots:[],expressionIdentifiers:[],structuralTokens:[]};if(!t)return n;let i;try{i=dx(t.body,{comments:!1})}catch{return n}let r=new Set,o=s=>{s.trim()&&r.add(s)};return td(i.children,t.startLine,n,o),n.structuralTokens=[...r].sort(),n}function td(e,t,n,i){for(let r of e)r.type===Zu.ELEMENT&&(bx(r,t,n,i),td(r.children,t,n,i))}function bx(e,t,n,i){let r=Ix(e.tag),o={tag:e.tag,normalized:r,kind:wx(e),startLine:ai(t,e.loc.start.line),endLine:ai(t,e.loc.end.line)};o.kind==="component"?(n.componentTags.push(o),i(`component:${r}`)):o.kind==="builtin"?(n.builtinTags.push(o),i(`builtin:${r}`)):(n.nativeTags.push(o),gx.has(e.tag)||i(`native:${e.tag}`));for(let s of e.props)Sx(s,t,n,i)}function Sx(e,t,n,i){if(e.type===Zu.ATTRIBUTE){let a=e.value?.content??null,c=Yu("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),i(`prop:${e.name}`);return}let r=Cx(e),o=nd(e.exp),s=Yu(xx(e.name),r,o,t,e.loc.start.line,e.loc.end.line);switch(s.kind){case"prop":n.props.push(s),i(`prop:${r}`);break;case"event":n.events.push(s),i(`event:${r}`);break;case"slot":n.slots.push(s),i(`slot:${r}`);break;case"directive":n.directives.push(s),i(`directive:${r}`);break}o&&vx(o,t,e.loc.start.line,n,i)}function Yu(e,t,n,i,r,o){return{kind:e,name:t,value:n,startLine:ai(i,r),endLine:ai(i,o)}}function xx(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function Cx(e){let t=nd(e.arg);return t||e.name}function nd(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function vx(e,t,n,i,r){for(let o of Rx(e)){let s={name:o,startLine:ai(t,n),endLine:ai(t,n)};i.expressionIdentifiers.push(s),r(`id:${o}`)}}function Rx(e){let t=new Set,n=kx(e),i=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,r;for(;r=i.exec(n);){let o=r[0];hx.has(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function kx(e){return e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/`(?:\\[\s\S]|\$\{([^}]*)\}|[^`\\])*`/g,(t,n)=>n??" ").replace(/'(?:\\[\s\S]|[^'\\])*'/g," ").replace(/"(?:\\[\s\S]|[^"\\])*"/g," ")}function wx(e){let t=e.tag;return e.tagType===ux.COMPONENT?"component":px.has(t)?"builtin":fx.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function Ix(e){return bo(e,/[-_:]/)}function ai(e,t){return e+Math.max(0,t-1)}import{readdirSync as Lx}from"fs";import{execFileSync as Dx}from"child_process";import{extname as So,join as Px}from"path";var va=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],id=[".vue"],rd=[".tsx",".jsx"],od=[".vue"],Nx=[...rd,...od],Ex=new Set(rd),Tx=new Set(od),sd=new Set(va.map(e=>e.toLowerCase())),Fx=[...sd].sort().join(","),Ra=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function $e(e,t={}){let n=t.includeIndexed??!0,i=t.includeAuxiliary??!0,r=t.extensions?.map(c=>c.toLowerCase()),o=r?new Set(r):sd,s=r?[...o].sort().join(","):Fx,a=`${n?"1":"0"}|${i?"1":"0"}|${s}`;return _x.get(e,a,()=>{let c=new Set;if(n)for(let l of B(e,{includeIgnored:!1}))o.has(So(l).toLowerCase())&&c.add(l);if(i)for(let l of Ax(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}function xo(e,t={}){let n=!1,i=!1;for(let r of $e(e,{extensions:Nx})){if(t.scope&&!r.includes(t.scope))continue;let o=So(r).toLowerCase();if(n||=Ex.has(o),i||=Tx.has(o),n&&i)break}return{react:n,vue:i}}var _x=U("source-files",{clearGroups:[]});function Ax(e,t){return $x(e,t)??Mx(e,t)}function $x(e,t){try{let n=Dx("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}),i=new Set;for(let r of n.split(`
|
|
52
|
+
`)){let o=r.trim();o&&t.has(So(o).toLowerCase())&&i.add(o)}return i}catch{return null}}function Mx(e,t){let n=new Set,i=r=>{let o=r?Px(e,r):e,s;try{s=Lx(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!Ra.has(a.name)){if(a.isDirectory()){i(r?`${r}/${a.name}`:a.name);continue}t.has(So(a.name).toLowerCase())&&n.add(r?`${r}/${a.name}`:a.name)}};return i(""),n}var Ox=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),jx=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),Bx=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),Hx=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),Vx=new Set(["catch","for","function","if","return","switch","while"]);function ad(e){let t={imports:[],functions:[],calls:[],composables:[],stores:[],reactivity:[],lifecycle:[],requests:[],macros:[],lineCount:0,externalLineCount:0,externalScriptPaths:[],unresolvedScripts:[]};for(let n of e.scripts){t.lineCount+=mn(n),n.external&&(t.externalLineCount+=mn(n),t.externalScriptPaths.push(n.sourcePath));for(let r of n.errors)t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:r});if(!n.body||!n.astLanguage){n.astLanguage||t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:`Unsupported Vue script language: ${n.lang??"unknown"}`});continue}t.imports.push(...zx(n));let i=Yi(n.astLanguage,n.body);i?Ux(n,i.rootNode,t):Wx(n,t)}return qx(t),t.externalScriptPaths=ld(t.externalScriptPaths),t}function qx(e){e.composables=ci(e,"composable"),e.stores=ci(e,"store"),e.reactivity=ci(e,"reactivity"),e.lifecycle=ci(e,"lifecycle"),e.requests=ci(e,"request"),e.macros=ci(e,"macro")}function ci(e,t){return ld(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function Ux(e,t,n){let i=new Set,r=new Set,o=s=>{let a=yo(s,e.astLanguage);if(a){let l=`${a.name}:${a.startLine}:${a.endLine}`;r.has(l)||(r.add(l),n.functions.push({name:a.name,sourcePath:e.sourcePath,startLine:e.startLine+a.startLine,endLine:e.startLine+a.endLine,setup:e.setup}))}let c=ti(s,e.astLanguage);if(c){let l=`${c.calleeLeaf}:${c.line}`;i.has(l)||(i.add(l),n.calls.push({name:c.calleeLeaf,sourcePath:e.sourcePath,line:e.startLine+c.line,categories:cd(c.calleeLeaf),setup:e.setup}))}for(let l of s.children)o(l)};o(t)}function Wx(e,t){for(let n of e.body.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)){let i=n[1];!i||Vx.has(i)||t.calls.push({name:i,sourcePath:e.sourcePath,line:e.startLine+Co(e.body,n.index??0),categories:cd(i),setup:e.setup})}for(let n of e.body.matchAll(/\bfunction\s+([A-Za-z_$][\w$]*)\b/g)){let i=n[1];if(!i)continue;let r=e.startLine+Co(e.body,n.index??0);t.functions.push({name:i,sourcePath:e.sourcePath,startLine:r,endLine:r,setup:e.setup})}for(let n of e.body.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/g)){let i=n[1];if(!i)continue;let r=e.startLine+Co(e.body,n.index??0);t.functions.push({name:i,sourcePath:e.sourcePath,startLine:r,endLine:r,setup:e.setup})}}function zx(e){let t=[];for(let n of e.body.matchAll(/\bimport\s+(?:type\s+)?([^'";]+?)\s+from\s+['"]([^'"]+)['"]/g)){let i=n[1]?.trim(),r=n[2];if(!i||!r)continue;let o=e.startLine+Co(e.body,n.index??0);for(let s of Gx(i))t.push({local:s,source:r,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function Gx(e){let t=[],i=e.split(",").map(s=>s.trim()).filter(Boolean)[0];i&&!i.startsWith("{")&&!i.startsWith("*")&&t.push(i);let r=/\{([^}]*)\}/.exec(e)?.[1];if(r)for(let s of r.split(",")){let a=s.trim();if(!a)continue;let c=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(a)?.[1];t.push(c??a.replace(/^type\s+/,"").trim())}let o=/\*\s+as\s+([A-Za-z_$][\w$]*)/.exec(e)?.[1];return o&&t.push(o),t.filter(s=>/^[A-Za-z_$][\w$]*$/.test(s))}function cd(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),Ox.has(e)&&t.push("reactivity"),jx.has(e)&&t.push("lifecycle"),Bx.has(e)&&t.push("request"),Hx.has(e)&&t.push("macro"),t}function Co(e,t){let n=0;for(let i=0;i<t&&i<e.length;i+=1)e.charCodeAt(i)===10&&(n+=1);return n}function ld(e){return[...new Set(e)].sort()}var Jx=new Set(["in","key","of"]),Kx=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]),Qx=qt("vue-component-behavior-profiles");function li(e,t={}){let n=$e(e,{extensions:[".vue"]}).filter(r=>!t.scope||r.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).map(r=>Xx(e,r)).filter(r=>(t.minTemplateTokens===void 0||r.templateTokens.size>=t.minTemplateTokens)&&(t.minBehaviorTokens===void 0||r.behaviorTokens.size>=t.minBehaviorTokens))}function Xx(e,t){let n=t.replace(/\\/g,"/"),i=F(e,n),r=Qx.get(e,n,i,()=>Yx(e,n,i));return Zx(r)}function Yx(e,t,n){let i=fo(e,t),r=ed(e,t),o=ad(i),s=nC(r),a=r.expressionIdentifiers.map(f=>f.name).filter(f=>!s.includes(f)).filter((f,g,y)=>y.indexOf(f)===g).sort(),c=r.componentTags.map(f=>f.normalized).filter((f,g,y)=>y.indexOf(f)===g).sort(),l=n?n.split(`
|
|
53
|
+
`).length:0,u=mn(i.template),d=o.lineCount,m=i.styles.reduce((f,g)=>f+mn(g),0),p=i.customBlocks.reduce((f,g)=>f+mn(g),0);return{file:t,sfc:i,templateFacts:r,scriptFacts:o,templateTokens:new Set(r.structuralTokens),behaviorTokens:tC(r,o,a),templateBindingNames:a,templateLocalNames:s,componentNames:c,sfcLines:l,totalLines:l+o.externalLineCount,templateLines:u,scriptLines:d,styleLines:m,externalScriptLines:o.externalLineCount,externalScriptPaths:o.externalScriptPaths,customBlockLines:p}}function Zx(e){let t=eC(e.scriptFacts);return{...e,scriptFacts:t,templateTokens:new Set(e.templateTokens),behaviorTokens:new Set(e.behaviorTokens),templateBindingNames:[...e.templateBindingNames],templateLocalNames:[...e.templateLocalNames],componentNames:[...e.componentNames],externalScriptPaths:t.externalScriptPaths}}function eC(e){return{...e,imports:e.imports.map(t=>({...t})),functions:e.functions.map(t=>({...t})),calls:e.calls.map(t=>({...t,categories:[...t.categories]})),composables:[...e.composables],stores:[...e.stores],reactivity:[...e.reactivity],lifecycle:[...e.lifecycle],requests:[...e.requests],macros:[...e.macros],externalScriptPaths:[...e.externalScriptPaths],unresolvedScripts:e.unresolvedScripts.map(t=>({...t}))}}function tC(e,t,n){let i=new Set;for(let r of t.composables)i.add(`composable:${r}`);for(let r of t.stores)i.add(`store:${r}`);for(let r of t.reactivity)i.add(`reactivity:${r}`);for(let r of t.lifecycle)i.add(`lifecycle:${r}`);for(let r of t.requests)i.add(`request:${r}`);for(let r of t.macros)i.add(`macro:${r}`);for(let r of t.functions){if(Kx.has(r.name))continue;i.add(`function:${r.name}`);let o=/^[a-z]+/.exec(r.name)?.[0]??null;o&&o.length>2&&o!==r.name&&i.add(`function-verb:${o}`)}for(let r of e.events)i.add(`template-event:${r.name}`);for(let r of n)i.add(`template-binding:${r}`);return i}function nC(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let i of iC(n.value))t.add(i);for(let n of e.slots)if(n.value)for(let i of ud(n.value))t.add(i);return[...t].sort()}function iC(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?ud(t[1]??""):[]}function ud(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let i=n[0];Jx.has(i)||t.push(i)}return t}import{extname as rC}from"path";function pn(e){return typeof e=="object"&&e!==null}function Me(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")?e:null}var oC=[".tsx",".jsx"],dd=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),sC=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),aC=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),cC=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),lC=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),uC=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),dC=new Set(["children","className","false","key","null","style","true","undefined"]),mC=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]),pC=qt("react-component-behavior-profiles");function ui(e,t={}){let n=$e(e,{extensions:oC}).filter(r=>!t.scope||r.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).flatMap(r=>fC(e,r)).filter(r=>(t.minJsxTokens===void 0||r.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||r.behaviorTokens.size>=t.minBehaviorTokens))}function fC(e,t){let n=t.replace(/\\/g,"/"),i=F(e,n);return pC.get(e,n,i,()=>gC(e,n,i)).map(yC)}function gC(e,t,n){let i=Z(e,t,n),r=ae(e,"react-component-behavior-profiles",t,i);if(r){let s=SC(r);if(s)return s}let o=hC(e,t);return ce(e,"react-component-behavior-profiles",t,i,bC(o)),o}function hC(e,t){let n=CC(t);if(!n)return[];let i=ke(e,t);if(!i)return[];let r=Ke(e,t).length;return vC(i.rootNode,n).filter(s=>s.kind==="hook"||hd(s.bodyNode)).map(s=>{let a=LC(s.bodyNode),c=TC(s.bodyNode,n);return{file:t,name:s.name,kind:s.kind,startLine:s.node.startPosition.row,endLine:s.node.endPosition.row,loc:Math.max(1,s.node.endPosition.row-s.node.startPosition.row+1),fileLines:r,jsxTokens:a.tokens,behaviorTokens:c.tokens,componentNames:Et(a.componentNames),nativeTags:Et(a.nativeTags),propNames:Et(a.propNames),eventNames:Et(a.eventNames),hookNames:Et(c.hookNames),requestNames:Et(c.requestNames),stateNames:Et(c.stateNames),effectNames:Et(c.effectNames),handlerNames:Et(c.handlerNames)}})}function yC(e){return{...e,jsxTokens:new Set(e.jsxTokens),behaviorTokens:new Set(e.behaviorTokens),componentNames:[...e.componentNames],nativeTags:[...e.nativeTags],propNames:[...e.propNames],eventNames:[...e.eventNames],hookNames:[...e.hookNames],requestNames:[...e.requestNames],stateNames:[...e.stateNames],effectNames:[...e.effectNames],handlerNames:[...e.handlerNames]}}function bC(e){return JSON.stringify(e.map(t=>({...t,jsxTokens:[...t.jsxTokens],behaviorTokens:[...t.behaviorTokens]})))}function SC(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=[];for(let i of t){let r=xC(i);if(!r)return null;n.push(r)}return n}catch{return null}}function xC(e){if(!pn(e))return null;let{file:t,name:n,kind:i,startLine:r,endLine:o,loc:s,fileLines:a,jsxTokens:c,behaviorTokens:l,componentNames:u,nativeTags:d,propNames:m,eventNames:p,hookNames:f,requestNames:g,stateNames:y,effectNames:S,handlerNames:R}=e;if(typeof t!="string"||typeof n!="string"||i!=="component"&&i!=="hook"||!vo(r)||!vo(o)||!vo(s)||!vo(a))return null;let k={jsxTokens:Me(c),behaviorTokens:Me(l),componentNames:Me(u),nativeTags:Me(d),propNames:Me(m),eventNames:Me(p),hookNames:Me(f),requestNames:Me(g),stateNames:Me(y),effectNames:Me(S),handlerNames:Me(R)};return Object.values(k).some(x=>x===null)?null:{file:t,name:n,kind:i,startLine:r,endLine:o,loc:s,fileLines:a,jsxTokens:new Set(k.jsxTokens),behaviorTokens:new Set(k.behaviorTokens),componentNames:k.componentNames,nativeTags:k.nativeTags,propNames:k.propNames,eventNames:k.eventNames,hookNames:k.hookNames,requestNames:k.requestNames,stateNames:k.stateNames,effectNames:k.effectNames,handlerNames:k.handlerNames}}function vo(e){return typeof e=="number"&&Number.isFinite(e)}function CC(e){let t=rC(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:K(e)}function vC(e,t){let n=[],i=new Set,r=o=>{let s=RC(o);if(s&&!wC(o)){let a=`${s.name}:${s.node.startIndex}:${s.node.endIndex}`;i.has(a)||(i.add(a),n.push(s));return}for(let a of o.namedChildren)r(a)};return(t==="tsx"||t==="javascript")&&r(e),n}function RC(e){if(e.type==="function_declaration"){let o=gd(e);return!o||!md(o)?null:{name:o,kind:pd(o),node:e,bodyNode:e}}if(e.type!=="variable_declarator")return null;let t=e.childForFieldName("name")??e.namedChild(0),n=e.childForFieldName("value")??e.namedChild(1),i=nr(t);if(!i||!n||!md(i))return null;let r=kC(n);return r?{name:i,kind:pd(i),node:e,bodyNode:r}:null}function md(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function pd(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function kC(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=IC(e);return t!=="memo"&&t!=="forwardRef"?null:e.namedChildren.find(r=>r.type==="arguments")?.namedChildren.find(r=>r.type==="arrow_function"||r.type==="function_expression")??null}function wC(e){let t=e.parent;for(;t;){if(t.type==="function_declaration"||t.type==="function_expression"||t.type==="arrow_function"||t.type==="method_definition")return!0;t=t.parent}return!1}function gd(e){return nr(e.childForFieldName("name")??e.namedChild(0))}function IC(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function hd(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(hd)}function LC(e){let t={tokens:new Set,componentNames:new Set,nativeTags:new Set,propNames:new Set,eventNames:new Set},n=i=>{i.type==="jsx_opening_element"||i.type==="jsx_self_closing_element"?DC(i,t):i.type==="jsx_expression"?PC(i,t):i.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let r of i.namedChildren)n(r)};return n(e),t}function DC(e,t){let n=NC(e),i=!1;if(n){let r=fd(n);i=MC(r),i?(t.componentNames.add(r),t.tokens.add(`component:${r}`)):(t.nativeTags.add(r),t.tokens.add(`native:${r}`))}for(let r of e.namedChildren)if(r.type==="jsx_attribute"){let o=EC(r);if(!o)continue;let s=fd(o);if(s.startsWith("on")&&s.length>2){let a=s.slice(2).replace(/^[A-Z]/,c=>c.toLowerCase());t.eventNames.add(a),t.tokens.add(`event:${a}`)}else mC.has(s)||(t.propNames.add(s),t.tokens.add(`${i?"prop":"native-prop"}:${s}`))}else r.type==="jsx_spread_attribute"&&t.tokens.add("prop:spread")}function PC(e,t){let n=e.text;(n.includes("&&")||n.includes("?"))&&t.tokens.add("jsx:conditional"),(n.includes(".map(")||n.includes(".flatMap("))&&t.tokens.add("jsx:list");for(let i of OC(n))dC.has(i)||t.tokens.add(`binding:${i}`)}function NC(e){for(let t of e.namedChildren)if(t.type==="identifier"||t.type==="jsx_identifier"||t.type==="property_identifier"||t.type==="member_expression"||t.type==="jsx_member_expression")return t.text;return/^<\s*([A-Za-z][\w$.]*)/.exec(e.text)?.[1]??null}function EC(e){for(let t of e.namedChildren)if(t.type==="property_identifier"||t.type==="identifier"||t.type==="jsx_identifier")return t.text;return/^([A-Za-z_$][\w$:-]*)/.exec(e.text)?.[1]??null}function TC(e,t){let n={tokens:new Set,hookNames:new Set,requestNames:new Set,stateNames:new Set,effectNames:new Set,handlerNames:new Set},i=r=>{if(r.type==="call_expression"){let o=ti(r,t);o&&FC(o.calleeLeaf,n)}else if(r.type==="variable_declarator")AC(r,n);else if(r.type==="function_declaration"){let o=gd(r);o&&yd(o,n)}for(let o of r.namedChildren)i(o)};return i(e),n}function FC(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!dd.has(e)&&!cC.has(e)&&t.tokens.add(`hook:${e}`)),dd.has(e)&&t.tokens.add(`react-hook:${e}`),sC.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),aC.has(e)&&t.tokens.add(`state-hook:${e}`),_C(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function _C(e){if(lC.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function AC(e,t){let n=e.childForFieldName("name")??e.namedChild(0),i=e.childForFieldName("value")??e.namedChild(1);if(n?.type==="array_pattern"&&i?.text.includes("useState")){let o=n.namedChildren.find(a=>nr(a)),s=nr(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let r=nr(n);r&&yd(r,t)}function yd(e,t){let n=$C(e);!n||!uC.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function $C(e){let t=e.startsWith("handle")&&e.length>6?e.slice(6).replace(/^[A-Z]/,n=>n.toLowerCase()):e;return/^[a-z]+/.exec(t)?.[0]??null}function MC(e){return/^[A-Z]/.test(e)||e.includes(".")}function fd(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function nr(e){return e&&(e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"||/^[A-Za-z_$][\w$]*$/.test(e.text))?e.text:null}function OC(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let i=n[0];t.includes(i)||t.push(i)}return t}function Et(e){return[...e].sort()}function fn(e,t,n={}){let i=ye(e,t);if(!i)return[];let r=[];if(n.includeCrossLanguageDispatchNames)for(let o of i.crossLanguageDispatchNames)r.push({name:o,kind:"cross-language-dispatch",occurrences:1});if(n.includeRustAttributeNames&&i.language==="rust")for(let o of i.rustAttrReferencedNames)r.push({name:o,kind:"rust-attribute",occurrences:1});return r}var jC={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function we(e){if(e.startsWith("local "))return{kind:"local",id:e.slice(6),raw:e};let t=e.split(" ");if(t.length<4)return{scheme:t[0]??"",manager:t[1]??"",packageName:t[2]??"",version:"",descriptors:[],raw:e};let n=t[0],i=t[1],r=e.slice(n.length+1+i.length+1),o;if(r.startsWith("`")){let l=r.indexOf("`",1);l===-1?(o=r.slice(1),r=""):(o=r.slice(1,l),r=r.slice(l+2))}else{let l=r.indexOf(" ");l===-1?(o=r,r=""):(o=r.slice(0,l),r=r.slice(l+1))}let s,a=r.indexOf(" ");a===-1?(s=r,r=""):(s=r.slice(0,a),r=r.slice(a+1));let c=BC(r);return{scheme:n,manager:i,packageName:o,version:s,descriptors:c,raw:e}}function yt(e){let t=we(e);if("kind"in t)return null;for(let n=t.descriptors.length-2;n>=0;n--){let i=t.descriptors[n];if(i?.suffix==="type")return i.name}return null}function BC(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="["){let o=e.indexOf("]",n+1);if(o===-1){t.push({name:e.slice(n+1),suffix:"type-param"});break}t.push({name:e.slice(n+1,o),suffix:"type-param"}),n=o+1;continue}if(e[n]==="("&&(t.length===0||n===0||bd(e[n-1]))){let o=e.indexOf(")",n+1);if(o!==-1&&e[o+1]!=="."){t.push({name:e.slice(n+1,o),suffix:"parameter"}),n=o+1;continue}}let i;if(e[n]==="`"){let o=e.indexOf("`",n+1);if(o===-1){i=e.slice(n+1),t.push({name:i,suffix:"term"});break}i=e.slice(n+1,o),n=o+1}else{let o=n;for(;n<e.length&&!bd(e[n]);)n++;i=e.slice(o,n)}if(n>=e.length){i&&t.push({name:i,suffix:"term"});break}let r=e[n];if(r==="("){let o=e.indexOf(")",n+1);o!==-1&&e[o+1]==="."?(t.push({name:i,suffix:"method"}),n=o+2):o!==-1?(t.push({name:i,suffix:"method"}),n=o+1):(t.push({name:i,suffix:"term"}),n++)}else{let o=jC[r];o&&t.push({name:i,suffix:o}),n+=1}}return t}function bd(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function v(e){let t=we(e);if("kind"in t&&t.kind==="local")return`local:${t.id}`;let n=t;if(n.descriptors.length===0)return n.raw;let i=[];for(let r of n.descriptors){let o=HC(r);o&&i.push(o)}return i.join(":")}function HC(e){let t=e.suffix==="namespace"?VC(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function VC(e){return e.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/,"").replace(/\.(py|pyi)$/,"").replace(/\.(rs)$/,"").replace(/\.(java|scala|kt|kts)$/,"").replace(/\.(rb)$/,"").replace(/\.(go)$/,"").replace(/\.(cs|vb)$/,"").replace(/\.(dart)$/,"").replace(/\.(php)$/,"").replace(/\.(c|cc|cpp|cxx|h|hpp)$/,"")}function M(e){let t=we(e);if("kind"in t&&t.kind==="local")return t.id;let n=t;return n.descriptors.length===0?"":n.descriptors[n.descriptors.length-1].name}function ee(e){let t=we(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function le(e){return e.endsWith("().")||ee(e)==="method"}function ue(e){let t=ee(e);return t==="method"||t==="term"}function Ut(e){return ee(e)==="namespace"}var qC=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function Ro(e){return qC.test(e)}var UC=new Set(["test","tests","_tests"]);function di(e){let t=we(e);if("kind"in t)return!1;for(let n=0;n<t.descriptors.length-1;n+=1){let i=t.descriptors[n];if(i?.suffix==="namespace"&&i.name&&UC.has(i.name))return!0}return!1}function Sd(e,t){let n=we(e),i=we(t);if("kind"in n||"kind"in i)return!1;let r=n.descriptors,o=i.descriptors;if(o.length!==r.length+1)return!1;for(let s=0;s<r.length;s++){let a=r[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function xd(e,t){let n=we(e),i=we(t);if("kind"in n||"kind"in i)return!1;let r=n.descriptors,o=i.descriptors;if(o.length<=r.length)return!1;for(let s=0;s<r.length;s++){let a=r[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function mi(e,t){return e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name, gs.documentation
|
|
45
54
|
FROM global_symbols gs
|
|
46
55
|
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
47
56
|
JOIN documents d ON der.document_id = d.id
|
|
48
57
|
WHERE ${t.where}
|
|
49
58
|
${e.pathExclusionsFor("d")}
|
|
50
|
-
${
|
|
51
|
-
${
|
|
59
|
+
${vd(t.orderBy)}
|
|
60
|
+
${Rd(t.limit)}`,...t.params??[])}function pi(e,t){return e.all(`SELECT
|
|
52
61
|
gs.id,
|
|
53
62
|
gs.symbol,
|
|
54
63
|
c.document_id,
|
|
@@ -65,8 +74,8 @@ import{program as Js}from"commander";import{realpathSync as Rb}from"fs";import{f
|
|
|
65
74
|
AND ${t.where}
|
|
66
75
|
${e.pathExclusionsFor("d")}
|
|
67
76
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
|
|
68
|
-
${
|
|
69
|
-
${
|
|
77
|
+
${vd(t.orderBy)}
|
|
78
|
+
${Rd(t.limit)}`,...t.params??[])}function vd(e){return e?`ORDER BY ${e}`:""}function Rd(e){return typeof e=="number"?`LIMIT ${e}`:""}function gn(e){return!e||!e.trim()?null:e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim()||null}function hn(e){if(!e)return null;let t=Cd(e);if(t)return t.replace(/\n/g," ");let n=e.indexOf("|");if(n===-1)return e.replace(/\n/g," ");let i=e.slice(n+1);return(Cd(i)??i).replace(/\n/g," ")}function Cd(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function WC(e){if(yt(e.symbol)!==null)return!1;let n=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(n)}function yn(e,t,n={}){let i=new Map;for(let o of t)e.length>0&&!WC(o)||i.set(o.id,o);for(let o of e)i.set(o.id,o);let r=[...i.values()];return n.sort?r.sort((o,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):r}var zC=U("file-definitions",{clearGroups:["definition-catalog"]}),GC=U("file-function-like-definitions",{clearGroups:["definition-catalog"]}),kd=new WeakMap;function Q(e,t){return zC.get(e,t,()=>{let n=Ld(e,t);if(n)return n;let i=Dd(e,t),r=er(e),o=F(e,t);return r&&o&&ce(e,"file-definitions",t,Z(e,t,o),JSON.stringify({projectFingerprint:r,definitions:i.map(s=>({...s}))})),i})}function JC(e,t){return GC.get(e,t,()=>{let n=Ld(e,t);return n?n.filter(i=>i.isFunctionLike):Dd(e,t,i=>i.isFunctionLike)})}function Ld(e,t){let n=er(e);if(!n)return null;let i=F(e,t);if(!i)return null;let r=ae(e,"file-definitions",t,Z(e,t,i));return r?KC(r,n,t):null}function KC(e,t,n){try{let i=JSON.parse(e);if(!pn(i)||i.projectFingerprint!==t||!Array.isArray(i.definitions))return null;let r=[];for(let o of i.definitions){let s=QC(o,n);if(!s)return null;r.push(s)}return r}catch{return null}}function QC(e,t){return!pn(e)||typeof e.symbolId!="number"||typeof e.symbol!="string"||typeof e.documentId!="number"||typeof e.startLine!="number"||typeof e.endLine!="number"||e.relativePath!==t||typeof e.leaf!="string"||typeof e.parentTypeName!="string"&&e.parentTypeName!==null||typeof e.isFunctionLike!="boolean"||typeof e.isTypeLike!="boolean"||typeof e.kind!="number"&&e.kind!==null||typeof e.documentation!="string"&&e.documentation!==null||typeof e.enclosingSymbol!="string"&&e.enclosingSymbol!==null?null:{symbolId:e.symbolId,symbol:e.symbol,documentId:e.documentId,startLine:e.startLine,endLine:e.endLine,relativePath:e.relativePath,leaf:e.leaf,parentTypeName:e.parentTypeName,isFunctionLike:e.isFunctionLike,isTypeLike:e.isTypeLike,kind:e.kind,documentation:e.documentation,enclosingSymbol:e.enclosingSymbol}}function Dd(e,t,n){let i=yn(XC(e,t),YC(e,t),{sort:!0}).map(Pd);return n&&(i=i.filter(n)),Fd(e,t,i)}function XC(e,t){return e.all(`SELECT
|
|
70
79
|
gs.id,
|
|
71
80
|
gs.symbol,
|
|
72
81
|
der.document_id,
|
|
@@ -82,7 +91,7 @@ import{program as Js}from"commander";import{realpathSync as Rb}from"fs";import{f
|
|
|
82
91
|
JOIN documents d ON der.document_id = d.id
|
|
83
92
|
WHERE d.relative_path = ?
|
|
84
93
|
${e.symbolNoiseFor("gs")}
|
|
85
|
-
ORDER BY der.start_line, der.end_line`,t)}function
|
|
94
|
+
ORDER BY der.start_line, der.end_line`,t)}function YC(e,t){return e.all(`SELECT
|
|
86
95
|
gs.id,
|
|
87
96
|
gs.symbol,
|
|
88
97
|
c.document_id,
|
|
@@ -101,11 +110,51 @@ import{program as Js}from"commander";import{realpathSync as Rb}from"fs";import{f
|
|
|
101
110
|
AND m.role = 1
|
|
102
111
|
${e.symbolNoiseFor("gs")}
|
|
103
112
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
104
|
-
ORDER BY start_line, end_line`,t)}function
|
|
105
|
-
|
|
106
|
-
`)))}function et(e){return e.replace(/\\/g,"/")}import{basename as gd}from"path";function mn(e){return e.replace(/'''[\s\S]*?'''/g,qt).replace(/"""[\s\S]*?"""/g,qt).replace(/#.*$/gm,qt).replace(/\/\/.*$/gm,qt).replace(/\/\*[\s\S]*?\*\//g,qt).replace(/`(?:\\[\s\S]|[^`])*`/g,qt).replace(/'(?:\\.|[^'\\\r\n])*'/g,qt).replace(/"(?:\\.|[^"\\\r\n])*"/g,qt)}function qt(e){return e.replace(/[^\r\n]/g," ")}var _V=rn("stripped-lines",{clearGroups:["whole-project","source-file"]});$t({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{bo=null,Wr=""},clearFile:()=>{bo=null,Wr=""}});var bo=null,Wr="";function ov(e){return bo===e||(bo=e,Wr=mn(e)),Wr}function Ut(e,t,n){let r=ov(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function Te(e,t){return new RegExp(`\\b${fd(t)}\\b`,"m").test(e)}function ur(e,t){let n=new Set,r=new RegExp(`\\b${fd(t)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`,"g");for(let i of e.matchAll(r)){let o=i[1];o&&n.add(o)}return[...n]}function fd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gr(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var sv=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function _e(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let o=e[i];(o==="{"||o==="["||o==="(")&&n++,(o==="}"||o==="]"||o===")")&&n--,o===","&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function Me(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function ne(e,t){let n=new Set,r=(i,o)=>{let s=o||t.has(i.type);!s&&sv.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,s)};return r(e.rootNode,!1),n}function dt(e,t,n,r,i,o,s){return{importedName:i,localName:o,sourcePath:s??te(e,r,ha(t)),kind:"named",used:Te(n,o),usedMembers:[]}}function Z(e,t,n,r,i="named",o={}){return{importedName:e,localName:t,sourcePath:n,kind:i,used:r.has(t),usedMembers:[],isTypeOnly:o.isTypeOnly}}function dr(e,t,n,r,i="named",o=[],s={}){return{importedName:e,localName:t,sourcePath:n,kind:i,used:r,usedMembers:o,isTypeOnly:s.isTypeOnly}}function pn(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function fn(e,t,n={}){return{importedName:e,localName:n.localName??null,sourcePath:t,kind:"namespace",used:n.used??!0,usedMembers:n.usedMembers??[],isTypeOnly:n.isTypeOnly}}function Ve(e,t,n){let r=[];for(let i of e.matchAll(t)){let o=i[0];if(!o||typeof i.index!="number")continue;let s=Ut(e,i.index,i.index+o.length);for(let a of n(i,s))r.push(a)}return r}function qe(e,t,n,r){let i=fe(e,t);if(i){let o=n(i);if(o)return o}return r()}function So(e,t,n,r){let i=fe(e,t),o=W(t),s=o?n[o]:void 0;return i&&s?s(i):r()}function hd(e,t,n){return qe(e,t,r=>cv(e,t,r),()=>av(e,t,n))}function av(e,t,n){return Ve(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=gd(o).replace(/\.[^.]+$/,"");return[dr(o,s,ho(e,t,o),Te(i,s))]})}function cv(e,t,n){let r=ne(n,new Set(["preproc_include"])),i=[];for(let o of n.rootNode.descendantsOfType("preproc_include")){let s=null;for(let c of o.namedChildren){if(c.type==="system_lib_string"){s=c.text.replace(/^<|>$/g,"");break}if(c.type==="string_literal"){s=c.namedChildren.find(u=>u.type==="string_content")?.text??c.text.replace(/^"|"$/g,"");break}}if(!s)continue;let a=gd(s).replace(/\.[^.]+$/,"");i.push(Z(s,a,ho(e,t,s),r))}return i}function yd(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)){let o=i[1]?.trim(),s=i[2]?.trim()??null,a=i[0];if(!o||!a||typeof i.index!="number")continue;let c=Ut(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:yo(e,t,o),kind:s?"namespace":"side-effect",used:s?Te(c,s):!0,usedMembers:s?ur(c,s):[]})}return r}function bd(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)){let o=i[1]?.trim();o&&r.push({specifier:o,sourcePath:yo(e,t,o)})}return r}function Sd(e,t,n){return So(e,t,{csharp:r=>uv(e,t,r),vb:r=>lv(e,t,r)},()=>{let r=md(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return Ve(n,r,(i,o)=>{let s=i[1]?.trim();if(!s)return[];let[a,c]=s.split(/\s*=\s*/),l=!!c,u=(l?c:a)?.trim()??s,d=u.split(".").pop()??u,m=l?a?.trim()??d:d;return[dt(e,t,o,u,d,m,te(e,u,Ht))]})})}function lv(e,t,n){let r=ne(n,new Set(["imports_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("imports_statement")){let s=o.namedChildren.filter(m=>m.type==="namespace_name");if(s.length===0)continue;let a=s[s.length-1],c=s.length>1?s[0]:null,l=a.text,u=l.split(".").pop()??l,d=c?.text??u;i.push(Z(u,d,te(e,l,Ht),r,c?"namespace":"named"))}return i}function uv(e,t,n){let r=ne(n,new Set(["using_directive"])),i=[];for(let o of n.rootNode.descendantsOfType("using_directive")){let s=o.namedChildren;if(s.length===0)continue;let a=null,c;s.length>=2&&s[0].type==="identifier"&&(s[1].type==="qualified_name"||s[1].type==="identifier")?(a=s[0],c=s[1]):c=s[s.length-1];let l=c.text,u=l.split(".").pop()??l,d=a?.text??u;i.push(Z(u,d,te(e,l,Ht),r,a?"namespace":"named"))}return i}var dv=U("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function xd(e,t){return dv.get(e,t,()=>{let n=new Set,r=F(e,t);if(!r)return n;let o=r.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g,s=>s.replace(/[^\r\n]/g," ")).replace(/<!--[\s\S]*?-->/g,s=>s.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\r\n]/g," "));for(let s of o.matchAll(/[A-Za-z_$][\w$]*/g))n.add(s[0]);return n})}function ba(e,t,n){return qe(e,t,r=>pv(e,t,r),()=>mv(e,t,n))}function mv(e,t,n){return kv(n).flatMap(r=>wv(e,t,r.clause,r.specifier,r.start,r.end,n))}function pv(e,t,n){let r=fv(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...gv(e,t,n,o,r));return i}function fv(e,t,n){let r=ne(n,new Set(["import_statement"]));if(Rt(t))for(let i of xd(e,t))r.add(i);return r}function gv(e,t,n,r,i){let o=xv(r);if(!o)return[];let s=tt(e,t,o),a=Me(r,"import_clause");return a?hv(n,a,s,i,Cv(r.text)):[pn("*",s)]}function hv(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(yv(s.text,n,r,i));else if(s.type==="namespace_import"){let a=bv(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...Sv(s,n,r,i));return o}function yv(e,t,n,r){return Z("default",e,t,n,"default",{isTypeOnly:r})}function bv(e,t,n,r,i){let s=Me(t,"identifier")?.text??"";if(!s)return null;let a=Rv(e,s);return fn("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function Sv(e,t,n,r){let i=[];for(let o of e.namedChildren){if(o.type!=="import_specifier")continue;let s=o.namedChild(0),a=o.namedChild(1);if(!s)continue;let c=s.text,l=a?.text??c;i.push(Z(c,l,t,n,"named",{isTypeOnly:r||vv(o.text)}))}return i}function xv(e){let t=Me(e,"string");if(!t)return null;let n=Me(t,"string_fragment");return n?n.text:null}function Cv(e){return/^\s*import\s+type\b/.test(e)}function vv(e){return/^\s*type\b/.test(e.trim())}function Rv(e,t){let n=new Set;for(let r of e.rootNode.descendantsOfType("member_expression")){let i=r.namedChild(0),o=r.namedChild(1);!i||!o||i.type!=="identifier"||i.text!==t||(o.type==="property_identifier"||o.type==="identifier")&&n.add(o.text)}return[...n]}function kv(e){let t=[],n=/^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(n)){let o=i[0],s=i[1],a=i[2];!o||!a||typeof i.index!="number"||t.push({clause:s,specifier:a,start:i.index,end:i.index+o.length})}let r=/^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(r)){let o=i[0],s=i[1];!o||!s||typeof i.index!="number"||t.push({clause:null,specifier:s,start:i.index,end:i.index+o.length})}return t.sort((i,o)=>i.start-o.start)}function wv(e,t,n,r,i,o,s){let a=tt(e,t,r),c=Ut(s,i,o);return n?Lv(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=ur(c,u.localName);return fn(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||Te(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?pn(u.importedName,u.sourcePath):dr(u.importedName,u.localName??"",u.sourcePath,u.localName?Te(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[pn("*",a)]}function Lv(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=Iv(r),s=[];return i&&s.push(...Cd(i,n)),o&&s.push(...Cd(o,n)),s}function Cd(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?_e(r).map(i=>{let o=i.trim(),s=t||/^type\b/.test(o),a=o.replace(/^type\s+/,""),[c,l]=a.split(/\s+as\s+/);return{importedName:c.trim(),localName:(l??c).trim(),kind:"named",isTypeOnly:s}}):[]}return n.startsWith("* as ")?[{importedName:"*",localName:n.slice(5).trim(),kind:"namespace",isTypeOnly:t}]:[{importedName:"default",localName:n,kind:"default",isTypeOnly:t}]}function Iv(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r==="{"&&t++,r==="}"&&t--,r===","&&t===0)return[e.slice(0,n).trim(),e.slice(n+1).trim()]}return[e.trim(),null]}function Sa(e,t,n){let r=fe(e,t);return r?_v(e,t,r):Dv(e,t,n)}function Dv(e,t,n){return[...Pv(e,t,n),...Nv(e,t,n),...Ev(e,t,n)]}function Pv(e,t,n){let r=[],i=/^[ \t]*export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[1]??"",a=o[2]??"",c=_e(s).map(d=>Tv(d.trim())).filter(d=>!!d),l=mr(n,o.index),u=mr(n,o.index+o[0].length-1);r.push({kind:"named",sourcePath:tt(e,t,a),names:c,startLine:l,endLine:u})}return r}function Nv(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[2]??"",a=mr(n,o.index),c=mr(n,o.index+o[0].length-1);r.push({kind:"star-as",sourcePath:tt(e,t,s),names:[],startLine:a,endLine:c})}return r}function Ev(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[1]??"",a=mr(n,o.index),c=mr(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:tt(e,t,s),names:[],startLine:a,endLine:c})}return r}function Tv(e){if(!e)return null;let t=e.replace(/^type\s+/,"").trim();if(!t)return null;let n=t.match(/^(\w+)\s+as\s+(\w+)$/);if(n)return n[2]??null;let r=t.match(/^(\w+)$/);return r?r[1]??null:null}function mr(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function _v(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=Fv(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=$v(i,o,s,a);r.push(c)}return r}function Fv(e,t,n){let r=Me(n,"string");if(!r)return;let i=Me(r,"string_fragment");if(i)return tt(e,t,i.text)}function $v(e,t,n,r){let i=Me(e,"export_clause");if(i){let s=[];for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let c=a.namedChild(0),l=a.namedChild(1);c&&s.push((l??c).text)}return{kind:"named",sourcePath:t,names:s,startLine:n,endLine:r}}return Me(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function vd(e,t,n){return So(e,t,{java:r=>Av(e,t,r),kotlin:r=>Mv(e,t,r),scala:r=>jv(e,t,r)},()=>Ve(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?Ov(e,t,o,i):[]}))}function Av(e,t,n){let r=ne(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.children.some(d=>d.type==="asterisk"),c=o.namedChildren.find(d=>d.type==="scoped_identifier")??o.namedChildren.find(d=>d.type==="identifier");if(!c)continue;let l=c.text;if(s){i.push(fn("*",te(e,l,Ae)));continue}let u=l.split(".").pop()??l;i.push(Z(u,u,te(e,l,Ae),r))}return i}function Mv(e,t,n){let r=ne(n,new Set(["import_header","import_list"])),i=[];for(let o of n.rootNode.descendantsOfType("import_header")){let s=o.namedChildren.find(f=>f.type==="identifier");if(!s)continue;let a=o.namedChildren.some(f=>f.type==="wildcard_import"),c=o.namedChildren.find(f=>f.type==="import_alias");if(a){i.push(fn("*",te(e,s.text,Ae)));continue}let l=s.text,u=l.split(".").pop()??l,m=c?.namedChild(0)?.text??u;i.push(Z(u,m,te(e,l,Ae),r))}return i}function jv(e,t,n){let r=ne(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.namedChildren.find(d=>d.type==="namespace_selectors"||d.type==="namespace_wildcard"),a=o.namedChildren.filter(d=>d!==s&&(d.type==="identifier"||d.type==="stable_identifier")),c=a.map(d=>d.text).join(".");if(!c)continue;if(s?.type==="namespace_wildcard"){i.push(fn("*",te(e,c,Ae)));continue}if(s?.type==="namespace_selectors"){for(let d of s.namedChildren)if(d.type==="arrow_renamed_identifier"){let[m,f]=d.namedChildren;if(!m)continue;let h=m.text,g=f?.text??h;if(h==="_")continue;i.push(Z(h,g,te(e,`${c}.${h}`,Ae),r))}else if(d.type==="identifier"){let m=d.text;i.push(Z(m,m,te(e,`${c}.${m}`,Ae),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;i.push(Z(l,l,te(e,u&&a.length>1?`${u}.${l}`:c,Ae),r))}return i}function Ov(e,t,n,r){if(n.includes("{")&&n.includes("}")){let i=n.slice(0,n.indexOf("{")).replace(/\.$/,"").trim(),o=n.slice(n.indexOf("{")+1,n.lastIndexOf("}")).trim();return _e(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.includes("=>")?a.split(/\s*=>\s*/):a.split(/\s+as\s+/),u=c?.trim();if(!u||u==="_")return[];let d=(l??u.split(".").pop()??u).trim(),m=u==="_"?i:`${i}.${u}`.replace(/\.\./g,".");return[dt(e,t,r,m,u,d)]})}return[dt(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function kd(e,t,n){return qe(e,t,r=>Bv(e,t,r),()=>Ve(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?_e(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.split(/\s+as\s+/i),u=c?.trim()??a,d=u.split("\\").pop()??u,m=(l??d).trim();return[dt(e,t,i,u,d,m,te(e,u.replace(/\\/g,"."),dn))]}):[]}))}function Bv(e,t,n){let r=ne(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(Z(a,c,te(e,s.replace(/\\/g,"."),dn),r))};for(let s of n.rootNode.descendantsOfType("namespace_use_declaration")){let a=s.namedChildren.find(c=>c.type==="namespace_use_group");if(a){let c=s.namedChildren.find(l=>l.type==="namespace_name")?.text??"";for(let l of a.namedChildren){if(l.type!=="namespace_use_clause")continue;let{importedName:u,localName:d,qualified:m}=Rd(l,c);u&&o(m,u,d)}continue}for(let c of s.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:l,localName:u,qualified:d}=Rd(c,"");l&&o(d,l,u)}}return i}function Rd(e,t){let n=e.namedChildren.find(l=>l.type==="qualified_name"),r=e.namedChildren.filter(l=>l.type==="name"),i="";n?i=n.text:r.length>=1&&(i=r[0].text);let o=n&&r.length>0?r[r.length-1]:null,s=i.split("\\").pop()??i,a=o?.text??s,c=t?`${t}\\${i}`:i;return{importedName:s,localName:a,qualified:c}}function Ld(e,t,n){return qe(e,t,r=>Hv(e,t,r),()=>qv(n).flatMap(r=>Wv(e,t,r,n)))}function Hv(e,t,n){let r=ne(n,new Set(["import_statement","import_from_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))for(let s of o.namedChildren){let a=wd(s);if(!a)continue;let c=cr(e,t,a.qualifiedName);i.push({importedName:a.qualifiedName,localName:a.localName,sourcePath:c,kind:"namespace",used:r.has(a.localName),usedMembers:[]})}for(let o of n.rootNode.descendantsOfType("import_from_statement")){let s=o.namedChild(0);if(!s)continue;let a=Vv(s);if(a===null)continue;let c=cr(e,t,a);for(let l=1;l<o.namedChildCount;l+=1){let u=o.namedChild(l);if(u.type==="wildcard_import"){i.push({importedName:"*",localName:null,sourcePath:c,kind:"side-effect",used:!0,usedMembers:[]});continue}let d=wd(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function wd(e){if(e.type==="aliased_import"){let t=e.namedChild(0),n=e.namedChild(1);return!t||!n?null:{qualifiedName:t.text,localName:n.text}}if(e.type==="dotted_name"){let t=e.text;return{qualifiedName:t,localName:t.split(".")[0]??t}}return e.type==="identifier"?{qualifiedName:e.text,localName:e.text}:null}function Vv(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=Me(e,"import_prefix")?.text??"",n=Me(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function qv(e){let t=e.split(`
|
|
107
|
-
|
|
108
|
-
|
|
113
|
+
ORDER BY start_line, end_line`,t)}function Pd(e){return{symbolId:e.id,symbol:e.symbol,documentId:e.document_id,startLine:e.start_line,endLine:e.end_line,relativePath:e.relative_path,leaf:M(e.symbol),parentTypeName:yt(e.symbol),isFunctionLike:ue(e.symbol),isTypeLike:ee(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function bt(e,t={}){return ir(e,t.scope)}function ir(e,t){return B(e,{scope:t,includeIgnored:!1}).flatMap(n=>Q(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function Nd(e,t){return B(e,{scope:t,includeIgnored:!1}).flatMap(n=>JC(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function Ed(e,t){let n=wd(ZC(e,t.scope,t.sqlPrefilter)),i=wd(ev(e,t.scope,t.sqlPrefilter)),r=new Set([...n.keys(),...i.keys()]),o=[];for(let s of[...r].sort()){if(e.isIgnored(s))continue;let a=yn(n.get(s)??[],i.get(s)??[],{sort:!0}).filter(c=>t.symbolMatches(c.symbol));a.length!==0&&o.push(...Fd(e,s,a.map(Pd)))}return o}function ZC(e,t,n){let i=t?"AND d.relative_path LIKE ?":"",r=n?`AND ${Td("gs",n)}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
|
|
114
|
+
gs.id,
|
|
115
|
+
gs.symbol,
|
|
116
|
+
der.document_id,
|
|
117
|
+
der.start_line,
|
|
118
|
+
der.end_line,
|
|
119
|
+
d.relative_path,
|
|
120
|
+
gs.display_name,
|
|
121
|
+
gs.kind,
|
|
122
|
+
gs.documentation,
|
|
123
|
+
gs.enclosing_symbol
|
|
124
|
+
FROM global_symbols gs
|
|
125
|
+
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
126
|
+
JOIN documents d ON der.document_id = d.id
|
|
127
|
+
WHERE 1 = 1
|
|
128
|
+
${e.pathExclusionsFor("d")}
|
|
129
|
+
${i}
|
|
130
|
+
${r}
|
|
131
|
+
${e.symbolNoiseFor("gs")}
|
|
132
|
+
ORDER BY d.relative_path, der.start_line, der.end_line`,...o)}function ev(e,t,n){let i=t?"AND d.relative_path LIKE ?":"",r=n?`AND ${Td("gs",n)}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
|
|
133
|
+
gs.id,
|
|
134
|
+
gs.symbol,
|
|
135
|
+
c.document_id,
|
|
136
|
+
MIN(c.start_line) AS start_line,
|
|
137
|
+
MAX(c.end_line) AS end_line,
|
|
138
|
+
d.relative_path,
|
|
139
|
+
gs.display_name,
|
|
140
|
+
gs.kind,
|
|
141
|
+
gs.documentation,
|
|
142
|
+
gs.enclosing_symbol
|
|
143
|
+
FROM global_symbols gs
|
|
144
|
+
JOIN mentions m ON m.symbol_id = gs.id
|
|
145
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
146
|
+
JOIN documents d ON c.document_id = d.id
|
|
147
|
+
WHERE m.role = 1
|
|
148
|
+
${e.pathExclusionsFor("d")}
|
|
149
|
+
${i}
|
|
150
|
+
${r}
|
|
151
|
+
${e.symbolNoiseFor("gs")}
|
|
152
|
+
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
153
|
+
ORDER BY d.relative_path, start_line, end_line`,...o)}function tv(e){return`(${e}.symbol LIKE '%().' OR ${e}.symbol LIKE '%()')`}function Td(e,t){return t==="callable"?tv(e):nv(e)}function nv(e){return`${e}.symbol LIKE '%.'`}function wd(e){let t=new Map;for(let n of e){let i=t.get(n.relative_path);i?i.push(n):t.set(n.relative_path,[n])}return t}function ko(e,t,n={}){if(t.length===0)return[];let i=t.flatMap(r=>Q(e,r)).filter(r=>!e.isIgnored(r.relativePath));return n.onlyDocumented&&(i=i.filter(r=>r.documentation!==null&&r.documentation!=="")),n.sort&&(i=i.sort((r,o)=>r.relativePath.localeCompare(o.relativePath)||r.startLine-o.startLine||r.endLine-o.endLine)),i.map(r=>({startLine:r.startLine,endLine:r.endLine,symbol:r.symbol,shortName:v(r.symbol),signature:gn(hn(r.documentation)),relativePath:r.relativePath,enclosingSymbol:r.enclosingSymbol}))}function ka(e){let t=new Map,n=e.map((i,r)=>({definition:i,index:r,span:i.endLine-i.startLine})).sort((i,r)=>i.span-r.span||i.index-r.index);for(let{definition:i}of n)for(let r=i.startLine;r<=i.endLine;r+=1)t.has(r)||t.set(r,i);return t}function Qe(e,t){let n=kd.get(e);return n||(n=ka(e),kd.set(e,n)),n.get(t)??null}function bn(e,t){let n=Q(e,t.relative_path).find(i=>i.symbolId===t.id);return n?{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,endLine:n.endLine,relativePath:n.relativePath}:{symbolId:t.id,symbol:t.symbol,documentId:t.document_id,startLine:t.start_line,endLine:t.end_line,relativePath:t.relative_path}}function Fd(e,t,n){let i=F(e,t),r=xa(e,t);return r?cv(n,r,i):i?iv(n,i):n}function iv(e,t){let n=t.split(/\r?\n/),i=rv(e,n),r=ov(e,i),o=sv(r,n);return av(e,o)}function rv(e,t){let n=e.some(r=>wo(r.symbol))?dv(t):null,i=new Map;for(let r of e)i.set(r.symbolId,uv(t,n,r));return i}function ov(e,t){return e.filter(n=>wo(n.symbol)).map(n=>({definition:n,startLine:t.get(n.symbolId)??n.startLine})).sort((n,i)=>n.startLine-i.startLine||n.definition.startLine-i.definition.startLine||n.definition.symbol.localeCompare(i.definition.symbol))}function sv(e,t){let n=new Map;for(let i=0;i<e.length;i+=1){let r=e[i],o=e[i+1],s=o?Math.max(r.startLine,o.startLine-1):t.length-1;n.set(r.definition.symbolId,{startLine:r.startLine,endLine:mv(t,r.definition,r.startLine,s)})}return n}function av(e,t){return e.map(n=>{let i=t.get(n.symbolId);return i?{...n,startLine:i.startLine,endLine:i.endLine}:n})}function cv(e,t,n=null){let i=new Map;for(let r of t){let o=i.get(r.name);o?o.push(r):i.set(r.name,[r])}return e.map(r=>{if(!lv(r)||!r.leaf)return Id(r,n);let o=i.get(r.leaf);if(!o||o.length===0)return Id(r,n);let s=o[0],a=Math.abs(s.startLine-r.startLine);for(let c=1;c<o.length;c+=1){let l=o[c],u=Math.abs(l.startLine-r.startLine);u<a&&(s=l,a=u)}return{...r,startLine:s.startLine,endLine:s.endLine}})}function lv(e){return wo(e.symbol)?!0:ee(e.symbol)==="term"&&yt(e.symbol)===null}function Id(e,t){if(!t||!e.leaf||ee(e.symbol)!=="term"||yt(e.symbol)!==null)return e;let n=e.leaf.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`),o=t.split(/\r?\n/).findIndex(s=>i.test(s));return o>=0?{...e,startLine:o,endLine:o}:e}function uv(e,t,n){if(!wo(n.symbol))return n.startLine;let i=Math.max(0,Math.min(n.startLine,e.length-1));if(!t)return i;let r=t.get(n.leaf);if(!r||r.length===0)return i;let o=null;for(let s of r){let a=Math.abs(s-n.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??i}function dv(e){let t=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,n=/\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\()/g,i=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,r=/\b([A-Za-z_$][\w$]*)\s*\(/g,o=new Map,s=(a,c)=>{let l=o.get(a);if(!l){o.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let a=0;a<e.length;a+=1){let c=e[a]??"";for(let u of c.matchAll(t))u[1]&&s(u[1],a);for(let u of c.matchAll(n))u[1]&&s(u[1],a);let l=c.match(i);l?.[1]&&s(l[1],a);for(let u of c.matchAll(r))u[1]&&s(u[1],a)}return o}function mv(e,t,n,i){let r=Math.max(n,Math.min(e.length-1,i)),o=Math.max(n,Math.min(r,t.endLine)),s=0,a=0,c=!1;for(let l=n;l<=r;l+=1){let u=pv(e[l]??"");for(let d of u)d==="{"?(s+=1,c=!0):d==="}"?s=Math.max(0,s-1):d==="("?a+=1:d===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function pv(e){let t="",n=null,i=!1;for(let r=0;r<e.length;r+=1){let o=e[r],s=e[r+1];if(!n&&o==="/"&&s==="/"){t+=" ".repeat(e.length-r);break}if(n){if(i){i=!1,t+=" ";continue}if(o==="\\"){i=!0,t+=" ";continue}o===n&&(n=null),t+=" ";continue}if(o==='"'||o==="'"||o==="`"){n=o,t+=" ";continue}t+=o}return t}function wo(e){return e.includes("().")}function Io(e){let t=we(e);if("kind"in t)return[];let n=[];for(let i=t.descriptors.length-2;i>=0;i-=1){let r=t.descriptors[i];r?.suffix==="type"&&r.name&&n.push(r.name)}return n}import{existsSync as Lv}from"fs";import{basename as _d,isAbsolute as Dv,join as Pv}from"path";function V(e,t){let n=gi(e,t.trim());if(n)return n;let i=Sv(e,t);if(i)return i;let r=fv(e,t);return r||bv(e,t)}function fv(e,t){let n=Ia(t),i=wa(n);if(!i)return null;let r=`%${i.path}%`,o=i.leaf,a=gv(e,r,o,n)[0];return a?bn(e,a):null}function gv(e,t,n,i){let r=yn([],[...hv(e,t,n),...yv(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>fi(o,i)>1);return r.sort((o,s)=>fi(s,i)-fi(o,i)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.start_line-s.start_line||o.symbol.localeCompare(s.symbol)),r}function hv(e,t,n){return mi(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function yv(e,t,n){return pi(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function bv(e,t){let n=Ia(t),i=wv(t),r=Rv(e,i),o=Iv(r,t,n);if(o&&!e.isIgnored(o.relative_path))return bn(e,o);let s=null;for(let a of r){if(e.isIgnored(a.relative_path))continue;let c=kv(a,t,n,i);c<=0||(!s||c>s.score)&&(s={row:a,score:c})}return s?bn(e,s.row):null}function Sv(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return null;let[,i,r,o]=n,s=Math.max(0,parseInt(r,10)-1),a=Math.max(s,parseInt(o,10)-1),c=xv(e,i,s,a)??Cv(e,i,s,a);return c&&!e.isIgnored(c.relative_path)?bn(e,c):null}function xv(e,t,n,i){return mi(e,{where:"d.relative_path LIKE ? AND der.start_line <= ? AND der.end_line >= ?",params:[`%${t}%`,n,i],orderBy:"(der.end_line - der.start_line) ASC",limit:1})[0]}function Cv(e,t,n,i){return pi(e,{where:"d.relative_path LIKE ? AND c.start_line <= ? AND c.end_line >= ?",params:[`%${t}%`,n,i],orderBy:"(MAX(c.end_line) - MIN(c.start_line)) ASC",limit:1})[0]}function gi(e,t){let i=mi(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line",limit:1})[0]??pi(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line",limit:1})[0];return!i||e.isIgnored(i.relative_path)?null:bn(e,i)}function Lo(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=vv(e,t.symbolId)[0];return n?bn(e,n):null}function vv(e,t){let n=mi(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),i=pi(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return yn(n,i)}function Rv(e,t){let n=t.map(()=>"(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)"),i=t.flatMap(a=>{let c=`%${a}%`;return[c,c,c]}),r=n.join(`
|
|
154
|
+
AND `),o=mi(e,{where:r,params:i,limit:200}),s=pi(e,{where:r,params:i,limit:200});return yn(o,s)}function kv(e,t,n,i){let r=t.trim(),o=n,s=o.replace(/\(\)$/,""),a=t.toLowerCase(),c=n.toLowerCase(),l=c.replace(/\(\)$/,""),u=e.symbol,d=v(e.symbol),m=M(e.symbol),p=e.display_name??"",f=e.symbol.toLowerCase(),g=d.toLowerCase(),y=m.toLowerCase(),S=p.toLowerCase(),R=e.relative_path.toLowerCase(),k=/[/:.]/.test(n),x=wa(n),b=x?.leaf.toLowerCase(),C=0;return(u===r||u===o)&&(C+=1150),(d===r||d===o)&&(C+=1100),p===s&&(C+=1180),m===s&&(C+=1160),(`${m}()`===r||`${m}()`===o)&&(C+=955),(f===a||f===c)&&(C+=1e3),(g===a||g===c)&&(C+=950),(R===a||R===c)&&(C+=925),(R.endsWith(`/${c}`)||R.endsWith(`/${a}`))&&(C+=875),S===l&&(C+=850),y===l&&(C+=825),(`${y}()`===a||`${y}()`===c)&&(C+=820),(g.endsWith(`:${c}`)||g.endsWith(`:${l}`)||g.endsWith(`:${l}()`))&&(C+=800),f.includes(c)&&(C+=120),g.includes(c)&&(C+=140),R.includes(c)&&(C+=140),S.includes(c)&&(C+=110),i.every(D=>{let w=D.toLowerCase();return f.includes(w)||g.includes(w)||R.includes(w)||S.includes(w)})&&(C+=100+i.length*15),x&&R.includes(x.path.toLowerCase())&&(C+=360,b&&(y===b||`${y}()`===b||`${y}()`==`${b}()`)&&(C+=700),le(e.symbol)&&(C+=180)),ue(e.symbol)&&y===l&&(C+=60),!k&&Ut(e.symbol)&&(C-=160),C-=Math.min(50,Math.max(0,e.end_line-e.start_line)),C}function wa(e){let t=e.trim().replace(/\\/g,"/"),n=t.lastIndexOf("/");if(n<=0||n===t.length-1)return null;let i=t.slice(n+1).replace(/\(\)$/,"");return!i||i.includes(".")?null:{path:t.slice(0,n),leaf:i}}function Ia(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function wv(e){let t=Ia(e),n=t.split(/[^A-Za-z0-9_]+/).map(i=>i.trim()).filter(i=>i.length>0);return n.length>0?[...new Set(n)]:[t]}function Iv(e,t,n){let i=t.trim(),r=e.filter(o=>{let s=v(o.symbol),a=(o.display_name??"").trim();return o.symbol===i||s===i||s===n||a===i||a===n||`${a}()`===i||fi(o,n)>1||o.relative_path===i});return r.length===0?null:(r.sort((o,s)=>fi(s,n)-fi(o,n)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.relative_path.localeCompare(s.relative_path)||o.symbol.localeCompare(s.symbol)),r[0]??null)}function fi(e,t){let n=wa(t);if(!n)return 0;let i=e.relative_path.toLowerCase(),r=M(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return i.includes(o)?r!==s?1:le(e.symbol)?yt(e.symbol)===null?5:4:yt(e.symbol)===null?3:2:0}function Be(e,t){let n=Ad(e,t,{allowMultiple:!1})[0]?.relativePath;return n||Nv(e,t)}function hi(e,t){return Ad(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function Nv(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),i=Dv(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,r=Pv(e.config.projectRoot,i);return Lv(r)?i:null}function Ad(e,t,n){let i=$d(t);if(!i)return[];let r=B(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:Ev(a,i)})).filter(a=>a.score>0).sort((a,c)=>c.score-a.score||a.relativePath.localeCompare(c.relativePath));if(r.length===0){let a=V(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}let o=r.filter(a=>a.score>=1100);if(o.length>0)return n.allowMultiple?o:[o[0]];let s=r.filter(a=>a.score>=800);return s.length>0?n.allowMultiple?s:[s[0]]:n.allowMultiple?r:[r[0]]}function Ev(e,t){let n=$d(e),i=_d(n),r=_d(t),o=0;return n===t&&(o+=1200),n.endsWith(`/${t}`)&&(o+=1100),i===r&&(o+=900),n.startsWith(`${t}/`)&&(o+=850),n.includes(t)&&(o+=250),o}function $d(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{basename as yI}from"path";import{existsSync as Do}from"fs";import{basename as Tv,dirname as Wt,extname as Tt,join as at,relative as rr,resolve as Xe}from"path";var Fv=re("indexed-paths",{clearGroups:[]}),_v=re("indexed-path-digest",{clearGroups:[]}),Sn=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],Po=[".py",".pyi"],We=[".java",".scala",".kt",".kts"],No=[".rs"],Eo=[".rb"],To=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],zt=[".cs",".vb"],Fo=[".dart"],xn=[".php"],Av=new Set(Sn),La=new Set(Po),Md=new Set(We),Da=new Set(No),Pa=new Set(Eo),Od=new Set(To),jd=new Set(zt),Na=new Set(Fo),Bd=new Set(xn),$v=[{extensions:Sn,lookup:Av},{extensions:Po,lookup:La},{extensions:We,lookup:Md},{extensions:No,lookup:Da},{extensions:Eo,lookup:Pa},{extensions:To,lookup:Od},{extensions:zt,lookup:jd},{extensions:Fo,lookup:Na},{extensions:xn,lookup:Bd}];function Gt(e,t){return t.has(Tt(e).toLowerCase())}function Mv(e){return Gt(e,La)}function Ov(e){return Gt(e,Md)}function jv(e){return Gt(e,Da)}function Bv(e){return Gt(e,Pa)}function Hv(e){return Gt(e,Od)}function Vv(e){return Gt(e,jd)}function Hd(e){return Tt(e).toLowerCase()===".vb"}function qv(e){return Gt(e,Na)}function Uv(e){return Gt(e,Bd)}function Ea(e){let t=Tt(e).toLowerCase();for(let n of $v)if(n.lookup.has(t))return n.extensions;return Sn}function Wv(e){return Ov(e)||Vv(e)||Uv(e)}function lt(e,t,n){return Mv(t)?yi(e,t,n):jv(t)?Ft(e,t,n):Bv(t)?_o(e,t,n):Hv(t)?Ao(e,t,n):Wv(t)?de(e,n.replace(/\\/g,"."),Ea(t)):qv(t)?$o(e,t,n):zv(e,t,n)}function zv(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let i=Wt(at(e.config.projectRoot,t)),r=Xe(i,n),o=bi(e);for(let s of Xv(r)){let a=ct(rr(e.config.projectRoot,s));if(o.has(a)||Do(s))return a}return ct(rr(e.config.projectRoot,r))}function yi(e,t,n){let i=bi(e),r;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=Wt(at(e.config.projectRoot,t));for(let l=1;l<s;l++)c=Wt(c);r=a?Xe(c,a.replace(/\./g,"/")):c}else r=Xe(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of Gv(r)){let s=ct(rr(e.config.projectRoot,o));if(i.has(s)||Do(o))return s}return null}function Ft(e,t,n){if(!n)return null;let i=n.replace(/\s+as\s+.+$/,"").trim();if(!i.startsWith("crate::")&&!i.startsWith("self::")&&!i.startsWith("super::"))return null;let r=Wt(at(e.config.projectRoot,t)),o;return i.startsWith("crate::")?o=Xe(e.config.projectRoot,"src",i.slice(7).replace(/::/g,"/")):i.startsWith("self::")?o=Xe(r,i.slice(6).replace(/::/g,"/")):o=Xe(Wt(r),i.slice(7).replace(/::/g,"/")),Ta(e,Jv(o))}function _o(e,t,n){let i=Wt(at(e.config.projectRoot,t)),r=Xe(i,n);return Ta(e,Kv(r))}function Ao(e,t,n){let i=Wt(at(e.config.projectRoot,t)),r=[Xe(i,n),Xe(e.config.projectRoot,n),Xe(e.config.projectRoot,"include",n),Xe(e.config.projectRoot,"src",n)];return Ta(e,r)}function de(e,t,n){let i=bi(e),r=t.replace(/\\/g,".").replace(/::/g,".").replace(/^global::/,""),o=r.replace(/\./g,"/"),s=r.split(".").pop()??r;for(let c of n){let l=`${o}${c}`,u=[...i].find(d=>d.endsWith(l));if(u)return u}for(let c of n){let l=[...i].find(u=>Tv(u)===`${s}${c}`);if(l)return l}let a=[...i].filter(c=>n.includes(Tt(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function $o(e,t,n){let i=bi(e);if(n.startsWith("package:")){let s=n.slice(8),a=s.indexOf("/");if(a<0)return null;let c=s.slice(a+1),l=ct(c.startsWith("lib/")?c:`lib/${c}`);return i.has(l)?l:null}let r=Wt(at(e.config.projectRoot,t)),o=Xe(r,n);for(let s of Qv(o)){let a=ct(rr(e.config.projectRoot,s));if(i.has(a)||Do(s))return a}return null}function Gv(e){let t=Tt(e);return La.has(t)?[e]:[`${e}.py`,`${e}.pyi`,at(e,"__init__.py"),at(e,"__init__.pyi")]}function Ta(e,t){let n=bi(e);for(let i of t){let r=ct(rr(e.config.projectRoot,i));if(n.has(r)||Do(i))return r}return null}function Jv(e){let t=Tt(e);return Da.has(t)?[e]:[`${e}.rs`,at(e,"mod.rs")]}function Kv(e){let t=Tt(e);return Pa.has(t)?[e]:[`${e}.rb`,at(e,"index.rb")]}function Qv(e){let t=Tt(e);return Na.has(t)?[e]:[`${e}.dart`,e]}function Xv(e){let t=Tt(e),n=new Set;if(t){n.add(e);for(let i of Sn)n.add(e.slice(0,-t.length)+i)}else for(let i of Sn)n.add(`${e}${i}`),n.add(at(e,`index${i}`));return[...n]}function bi(e){return Fv.get(e,()=>new Set(B(e,{includeIgnored:!1}).map(ct)))}function Fa(e){return _v.get(e,()=>ii([...bi(e)].sort().join(`
|
|
155
|
+
`)))}function ct(e){return e.replace(/\\/g,"/")}import{basename as qd}from"path";function Cn(e){return e.replace(/'''[\s\S]*?'''/g,Jt).replace(/"""[\s\S]*?"""/g,Jt).replace(/#.*$/gm,Jt).replace(/\/\/.*$/gm,Jt).replace(/\/\*[\s\S]*?\*\//g,Jt).replace(/`(?:\\[\s\S]|[^`])*`/g,Jt).replace(/'(?:\\.|[^'\\\r\n])*'/g,Jt).replace(/"(?:\\.|[^"\\\r\n])*"/g,Jt)}function Jt(e){return e.replace(/[^\r\n]/g," ")}var kU=dn("stripped-lines",{clearGroups:["whole-project","source-file"]});Vt({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{Mo=null,or=""},clearFile:()=>{Mo=null,or=""}});var Mo=null,or="";function Yv(e){return Mo===e||(Mo=e,or=Cn(e)),or}function Kt(e,t,n){let i=Yv(e);return`${i.slice(0,t)}${" ".repeat(n-t)}${i.slice(n)}`}function He(e,t){return new RegExp(`\\b${Vd(t)}\\b`,"m").test(e)}function Si(e,t){let n=new Set,i=new RegExp(`\\b${Vd(t)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`,"g");for(let r of e.matchAll(i)){let o=r[1];o&&n.add(o)}return[...n]}function Vd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sr(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var Zv=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function Ve(e){let t=[],n=0,i=0;for(let r=0;r<e.length;r++){let o=e[r];(o==="{"||o==="["||o==="(")&&n++,(o==="}"||o==="]"||o===")")&&n--,o===","&&n===0&&(t.push(e.slice(i,r)),i=r+1)}return t.push(e.slice(i)),t}function ze(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function me(e,t){let n=new Set,i=(r,o)=>{let s=o||t.has(r.type);!s&&Zv.has(r.type)&&n.add(r.text);for(let a of r.children)i(a,s)};return i(e.rootNode,!1),n}function St(e,t,n,i,r,o,s){return{importedName:r,localName:o,sourcePath:s??de(e,i,Ea(t)),kind:"named",used:He(n,o),usedMembers:[]}}function oe(e,t,n,i,r="named",o={}){return{importedName:e,localName:t,sourcePath:n,kind:r,used:i.has(t),usedMembers:[],isTypeOnly:o.isTypeOnly}}function xi(e,t,n,i,r="named",o=[],s={}){return{importedName:e,localName:t,sourcePath:n,kind:r,used:i,usedMembers:o,isTypeOnly:s.isTypeOnly}}function vn(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function Rn(e,t,n={}){return{importedName:e,localName:n.localName??null,sourcePath:t,kind:"namespace",used:n.used??!0,usedMembers:n.usedMembers??[],isTypeOnly:n.isTypeOnly}}function Ye(e,t,n){let i=[];for(let r of e.matchAll(t)){let o=r[0];if(!o||typeof r.index!="number")continue;let s=Kt(e,r.index,r.index+o.length);for(let a of n(r,s))i.push(a)}return i}function Ze(e,t,n,i){let r=ke(e,t);if(r){let o=n(r);if(o)return o}return i()}function Oo(e,t,n,i){let r=ke(e,t),o=K(t),s=o?n[o]:void 0;return r&&s?s(r):i()}function Ud(e,t,n){return Ze(e,t,i=>tR(e,t,i),()=>eR(e,t,n))}function eR(e,t,n){return Ye(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(i,r)=>{let o=i[1]?.trim();if(!o)return[];let s=qd(o).replace(/\.[^.]+$/,"");return[xi(o,s,Ao(e,t,o),He(r,s))]})}function tR(e,t,n){let i=me(n,new Set(["preproc_include"])),r=[];for(let o of n.rootNode.descendantsOfType("preproc_include")){let s=null;for(let c of o.namedChildren){if(c.type==="system_lib_string"){s=c.text.replace(/^<|>$/g,"");break}if(c.type==="string_literal"){s=c.namedChildren.find(u=>u.type==="string_content")?.text??c.text.replace(/^"|"$/g,"");break}}if(!s)continue;let a=qd(s).replace(/\.[^.]+$/,"");r.push(oe(s,a,Ao(e,t,s),i))}return r}function Wd(e,t,n){let i=[];for(let r of n.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)){let o=r[1]?.trim(),s=r[2]?.trim()??null,a=r[0];if(!o||!a||typeof r.index!="number")continue;let c=Kt(n,r.index,r.index+a.length);i.push({importedName:o,localName:s,sourcePath:$o(e,t,o),kind:s?"namespace":"side-effect",used:s?He(c,s):!0,usedMembers:s?Si(c,s):[]})}return i}function zd(e,t,n){let i=[];for(let r of n.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)){let o=r[1]?.trim();o&&i.push({specifier:o,sourcePath:$o(e,t,o)})}return i}function Gd(e,t,n){return Oo(e,t,{csharp:i=>iR(e,t,i),vb:i=>nR(e,t,i)},()=>{let i=Hd(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return Ye(n,i,(r,o)=>{let s=r[1]?.trim();if(!s)return[];let[a,c]=s.split(/\s*=\s*/),l=!!c,u=(l?c:a)?.trim()??s,d=u.split(".").pop()??u,m=l?a?.trim()??d:d;return[St(e,t,o,u,d,m,de(e,u,zt))]})})}function nR(e,t,n){let i=me(n,new Set(["imports_statement"])),r=[];for(let o of n.rootNode.descendantsOfType("imports_statement")){let s=o.namedChildren.filter(m=>m.type==="namespace_name");if(s.length===0)continue;let a=s[s.length-1],c=s.length>1?s[0]:null,l=a.text,u=l.split(".").pop()??l,d=c?.text??u;r.push(oe(u,d,de(e,l,zt),i,c?"namespace":"named"))}return r}function iR(e,t,n){let i=me(n,new Set(["using_directive"])),r=[];for(let o of n.rootNode.descendantsOfType("using_directive")){let s=o.namedChildren;if(s.length===0)continue;let a=null,c;s.length>=2&&s[0].type==="identifier"&&(s[1].type==="qualified_name"||s[1].type==="identifier")?(a=s[0],c=s[1]):c=s[s.length-1];let l=c.text,u=l.split(".").pop()??l,d=a?.text??u;r.push(oe(u,d,de(e,l,zt),i,a?"namespace":"named"))}return r}var rR=U("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function Jd(e,t){return rR.get(e,t,()=>{let n=new Set,i=F(e,t);if(!i)return n;let o=i.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g,s=>s.replace(/[^\r\n]/g," ")).replace(/<!--[\s\S]*?-->/g,s=>s.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\r\n]/g," "));for(let s of o.matchAll(/[A-Za-z_$][\w$]*/g))n.add(s[0]);return n})}function _a(e,t,n){return Ze(e,t,i=>sR(e,t,i),()=>oR(e,t,n))}function oR(e,t,n){return yR(n).flatMap(i=>bR(e,t,i.clause,i.specifier,i.start,i.end,n))}function sR(e,t,n){let i=aR(e,t,n),r=[];for(let o of n.rootNode.descendantsOfType("import_statement"))r.push(...cR(e,t,n,o,i));return r}function aR(e,t,n){let i=me(n,new Set(["import_statement"]));if(Nt(t))for(let r of Jd(e,t))i.add(r);return i}function cR(e,t,n,i,r){let o=pR(i);if(!o)return[];let s=lt(e,t,o),a=ze(i,"import_clause");return a?lR(n,a,s,r,fR(i.text)):[vn("*",s)]}function lR(e,t,n,i,r){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(uR(s.text,n,i,r));else if(s.type==="namespace_import"){let a=dR(e,s,n,i,r);a&&o.push(a)}else s.type==="named_imports"&&o.push(...mR(s,n,i,r));return o}function uR(e,t,n,i){return oe("default",e,t,n,"default",{isTypeOnly:i})}function dR(e,t,n,i,r){let s=ze(t,"identifier")?.text??"";if(!s)return null;let a=hR(e,s);return Rn("*",n,{localName:s,usedMembers:a,isTypeOnly:r,used:a.length>0||i.has(s)})}function mR(e,t,n,i){let r=[];for(let o of e.namedChildren){if(o.type!=="import_specifier")continue;let s=o.namedChild(0),a=o.namedChild(1);if(!s)continue;let c=s.text,l=a?.text??c;r.push(oe(c,l,t,n,"named",{isTypeOnly:i||gR(o.text)}))}return r}function pR(e){let t=ze(e,"string");if(!t)return null;let n=ze(t,"string_fragment");return n?n.text:null}function fR(e){return/^\s*import\s+type\b/.test(e)}function gR(e){return/^\s*type\b/.test(e.trim())}function hR(e,t){let n=new Set;for(let i of e.rootNode.descendantsOfType("member_expression")){let r=i.namedChild(0),o=i.namedChild(1);!r||!o||r.type!=="identifier"||r.text!==t||(o.type==="property_identifier"||o.type==="identifier")&&n.add(o.text)}return[...n]}function yR(e){let t=[],n=/^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let r of e.matchAll(n)){let o=r[0],s=r[1],a=r[2];!o||!a||typeof r.index!="number"||t.push({clause:s,specifier:a,start:r.index,end:r.index+o.length})}let i=/^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;for(let r of e.matchAll(i)){let o=r[0],s=r[1];!o||!s||typeof r.index!="number"||t.push({clause:null,specifier:s,start:r.index,end:r.index+o.length})}return t.sort((r,o)=>r.start-o.start)}function bR(e,t,n,i,r,o,s){let a=lt(e,t,i),c=Kt(s,r,o);return n?SR(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=Si(c,u.localName);return Rn(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||He(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?vn(u.importedName,u.sourcePath):xi(u.importedName,u.localName??"",u.sourcePath,u.localName?He(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[vn("*",a)]}function SR(e){let t=e.trim(),n=/^type\b/.test(t),i=t.replace(/^type\s+/,""),[r,o]=xR(i),s=[];return r&&s.push(...Kd(r,n)),o&&s.push(...Kd(o,n)),s}function Kd(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let i=n.slice(1,-1).trim();return i?Ve(i).map(r=>{let o=r.trim(),s=t||/^type\b/.test(o),a=o.replace(/^type\s+/,""),[c,l]=a.split(/\s+as\s+/);return{importedName:c.trim(),localName:(l??c).trim(),kind:"named",isTypeOnly:s}}):[]}return n.startsWith("* as ")?[{importedName:"*",localName:n.slice(5).trim(),kind:"namespace",isTypeOnly:t}]:[{importedName:"default",localName:n,kind:"default",isTypeOnly:t}]}function xR(e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];if(i==="{"&&t++,i==="}"&&t--,i===","&&t===0)return[e.slice(0,n).trim(),e.slice(n+1).trim()]}return[e.trim(),null]}function Aa(e,t,n){let i=ke(e,t);return i?IR(e,t,i):CR(e,t,n)}function CR(e,t,n){return[...vR(e,t,n),...RR(e,t,n),...kR(e,t,n)]}function vR(e,t,n){let i=[],r=/^[ \t]*export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(r)){if(typeof o.index!="number")continue;let s=o[1]??"",a=o[2]??"",c=Ve(s).map(d=>wR(d.trim())).filter(d=>!!d),l=Ci(n,o.index),u=Ci(n,o.index+o[0].length-1);i.push({kind:"named",sourcePath:lt(e,t,a),names:c,startLine:l,endLine:u})}return i}function RR(e,t,n){let i=[],r=/^[ \t]*export\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(r)){if(typeof o.index!="number")continue;let s=o[2]??"",a=Ci(n,o.index),c=Ci(n,o.index+o[0].length-1);i.push({kind:"star-as",sourcePath:lt(e,t,s),names:[],startLine:a,endLine:c})}return i}function kR(e,t,n){let i=[],r=/^[ \t]*export\s+\*\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(r)){if(typeof o.index!="number")continue;let s=o[1]??"",a=Ci(n,o.index),c=Ci(n,o.index+o[0].length-1);i.push({kind:"star",sourcePath:lt(e,t,s),names:[],startLine:a,endLine:c})}return i}function wR(e){if(!e)return null;let t=e.replace(/^type\s+/,"").trim();if(!t)return null;let n=t.match(/^(\w+)\s+as\s+(\w+)$/);if(n)return n[2]??null;let i=t.match(/^(\w+)$/);return i?i[1]??null:null}function Ci(e,t){let n=0;for(let i=0;i<t&&i<e.length;i++)e.charCodeAt(i)===10&&n++;return n}function IR(e,t,n){let i=[];for(let r of n.rootNode.descendantsOfType("export_statement")){let o=LR(e,t,r);if(o===void 0)continue;let s=r.startPosition.row,a=r.endPosition.row,c=DR(r,o,s,a);i.push(c)}return i}function LR(e,t,n){let i=ze(n,"string");if(!i)return;let r=ze(i,"string_fragment");if(r)return lt(e,t,r.text)}function DR(e,t,n,i){let r=ze(e,"export_clause");if(r){let s=[];for(let a of r.namedChildren){if(a.type!=="export_specifier")continue;let c=a.namedChild(0),l=a.namedChild(1);c&&s.push((l??c).text)}return{kind:"named",sourcePath:t,names:s,startLine:n,endLine:i}}return ze(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:i}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:i}}function Qd(e,t,n){return Oo(e,t,{java:i=>PR(e,t,i),kotlin:i=>NR(e,t,i),scala:i=>ER(e,t,i)},()=>Ye(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(i,r)=>{let o=i[1]?.trim();return o?TR(e,t,o,r):[]}))}function PR(e,t,n){let i=me(n,new Set(["import_declaration"])),r=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.children.some(d=>d.type==="asterisk"),c=o.namedChildren.find(d=>d.type==="scoped_identifier")??o.namedChildren.find(d=>d.type==="identifier");if(!c)continue;let l=c.text;if(s){r.push(Rn("*",de(e,l,We)));continue}let u=l.split(".").pop()??l;r.push(oe(u,u,de(e,l,We),i))}return r}function NR(e,t,n){let i=me(n,new Set(["import_header","import_list"])),r=[];for(let o of n.rootNode.descendantsOfType("import_header")){let s=o.namedChildren.find(p=>p.type==="identifier");if(!s)continue;let a=o.namedChildren.some(p=>p.type==="wildcard_import"),c=o.namedChildren.find(p=>p.type==="import_alias");if(a){r.push(Rn("*",de(e,s.text,We)));continue}let l=s.text,u=l.split(".").pop()??l,m=c?.namedChild(0)?.text??u;r.push(oe(u,m,de(e,l,We),i))}return r}function ER(e,t,n){let i=me(n,new Set(["import_declaration"])),r=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.namedChildren.find(d=>d.type==="namespace_selectors"||d.type==="namespace_wildcard"),a=o.namedChildren.filter(d=>d!==s&&(d.type==="identifier"||d.type==="stable_identifier")),c=a.map(d=>d.text).join(".");if(!c)continue;if(s?.type==="namespace_wildcard"){r.push(Rn("*",de(e,c,We)));continue}if(s?.type==="namespace_selectors"){for(let d of s.namedChildren)if(d.type==="arrow_renamed_identifier"){let[m,p]=d.namedChildren;if(!m)continue;let f=m.text,g=p?.text??f;if(f==="_")continue;r.push(oe(f,g,de(e,`${c}.${f}`,We),i))}else if(d.type==="identifier"){let m=d.text;r.push(oe(m,m,de(e,`${c}.${m}`,We),i))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;r.push(oe(l,l,de(e,u&&a.length>1?`${u}.${l}`:c,We),i))}return r}function TR(e,t,n,i){if(n.includes("{")&&n.includes("}")){let r=n.slice(0,n.indexOf("{")).replace(/\.$/,"").trim(),o=n.slice(n.indexOf("{")+1,n.lastIndexOf("}")).trim();return Ve(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.includes("=>")?a.split(/\s*=>\s*/):a.split(/\s+as\s+/),u=c?.trim();if(!u||u==="_")return[];let d=(l??u.split(".").pop()??u).trim(),m=u==="_"?r:`${r}.${u}`.replace(/\.\./g,".");return[St(e,t,i,m,u,d)]})}return[St(e,t,i,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Yd(e,t,n){return Ze(e,t,i=>FR(e,t,i),()=>Ye(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,r)=>{let o=i[1]?.trim();return o?Ve(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.split(/\s+as\s+/i),u=c?.trim()??a,d=u.split("\\").pop()??u,m=(l??d).trim();return[St(e,t,r,u,d,m,de(e,u.replace(/\\/g,"."),xn))]}):[]}))}function FR(e,t,n){let i=me(n,new Set(["namespace_use_declaration"])),r=[],o=(s,a,c)=>{r.push(oe(a,c,de(e,s.replace(/\\/g,"."),xn),i))};for(let s of n.rootNode.descendantsOfType("namespace_use_declaration")){let a=s.namedChildren.find(c=>c.type==="namespace_use_group");if(a){let c=s.namedChildren.find(l=>l.type==="namespace_name")?.text??"";for(let l of a.namedChildren){if(l.type!=="namespace_use_clause")continue;let{importedName:u,localName:d,qualified:m}=Xd(l,c);u&&o(m,u,d)}continue}for(let c of s.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:l,localName:u,qualified:d}=Xd(c,"");l&&o(d,l,u)}}return r}function Xd(e,t){let n=e.namedChildren.find(l=>l.type==="qualified_name"),i=e.namedChildren.filter(l=>l.type==="name"),r="";n?r=n.text:i.length>=1&&(r=i[0].text);let o=n&&i.length>0?i[i.length-1]:null,s=r.split("\\").pop()??r,a=o?.text??s,c=t?`${t}\\${r}`:r;return{importedName:s,localName:a,qualified:c}}function em(e,t,n){return Ze(e,t,i=>_R(e,t,i),()=>$R(n).flatMap(i=>OR(e,t,i,n)))}function _R(e,t,n){let i=me(n,new Set(["import_statement","import_from_statement"])),r=[];for(let o of n.rootNode.descendantsOfType("import_statement"))for(let s of o.namedChildren){let a=Zd(s);if(!a)continue;let c=yi(e,t,a.qualifiedName);r.push({importedName:a.qualifiedName,localName:a.localName,sourcePath:c,kind:"namespace",used:i.has(a.localName),usedMembers:[]})}for(let o of n.rootNode.descendantsOfType("import_from_statement")){let s=o.namedChild(0);if(!s)continue;let a=AR(s);if(a===null)continue;let c=yi(e,t,a);for(let l=1;l<o.namedChildCount;l+=1){let u=o.namedChild(l);if(u.type==="wildcard_import"){r.push({importedName:"*",localName:null,sourcePath:c,kind:"side-effect",used:!0,usedMembers:[]});continue}let d=Zd(u);d&&r.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:i.has(d.localName),usedMembers:[]})}}return r}function Zd(e){if(e.type==="aliased_import"){let t=e.namedChild(0),n=e.namedChild(1);return!t||!n?null:{qualifiedName:t.text,localName:n.text}}if(e.type==="dotted_name"){let t=e.text;return{qualifiedName:t,localName:t.split(".")[0]??t}}return e.type==="identifier"?{qualifiedName:e.text,localName:e.text}:null}function AR(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=ze(e,"import_prefix")?.text??"",n=ze(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function $R(e){let t=e.split(`
|
|
156
|
+
`),n=[],i=0;for(let r=0;r<t.length;r++){let o=t[r],s=o.trimStart(),a=i;if(i+=o.length+1,!s.startsWith("import ")&&!s.startsWith("from "))continue;let c=o,l=a+o.length,u=sr(o);for(;r+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){r++;let m=t[r];c+=`
|
|
157
|
+
${m}`,l+=1+m.length,u+=sr(m),i+=m.length+1}let d=MR(c);d&&n.push({...d,start:a,end:l})}return n}function MR(e){let t=e.replace(/\\\s*\n/g," ").trim();if(t.startsWith("import "))return{kind:"import",module:null,clause:t.slice(7).trim()};let n=t.match(/^from\s+([.\w]+)\s+import\s+([\s\S]+)$/);if(!n)return null;let i=n[2].trim();return i.startsWith("(")&&i.endsWith(")")&&(i=i.slice(1,-1).trim()),{kind:"from",module:n[1],clause:i}}function OR(e,t,n,i){let r=Kt(i,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return Ve(o).flatMap(c=>{let l=c.trim().replace(/,$/,"");if(!l)return[];let[u,d]=l.split(/\s+as\s+/),m=u.trim(),p=(d??m.split(".")[0]??m).trim(),f=yi(e,t,m),g=Si(r,p);return[{importedName:m,localName:p,sourcePath:f,kind:"namespace",used:He(r,p)||g.length>0,usedMembers:g}]});let s=n.module?yi(e,t,n.module):null,a=[];for(let c of Ve(o)){let l=c.trim().replace(/,$/,"");if(!l)continue;if(l==="*"){a.push({importedName:"*",localName:null,sourcePath:s,kind:"side-effect",used:!0,usedMembers:[]});continue}let[u,d]=l.split(/\s+as\s+/),m=(d??u).trim();a.push({importedName:u.trim(),localName:m,sourcePath:s,kind:"named",used:He(r,m),usedMembers:[]})}return a}import{basename as jR}from"path";function tm(e,t,n){return Ze(e,t,i=>HR(e,t,i),()=>BR(e,t,n))}function BR(e,t,n){return Ye(n,/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm,(i,r)=>{let o=i[1],s=i[2];if(!o||!s)return[];let a=o==="require_relative"?_o(e,t,s):null;if(a){let c=nm(s);return[xi(c,c,a,He(r,c))]}return[vn(s,a)]})}function HR(e,t,n){let i=me(n,new Set([])),r=[],o=new Set(["require","require_relative","load"]);for(let s of n.rootNode.descendantsOfType("call")){let a=s.namedChild(0);if(!a||a.type!=="identifier"||!o.has(a.text))continue;let l=s.namedChildren.find(p=>p.type==="argument_list")?.namedChild(0);if(!l||l.type!=="string")continue;let d=l.namedChildren.find(p=>p.type==="string_content")?.text;if(!d)continue;let m=a.text==="require_relative"?_o(e,t,d):null;if(m){let p=nm(d);r.push(oe(p,p,m,i))}else r.push(vn(d,m))}return r}function nm(e){return bo(jR(e).replace(/\.[^.]+$/,""),/_/)}function im(e,t,n){return Ze(e,t,i=>VR(e,t,i),()=>Ye(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,r)=>{let o=i[1]?.trim();return o?qR(e,t,o,r):[]}))}function VR(e,t,n){let i=me(n,new Set(["use_declaration"])),r=[];for(let o of n.rootNode.descendantsOfType("use_declaration")){let s=o.namedChild(0);if(s)for(let a of ar(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=Ft(e,t,a.qualifiedName)??Ft(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));r.push(oe(a.importedName,a.localName,c,i))}}return r}function ar(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:jo(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,i=n.split("::").pop()??n;return[{qualifiedName:jo(t,n),importedName:i,localName:i}]}case"scoped_use_list":{let n=e.namedChild(0),i=e.namedChild(1);if(!n||!i)return[];let r=jo(t,n.text),o=[];for(let s of i.namedChildren)o.push(...ar(s,r));return o}case"use_list":{let n=[];for(let i of e.namedChildren)n.push(...ar(i,t));return n}case"use_as_clause":{let n=e.namedChild(0),i=e.namedChild(1);if(!n||!i)return[];let r=ar(n,t),o=i.text;return r.map(s=>({...s,localName:o}))}case"use_wildcard":{let n=e.namedChild(0),i=n?n.text:"";return[{qualifiedName:jo(t,`${i}::*`),importedName:"*",localName:"*"}]}default:return[]}}function jo(e,t){return e?t?`${e}::${t}`:e:t}function qR(e,t,n,i){let r=n.trim();if(r.includes("{")&&r.includes("}")){let u=r.slice(0,r.indexOf("{")).replace(/::$/,"").trim(),d=r.slice(r.indexOf("{")+1,r.lastIndexOf("}")).trim();return Ve(d).flatMap(m=>{let p=m.trim();if(!p||p==="self")return[];let[f,g]=p.split(/\s+as\s+/),y=f?.trim();if(!y)return[];let S=(g??y.split("::").pop()??y).trim(),R=`${u}::${y}`.replace(/::::/g,"::");return[St(e,t,i,R,y.split("::").pop()??y,S,Ft(e,t,u))]})}let[o,s]=r.split(/\s+as\s+/),a=o?.trim()??r,c=(s??a.split("::").pop()??a).trim(),l=Ft(e,t,a)??Ft(e,t,a.split("::").slice(0,-1).join("::"));return[St(e,t,i,a,a.split("::").pop()??a,c,l)]}function rm(e,t,n){let i=ke(e,t);if(i)return UR(e,t,i);let r=[];for(let o of n.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)){let s=o[1]?.trim();s&&r.push(...zR(e,t,s))}return r}function UR(e,t,n){let i=[];for(let r of n.rootNode.descendantsOfType("use_declaration")){if(!WR(r))continue;let o=r.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of ar(o,""))s.importedName&&i.push($a(e,t,s.qualifiedName))}return i}function WR(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function zR(e,t,n){let i=n.trim();if(i.includes("{")&&i.includes("}")){let r=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),o=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return Ve(o).flatMap(s=>{let a=s.trim();if(!a||a==="self")return[];let[c]=a.split(/\s+as\s+/),l=`${r}::${c?.trim()??a}`.replace(/::::/g,"::");return[$a(e,t,l)]})}return[$a(e,t,i)]}function $a(e,t,n){return{specifier:n,sourcePath:Ft(e,t,n)??Ft(e,t,n.split("::").slice(0,-1).join("::"))}}function kn({language:e,extensions:t,imports:n,parseImports:i}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:i}}function om(e,t){let n=t.toLowerCase();for(let i of e)for(let r of i.extensions)if(n.endsWith(r))return i;return null}var GR={language:"javascript",extensions:Sn,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:_a,parseReExports:Aa},JR=kn({language:"python",extensions:Po,imports:"ast-with-regex-fallback",parseImports:em}),KR=kn({language:"jvm",extensions:We,imports:"ast-dispatch-with-regex-fallback",parseImports:Qd}),QR={language:"rust",extensions:No,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:im,parseExports:rm},XR=kn({language:"ruby",extensions:Eo,imports:"ast-with-regex-fallback",parseImports:tm}),YR=kn({language:"c/cpp",extensions:To,imports:"ast-with-regex-fallback",parseImports:Ud}),ZR=kn({language:"dotnet",extensions:zt,imports:"ast-dispatch-with-regex-fallback",parseImports:Gd}),ek={language:"dart",extensions:Fo,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:Wd,parseExports:zd},tk=kn({language:"php",extensions:xn,imports:"ast-with-regex-fallback",parseImports:Yd}),nk=[GR,JR,KR,QR,XR,YR,ZR,ek,tk];function Bo(e){return om(nk,e)}var Ma={clearGroups:["whole-project","source-file"]},ik=U("source-imports",Ma),rk=U("source-exports",Ma),ok=U("source-reexports",Ma);function cr(e,t){let n=ct(t);return ok.get(e,n,()=>{let i=Bo(n);if(!i?.parseReExports)return[];let r=F(e,n);if(!r)return[];let o=Z(e,n,r),s=Fa(e),a=ae(e,"source-reexports",n,o);if(a!==null)try{let l=JSON.parse(a);if(l.resolutionFingerprint===s&&Array.isArray(l.reExports))return l.reExports}catch{}let c=i.parseReExports(e,n,r);return ce(e,"source-reexports",n,o,JSON.stringify({resolutionFingerprint:s,reExports:c})),c})}function Ie(e,t){let n=ct(t);return ik.get(e,n,()=>{let i=Bo(n);if(!i)return[];let r=F(e,n);if(!r)return[];let o=Z(e,n,r),s=Fa(e),a=ae(e,"source-imports",n,o);if(a!==null)try{let l=JSON.parse(a);if(l.resolutionFingerprint===s&&Array.isArray(l.imports))return l.imports}catch{}let c=i.parseImports(e,n,r);return ce(e,"source-imports",n,o,JSON.stringify({resolutionFingerprint:s,imports:c})),c})}function Ho(e,t){let n=ct(t);return rk.get(e,n,()=>{let i=Bo(n);if(!i?.parseExports)return[];let r=F(e,n);return r?i.parseExports(e,n,r):[]})}var sk=U("file-dep-graph",{clearGroups:["whole-project"]});function pe(e,t){return sk.get(e,t??"",()=>{let n=new Map,i=new Set(B(e,{includeIgnored:!1})),r=(o,s)=>ck(e,n,i,o,s);for(let o of ak(e,t))r(o.from_file,o.to_file);for(let o of i)if(!(t&&!o.includes(t)))for(let s of Ie(e,o))s.sourcePath&&r(o,s.sourcePath);return n})}function ak(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
|
|
109
158
|
d1.relative_path AS from_file,
|
|
110
159
|
d2.relative_path AS to_file
|
|
111
160
|
FROM mentions m
|
|
@@ -123,11 +172,11 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
123
172
|
WHERE d1.id != d2.id
|
|
124
173
|
AND m.role != 1
|
|
125
174
|
${e.pathExclusionsFor("d1","d2")}
|
|
126
|
-
${n}`)}function
|
|
175
|
+
${n}`)}function ck(e,t,n,i,r){if(i===r||e.isIgnored(i)||e.isIgnored(r)||!n.has(r))return;let o=t.get(i);o||(o=new Set,t.set(i,o)),o.add(r)}import{existsSync as Vo,readFileSync as lk,readdirSync as am}from"fs";import{join as lr}from"path";var uk={files:new Set,pathPrefixes:[]},Oa=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,dk=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,cm=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],mk=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),pk=4,fk=re("package-surface",{clearGroups:["whole-project"]});function gk(e){return fk.get(e,()=>hk(e.config.projectRoot))}function Ri(e,t){let n=gk(e);return n.files.has(t)?!0:n.pathPrefixes.some(i=>t.startsWith(i))}function hk(e){let t=new Set,n=[];for(let{manifest:i,packageRoot:r}of yk(e))for(let o of bk(i))Sk(e,r,o,t,n);return t.size===0&&n.length===0?uk:{files:t,pathPrefixes:n}}function yk(e){let t=[],n=um(e,"");return n&&t.push({manifest:n,packageRoot:""}),lm(e,"",t,0),t}function lm(e,t,n,i){if(i>=pk)return;let r=lr(e,t);if(Vo(r))for(let o of am(r,{withFileTypes:!0})){if(!o.isDirectory()||mk.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=um(e,s);a&&n.push({manifest:a,packageRoot:s}),lm(e,s,n,i+1)}}function um(e,t){try{let n=lk(lr(e,t,"package.json"),"utf-8"),i=JSON.parse(n);return i&&typeof i=="object"?i:null}catch{return null}}function bk(e){let t=[];for(let i of["main","module","types","browser"])typeof e[i]=="string"&&t.push(e[i]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let i of Object.values(n))typeof i=="string"&&t.push(i);return dm(e.exports,t),t}function dm(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))dm(n,t)}function Sk(e,t,n,i,r){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let c=o.slice(0,s);for(let l of sm(c))l!==""&&r.push(vi(t,l));return}let a=o.replace(dk,"");for(let c of sm(a)){c===a&&c===o&&i.add(vi(t,o));for(let l of cm)xk(e,i,t,c+l)}i.add(vi(t,o))}function sm(e){let t=[e];return Oa.test(e)&&(t.push(e.replace(Oa,"src/")),t.push(e.replace(Oa,""))),t}function xk(e,t,n,i){let r=vi(n,i);if(t.add(r),!i.startsWith("src/")||Vo(lr(e,r)))return;let o=cm.find(u=>i.endsWith(u));if(!o)return;let s=i.slice(0,-o.length);Ck(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let c=s.slice(0,a),l=s.slice(a+1);for(let u of mm(e,n,c,`${l}${o}`))t.add(u)}function Ck(e,t,n,i,r){let o=vi(n,`${i}/index${r}`);Vo(lr(e,o))&&t.add(o)}function mm(e,t,n,i){let r=lr(e,t,n);if(!Vo(r))return[];let o=[];for(let s of am(r,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...mm(e,t,a,i)):s.isFile()&&s.name===i&&o.push(vi(t,a))}return o}function vi(e,t){return e?`${e}/${t}`:t}function X(e){let t=ki(e);return $k(t)?"test":Mk(t)?"worker":Ok(t)?"entry":jk(t)?"barrel":"source"}function qo(e){return X(e)==="barrel"}function fm(e){return vk.get(e,()=>{let t=pe(e),n=$e(e).filter(o=>{let s=X(o);return s==="entry"||s==="worker"}),i=new Set,r=new Set;for(;n.length>0;){let o=n.shift();if(!i.has(o)){i.add(o),X(o)==="barrel"&&r.add(o);for(let s of t.get(o)??[])i.has(s)||n.push(s)}}return r})}var vk=re("live-barrels",{clearGroups:["whole-project"]});function ja(e,t){return fm(e).has(ki(t))}function gm(e){let t=fm(e);return $e(e).filter(n=>qo(n)&&!t.has(n)&&!Rk(e,n))}function Rk(e,t){let n=ki(t),i=ye(e,n)?.callables;return i&&i.length>0?!0:(e.get(`SELECT COUNT(*) AS n
|
|
127
176
|
FROM defn_enclosing_ranges der
|
|
128
177
|
JOIN documents d ON d.id = der.document_id
|
|
129
178
|
WHERE d.relative_path = ?
|
|
130
|
-
AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function
|
|
179
|
+
AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Oe(e,t){let n=X(t);return n==="entry"||n==="worker"||ja(e,t)}function fe(e,t,n){let i=ki(n);if(Ri(e,i)||Pk(t,i))return!0;let r=e.config.entryRoots;return r?!!(r.files?.some(o=>ki(o)===i)||r.pathPrefixes?.some(o=>i.startsWith(ki(o)))||r.qualifiedVars?.some(o=>Bk(t,o))||r.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}var hm=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),kk=new Set(["default","generateMetadata","generateStaticParams"]),wk=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),Ik=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),Lk=new Set(["load","actions","entries",...hm]),Dk=new Set(["default"]);function Pk(e,t){let n=M(e);return n===""?!1:Nk(t)?hm.has(n):Ek(t)?kk.has(n):Tk(t)?wk.has(n):Fk(t)?Ik.has(n):_k(t)?Lk.has(n):Ak(t)?Dk.has(n):!1}function Nk(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Ek(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Tk(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Fk(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function _k(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function Ak(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function $k(e){return!!(/\.(?:test|spec)\.[a-z0-9]+$/i.test(e)||/(?:^|\/)(?:_)?test_[^/]+$/i.test(e)||/(?:^|\/)spec_[^/]+$/i.test(e)||/(?:^|\/)[^/]+_test\.[a-z0-9]+$/i.test(e)||/(?:^|\/)[^/]+_tests\.rs$/i.test(e)||/(?:^|\/)tests\.rs$/i.test(e)||/(?:^|\/)[^/]+_spec\.[a-z0-9]+$/i.test(e)||/(?:^|\/)__tests__\//i.test(e)||/(?:^|\/)test\//i.test(e)||/(?:^|\/)tests\//i.test(e)||/(?:^|\/)__fixtures__\//i.test(e)||/(?:^|\/)__mocks__\//i.test(e)||/(?:^|\/)test-support\//i.test(e)||/(?:^|\/)test-utils\//i.test(e)||/(?:^|\/)testing\//i.test(e))}function Mk(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function Ok(e){let t=e.split("/"),n=t[t.length-1]??e;return n==="cli.ts"||n==="cli.js"||n==="postinstall.ts"||n==="postinstall.js"||n==="main.ts"||n==="main.js"||n==="main.rs"||n==="main.go"||n==="main.py"||n==="build.rs"||n==="lib.rs"||/\bsrc\/bin\/[^/]+\.rs$/.test(e)||/(?:^|\/)examples\/[^/]+\.rs$/.test(e)||/(?:^|\/)tests\/[^/]+\.rs$/.test(e)||/(?:^|\/)benches\/[^/]+\.rs$/.test(e)?!0:n==="index.ts"||n==="index.js"?/(?:^|\/)(?:apps|services)\/[^/]+\/src\/index\.(?:ts|js)$/.test(e)?!0:t.length<=2:!1}function jk(e){return e==="index.ts"||e==="index.js"||e.endsWith("/index.ts")||e.endsWith("/index.js")||e.endsWith("/mod.rs")||e.endsWith("/__init__.py")}function ki(e){return e.replace(/\\/g,"/")}function Bk(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let i=t.slice(0,n),r=t.slice(n+1);return e.includes(pm(i)+"/")&&e.includes(pm(r)+".")}function pm(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function Uo(e,t,n,i={}){if(!n)return[];let r=F(e,t);return r?r.indexOf(n)===-1?[]:(_t(e,t).get(n)??[]).filter(s=>!Hk(s,i)):[]}function Hk(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var Vk=U("file-identifiers",{clearGroups:["whole-project","source-file"]});function ym(e,t){let n=ye(e,t);return n?n.fileIdentifiers:Vk.get(e,t,()=>new Set(_t(e,t).keys()))}var qk=U("file-ident-lines",{clearGroups:["whole-project","source-file"]});function _t(e,t){let n=ye(e,t);return n?n.identifierLineMap:qk.get(e,t,()=>Wk(e,t))}var Uk=U("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function bm(e,t){let n=ye(e,t);return n?n.identifiersByLine:Uk.get(e,t,()=>{let i=_t(e,t),r=0;for(let s of i.values()){let a=s[s.length-1];a!==void 0&&a>r&&(r=a)}let o=new Array(r+1);for(let s=0;s<=r;s+=1)o[s]=new Set;for(let[s,a]of i)for(let c of a)o[c].add(s);return o})}function Wk(e,t){let n=new Map,i=(a,c)=>{let l=n.get(a);if(!l){n.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)},r=F(e,t);if(!r)return n;let o=Cn(r).split(/\r?\n/),s=/\b([A-Za-z_$][\w$]*)\b/g;for(let a=0;a<o.length;a+=1){let c=o[a]??"";for(let l of c.matchAll(s))l[1]&&i(l[1],a)}return n}function Sm(e,t){return Ba(e,t,n=>{let i=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
|
|
131
180
|
m.symbol_id,
|
|
132
181
|
d.relative_path,
|
|
133
182
|
COUNT(*) AS ref_count
|
|
@@ -135,23 +184,23 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
135
184
|
JOIN chunks c ON m.chunk_id = c.id
|
|
136
185
|
JOIN documents d ON c.document_id = d.id
|
|
137
186
|
WHERE m.role != 1
|
|
138
|
-
${
|
|
187
|
+
${i}
|
|
139
188
|
${e.pathExclusionsFor("d")}
|
|
140
|
-
GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function
|
|
189
|
+
GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function xm(e,t){return Ba(e,t,n=>{let i=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path
|
|
141
190
|
FROM mentions m
|
|
142
191
|
JOIN chunks c ON m.chunk_id = c.id
|
|
143
192
|
JOIN documents d ON c.document_id = d.id
|
|
144
193
|
WHERE m.role != 1
|
|
145
|
-
${
|
|
146
|
-
${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function
|
|
194
|
+
${i}
|
|
195
|
+
${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function wi(e,t){return Ba(e,t,n=>{let i=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path, c.document_id,
|
|
147
196
|
c.start_line AS chunk_start, c.end_line AS chunk_end
|
|
148
197
|
FROM mentions m
|
|
149
198
|
JOIN chunks c ON m.chunk_id = c.id
|
|
150
199
|
JOIN documents d ON c.document_id = d.id
|
|
151
200
|
WHERE m.role != 1
|
|
152
|
-
${
|
|
201
|
+
${i}
|
|
153
202
|
${e.pathExclusionsFor("d")}
|
|
154
|
-
ORDER BY d.relative_path, c.start_line`,...n??[])})}function
|
|
203
|
+
ORDER BY d.relative_path, c.start_line`,...n??[])})}function Ba(e,t,n){if(!t)return n();if(t.length===0)return[];let i=[];for(let r=0;r<t.length;r+=750)i.push(...n(t.slice(r,r+750)));return i}function Wo(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Qt(e,t){return Wo(e)===Wo(t)}function zo(e,t){let n=Cm(e);return n?t.filter(i=>Cm(i.file)===n):t}function Go(e,t,n,i){let r=n.find(o=>o.file===t);if(r)return r;if(i){let o=new Set(Ie(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(Qt(a,s.file))return s;return null}return n.length===1?n[0]:null}function Cm(e){let t=K(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var zk=re("global-leaf-index",{clearGroups:["whole-project"]});function wn(e){return zk.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
|
|
155
204
|
COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
|
|
156
205
|
FROM global_symbols gs
|
|
157
206
|
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
@@ -165,8 +214,10 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
165
214
|
GROUP BY m.symbol_id
|
|
166
215
|
) mention_doc ON mention_doc.symbol_id = gs.id
|
|
167
216
|
WHERE 1 = 1
|
|
168
|
-
${e.symbolNoiseFor("gs")}`),n=new Map;for(let
|
|
169
|
-
`),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let u=a[l]??"";s.lastIndex=0;let d;for(;(d=s.exec(u))!==null;)c.push({file:t,line:l,column:d.index})}return No(c.filter(l=>Qr(n,Xd.join(n,l.file))===t))}function wa(e){for(let t=e;t;t=t.getParent()){let n=t.getKindName();if(n.includes("Type")||n==="InterfaceDeclaration"||n==="TypeAliasDeclaration")return!0;if(n==="CallExpression"||n==="NewExpression"||n==="ExpressionStatement")return!1}return!1}function hr(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function No(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.line}:${r.column}`;t.has(i)||(t.add(i),n.push(r))}return n}function Qr(e,t){let n=Xd.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function ik(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tm(e,t,n,r){let i=ok(t,r);return i.size===0?new Map:sk(e,n,i)}function ok(e,t){let n=new Map;for(let r of z(e,t)){let i=$(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function sk(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of ak(e,o)){let a=n.get(s);if(!a)continue;let c=hr(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let u=Math.abs(c-l.startLine),d=i.get(l.symbolId);d!==void 0&&d<=u||(i.set(l.symbolId,u),r.set(l.symbolId,o))}}}),r}function ak(e,t){let n=[],r=i=>{i&&!n.includes(i)&&n.push(i)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let i=t.getNameNode();r(i?.getText())}if("getName"in t&&typeof t.getName=="function"){let i=t.getName();r(i)}return e.Node.isIdentifier(t)&&r(t.getText()),n}var ck=U("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function rm(e,t,n,r){let i=om(e,t),o=nm(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||$(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return nm(s,n)}function im(e,t){let n=new Map;for(let[r,i]of om(e,t)){let o=i[0];o&&n.set(r,o)}return n}function om(e,t){return ck.get(e,t,()=>{let n=new Map;for(let r of z(e,t)){let i=r.leaf||$(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push({...r,leaf:i})}for(let r of n.values())r.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return n})}function nm(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let i of e){let o=Math.abs(i.startLine-t);(o<r||o===r&&n&&i.startLine<n.startLine)&&(n=i,r=o)}return n}import lk from"path";var Yr=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function yn(e){let t=e.toLowerCase();return Yr.some(n=>t.endsWith(n))}function sm(e,t){let n=new Map,r=i=>yn(i)?nt(n,i,()=>{let o=lk.join(e.config.projectRoot,i);for(let{project:s}of t){let a=s.getSourceFile(o)??s.addSourceFileAtPathIfExists(o)??null;if(a)return{project:s,sourceFile:a}}return null}):null;return{sourceFile:i=>r(i)?.sourceFile??null,sourceFileMatch:r,indexedTypeScriptLikeDocuments:()=>j(e,{extensions:Yr})}}import Gt from"path";import{existsSync as Eo,readdirSync as uk,readFileSync as am}from"fs";function cm(e){let t=Gt.join(e,"package.json");if(!Eo(t))return[];let n;try{n=JSON.parse(am(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>dk(e,i)).flatMap(i=>mk(e,i))}function dk(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=Gt.join(e,t);return Eo(Gt.join(s,"package.json"))?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=Gt.join(e,r||".");if(!Eo(o))return[];try{return uk(o).map(s=>Gt.join(o,s,i)).filter(s=>Eo(Gt.join(s,"package.json")))}catch{return[]}}function mk(e,t){try{let n=JSON.parse(am(Gt.join(t,"package.json"),"utf8"));if(!n.name)return[];let r=Gt.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:r,sourceRootRelative:`${r}/src`}]}catch{return[]}}function lm(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function um(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as Zr,readFileSync as pk,readdirSync as fk,statSync as gk}from"fs";import oe from"path";var Ia=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Da(e,t){let r=t?oe.dirname(oe.join(e,t)):e,i=oe.resolve(e);for(;r.startsWith(i);){for(let s of Ia){let a=oe.join(r,s);if(Zr(a))return a}let o=oe.dirname(r);if(o===r)break;r=o}for(let o of Ia){let s=oe.join(e,o);if(Zr(s))return s}return null}function dm(e){let t=e.config.projectRoot,n=new Set(Pa(t,e.config.semantic?.typescript?.tsconfigs)),r=j(e,{includeIgnored:!1,extensions:Yr});for(let i of r){let o=Da(t,i);o&&n.add(oe.resolve(o))}if(n.size===0){let i=Da(t);i&&n.add(oe.resolve(i))}return[...n].filter(i=>!mm(t,i)).sort((i,o)=>i.localeCompare(o))}function Pa(e,t=[]){let n=new Set;for(let r of t){let i=oe.isAbsolute(r)?r:oe.join(e,r);Zr(i)&&n.add(oe.resolve(i))}for(let r of hk(e))for(let i of Ia){let o=oe.join(r,i);Zr(o)&&n.add(oe.resolve(o))}if(n.size===0){let r=Da(e);r&&n.add(oe.resolve(r))}return[...n].filter(r=>!mm(e,r)).sort((r,i)=>r.localeCompare(i))}function hk(e){let t=oe.join(e,"package.json");if(!Zr(t))return[];let n;try{n=JSON.parse(pk(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>yk(e,i))}function yk(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=oe.join(e,t);return La(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=oe.join(e,r||".");return La(o)?fk(o).map(s=>oe.join(o,s,i)).filter(La):[]}function La(e){try{return gk(e).isDirectory()}catch{return!1}}function mm(e,t){let n=oe.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}import{createRequire as bk}from"module";var Sk=bk(import.meta.url),ei;function pm(){if(ei!==void 0)return ei;try{ei=Sk("ts-morph")}catch{ei=null}return ei}function fm(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!1})}))}function To(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function ym(e,t){let n=pm();if(!n)return To("ts-morph is not installed");let r=dm(e);if(r.length===0)return To("no tsconfig found");try{let i=fm(n,r);return new Na(e,n,i)}catch(i){return To(i instanceof Error?i.message:String(i),r[0],r)}}var Na=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=cm(t.config.projectRoot),this.sourceFiles=sm(t,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return nt(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=[];for(let i of n.getImportDeclarations())for(let o of this.importUsageForDeclaration(t,i))r.push(o);return r})}referencesFor(t){return nt(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),r=this.packageImportReferencesForDefinition(t);return n?Qd(n,t,r,this.db.config.projectRoot):r})}calleesFor(t){return nt(this.calleesCache,t.symbolId,()=>nt(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return nt(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let r=n.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return hm(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${hm(o)}`})}importUsageForDeclaration(t,n){let r=tt(this.db,t,n.getModuleSpecifierValue()),i=gm(n);return n.getImportClause()?.isTypeOnly()?i.map(o=>xk(t,r,o)):i.map(o=>this.valueImportUsageForEntry(t,r,o))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let l of i)for(let u of Yd(l,t,r.identifier,this.db.config.projectRoot))o.push(u);let s=o.some(l=>!wa(l.node)),a=o.some(l=>wa(l.node)),c=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:c,isUsed:c||o.length>0,isTypeUsed:c||a,isValueUsed:s,references:o.map(l=>l.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,r);for(let[r,i]of t)t.set(r,No(i));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,r,o)}addPackageImportReferencesForDeclaration(t,n,r,i){let o=lm(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of gm(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=em(a.identifier,r,this.db.config.projectRoot);l.length>0&&Rk(t,c,l)}}packageExports(){if(this.packageExportIndex)return this.packageExportIndex;let t=new Map;for(let n of this.workspacePackages){let r=new Map;for(let i of um(n))this.collectPackageExports(n,i,r,new Set);r.size>0&&t.set(n.name,r)}return this.packageExportIndex=t,t}collectPackageExports(t,n,r,i){if(i.has(n))return;i.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?tt(this.db,n,a):n;if(!c||!c.startsWith(`${t.sourceRootRelative}/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,c,r,i);continue}for(let u of l){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,f=this.indexedDefinitionByLeaf(c,d);if(!f)continue;let h=r.get(m);h||(h=new Set,r.set(m,h)),h.add(f.symbolId)}}}indexedDefinitionByLeaf(t,n){return nt(this.indexedDefinitionLeafCache,t,()=>im(this.db,t)).get(n)??null}nodeForDefinition(t){return nt(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return nt(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?tm(this.tsMorph,this.db,n,t):new Map})}definitionFromSymbol(t){let n=t.getDeclarations();for(let r of n){let i=r.getSourceFile(),o=Qr(this.db.config.projectRoot,i.getFilePath());if(!o||this.db.isIgnored(o))continue;let s=hr(i,r),a=rm(this.db,o,s,t.getName());if(a)return{symbol:a.symbol,file:a.relativePath,line:a.startLine}}return null}calleeMapForFile(t){let n=this.sourceFiles.sourceFile(t);if(!n)return new Map;let r=z(this.db,t).sort((o,s)=>o.startLine-s.startLine||s.endLine-o.endLine);if(r.length===0)return new Map;let i=new Map;n.forEachDescendant(o=>{if(!this.tsMorph.Node.isCallExpression(o)&&!this.tsMorph.Node.isNewExpression(o))return;let s=this.semanticCalleeForCallNode(n,r,o);s&&Ck(i,s.callerId,s.target)});for(let[o,s]of i)i.set(o,kk(s));return i}semanticCalleeForCallNode(t,n,r){let i=vk(n,hr(t,r));if(!i)return null;let o=r.getExpression(),s=o.getSymbol()??o.getType().getSymbol(),a=s?this.definitionFromSymbol(s):null;return a?{callerId:i.symbolId,target:{symbol:a.symbol,file:a.file,line:a.line}}:null}};function gm(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let r=e.getNamespaceImport();r&&t.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let i of e.getNamedImports()){let o=i.getNameNode(),a=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function xk(e,t,n){return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function Ck(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function vk(e,t){let n=null;for(let r of e)t<r.startLine||t>r.endLine||(!n||r.startLine>=n.startLine)&&(n=r);return n}function Rk(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function kk(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}|${r.line}`;t.has(i)||(t.add(i),n.push(r))}return n}function hm(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Ea=new WeakMap;$t({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>Ea.delete(e)});function zt(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,r=Ea.get(e);r||(r=new Map,Ea.set(e,r));let i=r.get(n);if(i)return i;let o=ym(e,t);return r.set(n,o),o}function ti(e,t){let n=Fo(e,t);return n?n.importUsage(t):[]}function Jt(e,t){let n=Fo(e,t.relativePath);return n?n.referencesFor(t):[]}function mt(e,t){let n=new Map,r=fu(e),i=[];for(let o of t){let s=wk(e,o,r,i);for(let a of s){if(a.file===o.relativePath||e.isIgnored(a.file))continue;let c=n.get(o.symbolId);c||(c=new Set,n.set(o.symbolId,c)),c.add(a.file)}}return i.length>0&&zt(e).availability().available&&bu(e,i),n}function wk(e,t,n,r){if(!n||!yn(t.relativePath))return Jt(e,t);let i=hu(e,t.relativePath,t.symbol,n);if(i!==null){let s=Lk(i);if(s)return s}let o=Jt(e,t);return r.push({relativePath:t.relativePath,symbol:t.symbol,projectFingerprint:n,payload:JSON.stringify(o)}),o}function Lk(e){try{return JSON.parse(e)}catch{return null}}function _o(e,t){let n=new Map;for(let r of t){let i=Fo(e,r.relativePath);if(!i)continue;let o=i.calleesFor(r);o.length>0&&n.set(r.symbolId,o)}return n}function bm(e,t){let n=Fo(e,t.relativePath);return n?n.signatureFor(t):null}function Fo(e,t){if(!yn(t))return null;let n=zt(e,t);return n.availability().available?n:null}function $o(e,t){let n=new Map;for(let r of he(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i&&Sm(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)Sm(n,o,r.sourcePath)}return n}function Sm(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function yr(e,t,n){let r=hn(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[ni(r[0])];let i=r.filter(c=>c.file===t);if(i.length>0)return i.map(ni);let o=$o(e,t),s=o.get(n);if(s)for(let c of s){let l=r.filter(u=>Wt(c,u.file));if(l.length>0)return l.map(ni)}let a=new Set;for(let c of o.values())for(let l of c)a.add(l);for(let c of a){let l=r.filter(u=>Wt(c,u.file));if(l.length>0&&l.length===r.length)return l.map(ni)}return[]}function Cm(e,t,n){let r=yr(e,t,n);if(r.length>0)return r;let i=hn(e).get(n);return!i||i.length===0?[]:i.map(ni)}function vm(e,t,n={}){let r=ao(e,t);if(!r)return[];let i=$(r.symbol);if(!i)return[];if(n.semantic!==!1){let s=Jt(e,{...r,leaf:i,parentTypeName:null,isFunctionLike:!1,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:null});if(s.length>0){let a=new Map;for(let c of s){let l=a.get(c.file)??[];l.push(c.line),a.set(c.file,l)}return xm(e,a)}}let o=new Map;for(let s of Ie(e)){let a=F(e,s);if(!a||a.indexOf(i)===-1||s!==r.relativePath&&!yr(e,s,i).some(u=>u.symbolId===r.symbolId))continue;let c=wo(e,s,i,s===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});c.length>0&&o.set(s,c)}return xm(e,o)}function Rm(e,t){let n=new Map;for(let a of t){if(!a.leaf)continue;let c=n.get(a.leaf)??[];c.push(a),n.set(a.leaf,c)}if(n.size===0)return new Map;let r=new Set(t.map(a=>a.symbolId)),i=new Set(n.keys()),o=Xr(i),s=new Map;for(let a of Ie(e)){if(!Po(F(e,a),o))continue;let c=qd(e,a);if(c.size!==0){for(let l of c)if(n.has(l))for(let u of yr(e,a,l)){if(!r.has(u.symbolId)||a===u.relativePath)continue;let d=s.get(u.symbolId);d||(d=new Set,s.set(u.symbolId,d)),d.add(a)}}}return s}function ni(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function xm(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=z(e,i);for(let a of o){let c=Be(s,a),l=`${i}|${a}|${c?.symbol??""}`;r.has(l)||(r.add(l),n.push({file:i,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function bn(e,t){let n=Tk(e,t);return n?_k(e,Dk(e,n.match,n.identifier)):[]}function Kt(e,t,n={}){return Ik(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function Ik(e,t,n={}){let r=vm(e,t,{semantic:n.semantic}),i=r.length>0?km(r,"source-attribution"):km(bn(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function km(e,t){return e.map(n=>({...n,provenance:t}))}function Dk(e,t,n){let r=new Map;for(let[i,o]of Pk(e,t.symbolId))r.set(i,Nk(e,i,o,t,n));return r}function Pk(e,t){let n=new Map;for(let r of Lo(e,[t])){if(e.isIgnored(r.relative_path))continue;let i=n.get(r.relative_path);i||(i=[],n.set(r.relative_path,i)),i.push({start_line:r.chunk_start,end_line:r.chunk_end})}return n}function Nk(e,t,n,r,i){let o=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},s=i?wo(e,t,i,o):[];return n.flatMap(a=>Ek(s,a))}function Ek(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function Tk(e,t){let n=ao(e,t);return n?{match:n,identifier:$(n.symbol)||null}:null}function _k(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=z(e,i);for(let a of o){let c=Be(s,a),l=`${i}|${a}|${c?.symbol??""}`;r.has(l)||(r.add(l),n.push({file:i,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function je(e,t,n={}){let r=Ao(e,[t],{additive:n.additive,semantic:n.semantic}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>Ce(o.symbol)):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function Lm(e,t,n={}){let r=Ak(e)?jk(e,t,{semantic:n.semantic!==!1}):Mk(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var Fk=Y("caller-rows",{clearGroups:["whole-project"]}),$k=2e4;function Ak(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>$k}function Mk(e){return Fk.get(e,()=>{let t=ut(e),n=Ao(e,t),r=new Map;for(let s of t)r.set(s.symbol,s.symbolId);let i=new Map,o=new Map;for(let s of t){let a=n.get(s.symbolId);if(!(!a||a.length===0))for(let c of a){let l=r.get(c.symbol);if(l===void 0||l===s.symbolId)continue;let u=i.get(l);u||(u=[],i.set(l,u),o.set(l,new Set));let d=`${s.symbol}|${s.relativePath}`;o.get(l).has(d)||(o.get(l).add(d),u.push({symbol:s.symbol,file:s.relativePath,source:"caller-map-inversion"}))}}return i})}function jk(e,t,n){let r=[],i=new Set,o=a=>{if(a.symbol===t.symbol)return;let c=`${a.symbol}|${a.file}`;i.has(c)||(i.add(c),r.push(a))};for(let a of bn(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?Ok(e,t):null;if(s)for(let a of Jt(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=Be(z(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return r}function Ok(e,t){return e.get(`SELECT
|
|
217
|
+
${e.symbolNoiseFor("gs")}`),n=new Map;for(let i of t){if(!i.relative_path||e.isIgnored(i.relative_path))continue;let r=M(i.symbol);if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.some(s=>s.symbolId===i.id)||o.push({symbol:i.symbol,symbolId:i.id,file:i.relative_path})}return n})}var vm=/[A-Za-z_$][A-Za-z0-9_$]*/g,Gk=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function ur(e){let t=[],n=!1;for(let i of e)i&&(n=!0,Gk.test(i)||t.push(i));return{candidateNames:e,hasUsableCandidate:n,nonIdentifierNames:t}}function Jo(e,t){let n=Jk(t)?t:ur(t);if(n.candidateNames.size===0||!n.hasUsableCandidate)return!0;vm.lastIndex=0;let i;for(;(i=vm.exec(e))!==null;)if(n.candidateNames.has(i[0]))return!0;for(let r of n.nonIdentifierNames)if(e.includes(r))return!0;return!1}function Jk(e){return"candidateNames"in e}import{performance as z}from"perf_hooks";function ut(e,t,n){if(e.has(t))return e.get(t);let i=n();return e.set(t,i),i}import Rm from"path";function Kk(e,t){return e.getReferences().map(n=>{let i=n.getNode();return Ko(i,t)})}function Qk(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function km(e,t,n,i){let r=[];for(let o of Qk(e))for(let s of Kk(o,i))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||r.push(s);for(let o of n)r.push(o);return dr(r)}function wm(e,t,n,i){let r=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();mr(i,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||r.push({location:Ko(a,i),node:a}))}return r}function Ko(e,t){let n=e.getSourceFile(),i=n.getLineAndColumnAtPos(e.getStart());return{file:mr(t,n.getFilePath())??n.getBaseName(),line:i.line-1,column:i.column-1}}function Im(e,t,n){let i=e.getSourceFile(),r=Va(i,e),o=e.getText(),s=new RegExp(`\\b${Xk(o)}\\b`,"g"),a=i.getFullText().split(`
|
|
218
|
+
`),c=[];for(let l=0;l<a.length;l++){if(l===r)continue;let u=a[l]??"";s.lastIndex=0;let d;for(;(d=s.exec(u))!==null;)c.push({file:t,line:l,column:d.index})}return dr(c.filter(l=>mr(n,Rm.join(n,l.file))===t))}function Ha(e){for(let t=e;t;t=t.getParent()){let n=t.getKindName();if(n.includes("Type")||n==="InterfaceDeclaration"||n==="TypeAliasDeclaration")return!0;if(n==="CallExpression"||n==="NewExpression"||n==="ExpressionStatement")return!1}return!1}function Va(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function dr(e){let t=new Set,n=[];for(let i of e){let r=`${i.file}:${i.line}:${i.column}`;t.has(r)||(t.add(r),n.push(i))}return n}function mr(e,t){let n=Rm.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function Xk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Lm(e,t,n,i){let r=Yk(t,i);return r.size===0?new Map:Zk(e,n,r)}function Yk(e,t){let n=new Map;for(let i of Q(e,t)){let r=M(i.symbol)??i.leaf;if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.push(i)}return n}function Zk(e,t,n){let i=new Map,r=new Map;return t.forEachDescendant(o=>{for(let s of ew(e,o)){let a=n.get(s);if(!a)continue;let c=Va(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let u=Math.abs(c-l.startLine),d=r.get(l.symbolId);d!==void 0&&d<=u||(r.set(l.symbolId,u),i.set(l.symbolId,o))}}}),i}function ew(e,t){let n=[],i=r=>{r&&!n.includes(r)&&n.push(r)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let r=t.getNameNode();i(r?.getText())}if("getName"in t&&typeof t.getName=="function"){let r=t.getName();i(r)}return e.Node.isIdentifier(t)&&i(t.getText()),n}var tw=U("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function Pm(e,t,n,i){let r=Em(e,t),o=Dm(r.get(i)??[],n);if(o)return o;let s=[];for(let a of r.values())for(let c of a)((c.leaf||M(c.symbol)||"").includes(i)||c.symbol.includes(i))&&s.push(c);return Dm(s,n)}function Nm(e,t){let n=new Map;for(let[i,r]of Em(e,t)){let o=r[0];o&&n.set(i,o)}return n}function Em(e,t){return tw.get(e,t,()=>{let n=new Map;for(let i of Q(e,t)){let r=i.leaf||M(i.symbol);if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.push({...i,leaf:r})}for(let i of n.values())i.sort((r,o)=>r.startLine-o.startLine||r.endLine-o.endLine||r.symbolId-o.symbolId);return n})}function Dm(e,t){let n=null,i=Number.POSITIVE_INFINITY;for(let r of e){let o=Math.abs(r.startLine-t);(o<i||o===i&&n&&r.startLine<n.startLine)&&(n=r,i=o)}return n}import Ua from"path";var pr=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function Xt(e){let t=e.toLowerCase();return pr.some(n=>t.endsWith(n))}import{appendFileSync as nw,mkdirSync as iw}from"fs";import{dirname as rw}from"path";import{performance as qa}from"perf_hooks";var ow="SCIP_QUERY_PROFILE",sw="SCIP_QUERY_PROFILE_OUT",aw="SCIP_QUERY_PROFILE_COMMAND",Tm=new Set,Fm=!1;function se(){let e=process.env[ow];return e==="1"||e==="true"}function cw(){return process.env[sw]}function lw(){return process.env[aw]}function T(e,t,n){if(!se())return t();let i=qa.now();try{let r=t();return In({type:"span",name:e,durationMs:Math.round(qa.now()-i),ok:!0,..._m(n)??{}}),r}catch(r){throw In({type:"span",name:e,durationMs:Math.round(qa.now()-i),ok:!1,error:r instanceof Error?r.message:String(r),..._m(n)??{}}),r}}function In(e,t=cw()){let n={timestamp:new Date().toISOString(),pid:process.pid,command:lw(),...e},i=`${JSON.stringify(n)}
|
|
219
|
+
`;if(t)try{let r=rw(t);Tm.has(r)||(iw(r,{recursive:!0}),Tm.add(r)),nw(t,i);return}catch(r){Fm||(Fm=!0,process.stderr.write(`[profile] failed to write ${t}: ${r instanceof Error?r.message:String(r)}
|
|
220
|
+
`));return}se()&&process.stderr.write(i)}function _m(e){return typeof e=="function"?e():e}function Am(e,t){let n=new Map,i=null,r=null,o=()=>(r??=B(e,{extensions:pr}),r),s=()=>(i??=T("typescript.source-file-index",()=>uw(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),i),a=c=>Xt(c)?ut(n,c,()=>{let l=fr(Ua.resolve(e.config.projectRoot,c));for(let{project:u,sourceFiles:d}of s()){let m=d.get(l)??null;if(m||(m=u.addSourceFileAtPathIfExists(l)??null,m&&d.set(fr(m.getFilePath()),m)),m)return{project:u,sourceFile:m}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function uw(e,t,n){let i=t.map(({project:r})=>({project:r,sourceFiles:new Map(r.getSourceFiles().map(o=>[fr(o.getFilePath()),o]))}));for(let r of n){let o=fr(Ua.resolve(e,r));for(let s of i){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){s.sourceFiles.set(fr(a.getFilePath()),a);break}}}return i}function fr(e){return Ua.resolve(e)}import Yt from"path";import{existsSync as Qo,readdirSync as dw,readFileSync as $m}from"fs";function Mm(e){let t=Yt.join(e,"package.json");if(!Qo(t))return[];let n;try{n=JSON.parse($m(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(r=>mw(e,r)).flatMap(r=>pw(e,r))}function mw(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=Yt.join(e,t);return Qo(Yt.join(s,"package.json"))?[s]:[]}let n=t.indexOf("*"),i=t.slice(0,n).replace(/\/$/,""),r=t.slice(n+1).replace(/^\//,""),o=Yt.join(e,i||".");if(!Qo(o))return[];try{return dw(o).map(s=>Yt.join(o,s,r)).filter(s=>Qo(Yt.join(s,"package.json")))}catch{return[]}}function pw(e,t){try{let n=JSON.parse($m(Yt.join(t,"package.json"),"utf8"));if(!n.name)return[];let i=Yt.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:i,sourceRootRelative:`${i}/src`}]}catch{return[]}}function Om(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function jm(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as gr,readFileSync as fw,readdirSync as gw,statSync as hw}from"fs";import ge from"path";var za=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Ga(e,t){let i=t?ge.dirname(ge.join(e,t)):e,r=ge.resolve(e);for(;i.startsWith(r);){for(let s of za){let a=ge.join(i,s);if(gr(a))return a}let o=ge.dirname(i);if(o===i)break;i=o}for(let o of za){let s=ge.join(e,o);if(gr(s))return s}return null}function Bm(e){let t=e.config.projectRoot,n=new Set(Ja(t,e.config.semantic?.typescript?.tsconfigs)),i=B(e,{includeIgnored:!1,extensions:pr});for(let r of i){let o=Ga(t,r);o&&n.add(ge.resolve(o))}if(n.size===0){let r=Ga(t);r&&n.add(ge.resolve(r))}return[...n].filter(r=>!Hm(t,r)).sort((r,o)=>r.localeCompare(o))}function Ja(e,t=[]){let n=new Set;for(let i of t){let r=ge.isAbsolute(i)?i:ge.join(e,i);gr(r)&&n.add(ge.resolve(r))}for(let i of yw(e))for(let r of za){let o=ge.join(i,r);gr(o)&&n.add(ge.resolve(o))}if(n.size===0){let i=Ga(e);i&&n.add(ge.resolve(i))}return[...n].filter(i=>!Hm(e,i)).sort((i,r)=>i.localeCompare(r))}function yw(e){let t=ge.join(e,"package.json");if(!gr(t))return[];let n;try{n=JSON.parse(fw(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(r=>bw(e,r))}function bw(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=ge.join(e,t);return Wa(s)?[s]:[]}let n=t.indexOf("*"),i=t.slice(0,n).replace(/\/$/,""),r=t.slice(n+1).replace(/^\//,""),o=ge.join(e,i||".");return Wa(o)?gw(o).map(s=>ge.join(o,s,r)).filter(Wa):[]}function Wa(e){try{return hw(e).isDirectory()}catch{return!1}}function Hm(e,t){let n=ge.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}import{createRequire as Sw}from"module";var xw=Sw(import.meta.url),hr;function Vm(){if(hr!==void 0)return hr;try{hr=xw("ts-morph")}catch{hr=null}return hr}function qm(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!0})}))}function Xo(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}var Cw=32;function Km(e,t){let n=T("typescript.provider.load",()=>Vm());if(!n)return Xo("ts-morph is not installed");let i=T("typescript.provider.tsconfig-discovery",()=>Bm(e));if(i.length===0)return Xo("no tsconfig found");try{let r=T("typescript.provider.project-bundles",()=>qm(n,i),()=>({tsconfigs:i.length}));return T("typescript.provider.construct",()=>new Ka(e,n,r),()=>({tsconfigs:i.length}))}catch(r){return Xo(r instanceof Error?r.message:String(r),i[0],i)}}var Ka=class{constructor(t,n,i){this.db=t;this.tsMorph=n;this.projects=i;this.workspacePackages=Mm(t.config.projectRoot),this.sourceFiles=Am(t,i)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return ut(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let i=Rw();return T("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,i),()=>({file:t,...i}))})}referencesFor(t){return ut(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t){let n=new Map,i=se(),r=[];for(let c of t){let l=this.referencesCache.get(c.symbolId);l?n.set(c.symbolId,l):r.push(c)}if(r.length===0)return n;let o=r,s=r.filter(c=>!Wm(c));if(s.length>=Cw){let c=this.referencesForDefinitionsBySymbolScan(s);for(let l of s){let u=c.get(l.symbolId)??[];this.referencesCache.set(l.symbolId,u),n.set(l.symbolId,u)}if(o=r.filter(l=>Wm(l)),o.length===0)return n}let a=new Map;for(let c of o){let l=a.get(c.relativePath);l?l.push(c):a.set(c.relativePath,[c])}for(let[c,l]of a){let u=zm();T("typescript.references-map.file",()=>{let d=this.definitionNodesForFile(c);for(let m of l){i&&(u.cacheMisses+=1);let p=d.get(m.symbolId)??null;i&&(p?u.nodeHits+=1:u.nodeMisses+=1);let f=this.referencesForDefinitionNode(m,p,i?u:void 0);this.referencesCache.set(m.symbolId,f),n.set(m.symbolId,f)}},()=>({relativePath:c,definitions:l.length,...Gm(u)}))}return n}referencesForDefinitionsBySymbolScan(t){let n=se(),i=zm(),r=new Map,o=new Set(t.map(a=>a.symbolId)),s=new Map(t.map(a=>[a.symbolId,a]));for(let a of t)r.set(a.symbolId,[]);return T("typescript.references-map.inverted-scan",()=>{let a=n?z.now():0;for(let d of t){let m=this.packageImportReferencesForDefinition(d);if(m.length>0){let p=r.get(d.symbolId)??[];p.push(...m),r.set(d.symbolId,p)}n&&(i.packageReferenceCount+=m.length)}n&&(i.packageRefsMs+=z.now()-a);let c=new Map,l=new Set(t.map(d=>d.leaf).filter(Boolean)),u=n?z.now():0;for(let d of this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(d))continue;let m=this.sourceFiles.sourceFile(d);m&&(n&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(m,d,o,s,l,c,r,n?i:void 0))}n&&(i.scanMs+=z.now()-u);for(let[d,m]of r){let p=dr(m);r.set(d,p),n&&(i.referenceCount+=p.length)}},()=>({definitions:t.length,...Gm(i)})),r}addReferencesFromSourceFileScan(t,n,i,r,o,s,a,c){let l=this.compilerCheckerForSourceFile(t),u=t.compilerNode,d=Iw(t),m=p=>{if(this.tsMorph.ts.isIdentifier(p)){if(c&&(c.identifiers+=1),!o.has(p.text)&&!d.has(p.text)){this.tsMorph.ts.forEachChild(p,m);return}let f=this.compilerReferenceSymbol(l,p,c);if(f){let g;if(s.has(f)?g=s.get(f)??null:(g=this.definitionFromCompilerSymbol(f),s.set(f,g)),c&&(g?c.targetHits+=1:c.targetMisses+=1),g&&i.has(g.symbolId)){c&&(c.requestedHits+=1);let y=r.get(g.symbolId);if(y&&!Dw(y,n,Um(u,p))){let S=a.get(g.symbolId)??[],R=u.getLineAndCharacterOfPosition(p.getStart(u));S.push({file:n,line:R.line,column:R.character}),a.set(g.symbolId,S)}}}}this.tsMorph.ts.forEachChild(p,m)};m(u)}compilerReferenceSymbol(t,n,i){i&&(i.symbolLookups+=1);let r=t.getSymbolAtLocation(n);if(r){if((r.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return r;try{return i&&(i.aliasResolutions+=1),t.getAliasedSymbol(r)}catch{return r}}}calleesFor(t){return ut(this.calleesCache,t.symbolId,()=>ut(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}calleesForDefinitions(t){let n=new Map,i=new Map;for(let r of t){let o=i.get(r.relativePath);o?o.push(r):i.set(r.relativePath,[r])}for(let[r,o]of i){let s=this.fileCalleesCache.get(r),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(r,a);for(let l of o){let u=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,u),n.set(l.symbolId,u)}}return n}referencesForDefinitionNode(t,n,i){let r=i?z.now():0,o=this.packageImportReferencesForDefinition(t);if(i&&(i.packageRefsMs+=z.now()-r,i.packageReferenceCount+=o.length),!n)return o;let s=i?z.now():0,a=km(n,t,o,this.db.config.projectRoot);return i&&(i.semanticRefsMs+=z.now()-s,i.referenceCount+=a.length),a}signatureFor(t){return ut(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let i=n.getType().getCallSignatures()[0];if(!i)return null;let r=i.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return Jm(c)}),o=i.getReturnType().getText(n);return`(${r.join(",")})=>${Jm(o)}`})}importUsageForSourceFile(t,n,i){let r=[],o=new Map;for(let s of n.getImportDeclarations()){i.declarations+=1;let a=lt(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of Qa(s)){i.entries+=1;let u=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(u?i.bindingSymbols+=1:i.missingBindingSymbols+=1);let d={sourcePath:a,entry:l,typeOnlyDeclaration:c,bindingSymbol:u,references:[]};if(r.push(d),c||!l.localName||!u)continue;let m=o.get(l.localName);m?m.push(d):o.set(l.localName,[d])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||kw(s))return;i.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(i.symbolLookups+=1,!!c){for(let l of a)if(l.bindingSymbol===c){l.references.push({location:Ko(s,this.db.config.projectRoot),node:s}),i.matchedReferences+=1;break}}}),r.map(s=>s.typeOnlyDeclaration?vw(t,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(i.fallbackEntries+=1,this.valueImportUsageForEntry(t,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(t,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(t,n,i){let r=i.identifier?i.identifier.findReferences():[],o=[];for(let s of r)for(let a of wm(s,t,i.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(t,n,i,o)}valueImportUsageFromLocations(t,n,i,r){let o=r.some(c=>!Ha(c.node)),s=r.some(c=>Ha(c.node)),a=i.isTypeOnly;return{importer:t,sourcePath:n,importedName:i.importedName,localName:i.localName,kind:i.kind,isTypeOnly:a,isUsed:a||r.length>0,isTypeUsed:a||s,isValueUsed:o,references:r.map(c=>c.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let i of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,i);for(let[i,r]of t)t.set(i,dr(r));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,i){if(this.db.isIgnored(i))return;let r=this.sourceFiles.sourceFileMatch(i);if(r)for(let o of r.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,i,o)}addPackageImportReferencesForDeclaration(t,n,i,r){let o=Om(this.workspacePackages,r.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of Qa(r)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=Im(a.identifier,i,this.db.config.projectRoot);l.length>0&&Ew(t,c,l)}}packageExports(){if(this.packageExportIndex)return this.packageExportIndex;let t=new Map;for(let n of this.workspacePackages){let i=new Map;for(let r of jm(n))this.collectPackageExports(n,r,i,new Set);i.size>0&&t.set(n.name,i)}return this.packageExportIndex=t,t}collectPackageExports(t,n,i,r){if(r.has(n))return;r.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?lt(this.db,n,a):n;if(!c||!c.startsWith(`${t.sourceRootRelative}/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,c,i,r);continue}for(let u of l){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,p=this.indexedDefinitionByLeaf(c,d);if(!p)continue;let f=i.get(m);f||(f=new Set,i.set(m,f)),f.add(p.symbolId)}}}indexedDefinitionByLeaf(t,n){return ut(this.indexedDefinitionLeafCache,t,()=>Nm(this.db,t)).get(n)??null}nodeForDefinition(t){return ut(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return ut(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?Lm(this.tsMorph,this.db,n,t):new Map})}definitionFromCompilerSymbol(t,n){let i=t.name,r=n?z.now():0,o=t.declarations??[];n&&(n.declarationsMs+=z.now()-r,n.declarationChecks+=o.length);for(let s of o){let a=n?z.now():0,c=s.getSourceFile(),l=mr(this.db.config.projectRoot,c.fileName),u=c.getLineAndCharacterOfPosition(s.getStart(c)).line;if(n&&(n.declarationLocationMs+=z.now()-a),!l||this.db.isIgnored(l))continue;let d=n?z.now():0,m=Pm(this.db,l,u,i);if(n&&(n.indexedLookupMs+=z.now()-d),m)return{symbolId:m.symbolId,symbol:m.symbol,file:m.relativePath,line:m.startLine}}return null}calleeMapForFile(t,n){let i=se(),r=0,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=i?Pw():void 0;return T("typescript.callee-map.file",()=>{let p=i?z.now():0,f=this.sourceFiles.sourceFile(t);if(i&&(c=Math.round(z.now()-p)),!f)return new Map;let g=i?z.now():0,y=Q(this.db,t).sort((w,j)=>w.startLine-j.startLine||j.endLine-w.endLine);if(i&&(l=Math.round(z.now()-g)),r=y.length,y.length===0)return new Map;let S=new Map,R=i?z.now():0,k=this.compilerCheckerForSourceFile(f),x=f.compilerNode;i&&(u=Math.round(z.now()-R));let b=new Map,C=w=>{if(this.tsMorph.ts.isCallExpression(w)||this.tsMorph.ts.isNewExpression(w)){i&&(o+=1);let j=this.semanticCalleeForCallNode(k,x,y,w,b,n,m);j&&(i&&(s+=1),ww(S,j.callerId,j.target))}this.tsMorph.ts.forEachChild(w,C)},D=i?z.now():0;C(x),i&&(d=Math.round(z.now()-D));for(let[w,j]of S)S.set(w,Tw(j));return a=S.size,S},()=>({relativePath:t,definitions:r,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??r,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:u,traversalMs:d,...m?Nw(m):{}}))}semanticCalleeForCallNode(t,n,i,r,o,s,a){let c=a?z.now():0,l=Lw(i,Um(n,r));if(a&&(a.callerLookupMs+=z.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let u=r.expression,d=this.compilerSymbolForExpression(t,u,a),m=null;if(d)if(a&&(a.targetSymbolHits+=1),o.has(d))a&&(a.compilerSymbolCacheHits+=1),m=o.get(d)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let p=a?z.now():0;m=this.definitionFromCompilerSymbol(d,a),a&&(a.targetLookupMs+=z.now()-p),o.set(d,m)}else a&&(a.targetMisses+=1);return m?{callerId:l.symbolId,target:{symbol:m.symbol,file:m.file,line:m.line}}:null}compilerSymbolForExpression(t,n,i){let r=i?z.now():0,o=t.getSymbolAtLocation(n);if(i&&(i.expressionSymbolMs+=z.now()-r),o)return o;i&&(i.typeFallbacks+=1);let s=i?z.now():0,a=t.getTypeAtLocation(n).getSymbol();return i&&(i.typeSymbolMs+=z.now()-s),a}compilerCheckerForSourceFile(t){let n=t.getProject(),i=this.compilerCheckerCache.get(n);return i||(i=n.getTypeChecker().compilerObject,this.compilerCheckerCache.set(n,i)),i}};function Qa(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let i=e.getNamespaceImport();i&&t.push({identifier:i,importedName:"*",localName:i.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let r of e.getNamedImports()){let o=r.getNameNode(),a=r.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:r.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function vw(e,t,n){return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function Rw(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function kw(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function ww(e,t,n){let i=e.get(t);i||(i=[],e.set(t,i)),i.push(n)}function Iw(e){let t=new Set;for(let n of e.getImportDeclarations())for(let i of Qa(n))i.localName&&t.add(i.localName);return t}function Lw(e,t){let n=null;for(let i of e)t<i.startLine||t>i.endLine||(!n||i.startLine>=n.startLine)&&(n=i);return n}function Um(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function Dw(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function Wm(e){return e.symbol.includes("#")?ee(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function Pw(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function Nw(e){return{...e,callerLookupMs:Math.round(e.callerLookupMs),expressionSymbolMs:Math.round(e.expressionSymbolMs),typeSymbolMs:Math.round(e.typeSymbolMs),targetLookupMs:Math.round(e.targetLookupMs),declarationsMs:Math.round(e.declarationsMs),declarationLocationMs:Math.round(e.declarationLocationMs),indexedLookupMs:Math.round(e.indexedLookupMs)}}function zm(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0}}function Gm(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs)}}function Ew(e,t,n){for(let i of t){let r=e.get(i)??[];r.push(...n),e.set(i,r)}}function Tw(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.file}|${i.line}`;t.has(r)||(t.add(r),n.push(i))}return n}function Jm(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Xa=new WeakMap;Vt({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>Xa.delete(e)});function Zt(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,i=Xa.get(e);i||(i=new Map,Xa.set(e,i));let r=i.get(n);if(r)return r;let o=Km(e,t);return i.set(n,o),o}function yr(e,t){let n=br(e,t);return n?n.importUsage(t):[]}function Ii(e,t){let n=br(e,t.relativePath);return n?n.referencesFor(t):[]}function et(e,t){let n=se(),i=new Map,r=er(e),o=[],s=[],a=[],c=0,l=0,u=0,d=0;if(T("semantic.references.cache-scan",()=>{for(let m of t){if(!r||!Xt(m.relativePath)){n&&!Xt(m.relativePath)&&(c+=1),a.push(m);continue}let p=Mu(e,m.relativePath,m.symbol,r);if(p!==null){let f=_w(p);if(f){n&&(l+=1),d+=Xm(e,i,m,f);continue}n&&(u+=1)}s.push(m)}},()=>({definitions:t.length,skippedNonTs:c,cacheHits:l,parseFailures:u,misses:s.length,unkeyed:a.length,resultRows:i.size,callerFiles:d})),s.length>0||a.length>0){let m=[...a,...s],p=0,f=T("semantic.references.compute-misses",()=>{let g=Fw(e,m);return p=g.size,g},()=>({definitions:m.length,misses:s.length,unkeyed:a.length,rows:p}));for(let g of m)d+=Xm(e,i,g,f.get(g.symbolId)??[]);if(r)for(let g of s)o.push({relativePath:g.relativePath,symbol:g.symbol,projectFingerprint:r,payload:JSON.stringify(f.get(g.symbolId)??[])})}return o.length>0&&(Zt(e).availability().available?T("semantic.references.cache-write",()=>ju(e,o),()=>({entries:o.length})):T("semantic.references.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",entries:o.length}))),i}function Fw(e,t){let n=se(),i=new Map,r=0,o=0,s=0,a=0;return T("semantic.references.provider-loop",()=>{let c=new Map,l=[];for(let u of t){let d=br(e,u.relativePath);if(!d){n&&(o+=1);continue}if(n&&(r+=1),d.referencesForDefinitions){let m=c.get(d);m?m.push(u):c.set(d,[u])}else l.push({provider:d,definition:u})}for(let[u,d]of c){let m=u.referencesForDefinitions(d);for(let p of d){let f=m.get(p.symbolId)??[];Qm(i,p.symbolId,f,n,g=>{s+=1,a+=g})}}for(let{provider:u,definition:d}of l){let m=u.referencesFor(d);Qm(i,d.symbolId,m,n,p=>{s+=1,a+=p})}return i},()=>({definitions:t.length,providerHits:r,providerMisses:o,definitionsWithReferences:s,referenceCount:a,rows:i.size}))}function Qm(e,t,n,i,r){e.set(t,n),i&&n.length>0&&r(n.length)}function Xm(e,t,n,i){let r=0;for(let o of i){if(o.file===n.relativePath||e.isIgnored(o.file))continue;let s=t.get(n.symbolId);s||(s=new Set,t.set(n.symbolId,s));let a=s.size;s.add(o.file),s.size!==a&&(r+=1)}return r}function _w(e){try{return JSON.parse(e)}catch{return null}}function Yo(e,t){let n=se(),i=new Map,r=0,o=0,s=0,a=0;return T("semantic.callees.provider-loop",()=>{let c=new Map,l=[];for(let u of t){let d=br(e,u.relativePath);if(!d){n&&(o+=1);continue}n&&(r+=1);let m=u;if(d.calleesForDefinitions){let p=c.get(d);p?p.push(m):c.set(d,[m])}else l.push({provider:d,definition:m})}for(let[u,d]of c){let m=u.calleesForDefinitions(d);for(let p of d){let f=m.get(p.symbolId)??[];Ym(i,p.symbolId,f,n,g=>{s+=1,a+=g})}}for(let{provider:u,definition:d}of l){let m=u.calleesFor(d);Ym(i,d.symbolId,m,n,p=>{s+=1,a+=p})}return i},()=>({definitions:t.length,providerHits:r,providerMisses:o,definitionsWithCallees:s,calleeCount:a,rows:i.size}))}function Ym(e,t,n,i,r){n.length>0&&(e.set(t,n),i&&r(n.length))}function Zm(e,t){let n=br(e,t.relativePath);return n?n.signatureFor(t):null}function br(e,t){if(!Xt(t))return null;let n=Zt(e,t);return n.availability().available?n:null}var Aw=U("source-import-paths-by-local-name",{clearGroups:["whole-project","source-file"]});function Zo(e,t){let n=Wo(t);return Aw.get(e,n,()=>$w(e,n))}function $w(e,t){let n=new Map;for(let i of Ie(e,t)){if(!i.sourcePath)continue;let r=i.localName??i.importedName;if(r&&ep(n,r,i.sourcePath),i.kind==="namespace")for(let o of i.usedMembers)ep(n,o,i.sourcePath)}return n}function ep(e,t,n){let i=e.get(t);i||(i=new Set,e.set(t,i)),i.add(n)}function Li(e,t,n){let i=wn(e).get(n);if(!i||i.length===0)return[];if(i.length===1)return[Sr(i[0])];let r=i.filter(c=>c.file===t);if(r.length>0)return r.map(Sr);let o=Zo(e,t),s=o.get(n);if(s)for(let c of s){let l=i.filter(u=>Qt(c,u.file));if(l.length>0)return l.map(Sr)}let a=new Set;for(let c of o.values())for(let l of c)a.add(l);for(let c of a){let l=i.filter(u=>Qt(c,u.file));if(l.length>0&&l.length===i.length)return l.map(Sr)}return[]}function np(e,t,n){let i=Li(e,t,n);if(i.length>0)return i;let r=wn(e).get(n);return!r||r.length===0?[]:r.map(Sr)}function ip(e,t,n={}){let i=Lo(e,t);if(!i)return[];let r=M(i.symbol);if(!r)return[];if(n.semantic!==!1){let s=Ii(e,{...i,leaf:r,parentTypeName:null,isFunctionLike:!1,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:null});if(s.length>0){let a=new Map;for(let c of s){let l=a.get(c.file)??[];l.push(c.line),a.set(c.file,l)}return tp(e,a)}}let o=new Map;for(let s of $e(e)){let a=F(e,s);if(!a||a.indexOf(r)===-1||s!==i.relativePath&&!Li(e,s,r).some(u=>u.symbolId===i.symbolId))continue;let c=Uo(e,s,r,s===i.relativePath?{excludeStartLine:i.startLine,excludeEndLine:i.endLine}:{});c.length>0&&o.set(s,c)}return tp(e,o)}function rp(e,t){let n=new Map;for(let a of t){if(!a.leaf)continue;let c=n.get(a.leaf)??[];c.push(a),n.set(a.leaf,c)}if(n.size===0)return new Map;let i=new Set(t.map(a=>a.symbolId)),r=new Set(n.keys()),o=ur(r),s=new Map;for(let a of $e(e)){if(!Jo(F(e,a),o))continue;let c=ym(e,a);if(c.size!==0){for(let l of c)if(n.has(l))for(let u of Li(e,a,l)){if(!i.has(u.symbolId)||a===u.relativePath)continue;let d=s.get(u.symbolId);d||(d=new Set,s.set(u.symbolId,d)),d.add(a)}}}return s}function Sr(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function tp(e,t){let n=[],i=new Set;for(let[r,o]of t){let s=Q(e,r);for(let a of o){let c=Qe(s,a),l=`${r}|${a}|${c?.symbol??""}`;i.has(l)||(i.add(l),n.push({file:r,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function Ln(e,t){let n=Vw(e,t);return n?qw(e,Ow(e,n.match,n.identifier)):[]}function en(e,t,n={}){return Mw(e,t,n).map(i=>({file:i.file,line:i.line,enclosingSymbol:i.enclosingSymbol}))}function Mw(e,t,n={}){let i=ip(e,t,{semantic:n.semantic}),r=i.length>0?op(i,"source-attribution"):op(Ln(e,t),"scip-reference-chunk");return n.includeIgnored===!0?r:r.filter(o=>!e.isIgnored(o.file))}function op(e,t){return e.map(n=>({...n,provenance:t}))}function Ow(e,t,n){let i=new Map;for(let[r,o]of jw(e,t.symbolId))i.set(r,Bw(e,r,o,t,n));return i}function jw(e,t){let n=new Map;for(let i of wi(e,[t])){if(e.isIgnored(i.relative_path))continue;let r=n.get(i.relative_path);r||(r=[],n.set(i.relative_path,r)),r.push({start_line:i.chunk_start,end_line:i.chunk_end})}return n}function Bw(e,t,n,i,r){let o=t===i.relativePath?{excludeStartLine:i.startLine,excludeEndLine:i.endLine}:{},s=r?Uo(e,t,r,o):[];return n.flatMap(a=>Hw(s,a))}function Hw(e,t){let n=e.filter(i=>i>=t.start_line&&i<=t.end_line);return n.length>0?n:[t.start_line]}function Vw(e,t){let n=Lo(e,t);return n?{match:n,identifier:M(n.symbol)||null}:null}function qw(e,t){let n=[],i=new Set;for(let[r,o]of t){let s=Q(e,r);for(let a of o){let c=Qe(s,a),l=`${r}|${a}|${c?.symbol??""}`;i.has(l)||(i.add(l),n.push({file:r,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function Ge(e,t,n={}){let i=es(e,[t],{additive:n.additive,semantic:n.semantic}),r=n.callableOnly?(i.get(t.symbolId)??[]).filter(o=>le(o.symbol)):i.get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}function ap(e,t,n={}){let i=zw(e)?Jw(e,t,{semantic:n.semantic!==!1}):Gw(e).get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}var Uw=re("caller-rows",{clearGroups:["whole-project"]}),Ww=2e4;function zw(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>Ww}function Gw(e){return Uw.get(e,()=>{let t=bt(e),n=es(e,t),i=new Map;for(let s of t)i.set(s.symbol,s.symbolId);let r=new Map,o=new Map;for(let s of t){let a=n.get(s.symbolId);if(!(!a||a.length===0))for(let c of a){let l=i.get(c.symbol);if(l===void 0||l===s.symbolId)continue;let u=r.get(l);u||(u=[],r.set(l,u),o.set(l,new Set));let d=`${s.symbol}|${s.relativePath}`;o.get(l).has(d)||(o.get(l).add(d),u.push({symbol:s.symbol,file:s.relativePath,source:"caller-map-inversion"}))}}return r})}function Jw(e,t,n){let i=[],r=new Set,o=a=>{if(a.symbol===t.symbol)return;let c=`${a.symbol}|${a.file}`;r.has(c)||(r.add(c),i.push(a))};for(let a of Ln(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?Kw(e,t):null;if(s)for(let a of Ii(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=Qe(Q(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return i}function Kw(e,t){return e.get(`SELECT
|
|
170
221
|
d.id AS documentId,
|
|
171
222
|
gs.id AS symbolId,
|
|
172
223
|
gs.symbol,
|
|
@@ -185,11 +236,11 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
185
236
|
LEFT JOIN chunks c ON c.document_id = der.document_id
|
|
186
237
|
JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
|
|
187
238
|
WHERE gs.id = ?
|
|
188
|
-
LIMIT 1`,t.symbolId)??null}function
|
|
239
|
+
LIMIT 1`,t.symbolId)??null}function es(e,t,n={}){if(t.length===0)return new Map;let i=n.additive??!1,r=[],o=[];for(let u of t)K(u.relativePath)&&si(e,u.relativePath)!==null?r.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[d,m]of u){let p=s.get(d);p||(p=[],s.set(d,p));let f=a.get(d);f||(f=new Set,a.set(d,f));for(let g of m){let y=`${g.symbol}|${g.chunkId}`;f.has(y)||(f.add(y),p.push(g))}}};r.length>0&&c(eI(e,r)),n.semantic!==!1&&c(rI(Qw(e,t)));let l=i?t:o;return l.length>0&&c(iI(e,l)),s}function Qw(e,t){let n=se(),i=new Map,r=[],o=[],s=0,a=0,c=0,l=0;if(T("semantic.callees.cache-scan",()=>{for(let f of t){if(!Xt(f.relativePath)){n&&(s+=1);continue}let g=F(e,f.relativePath);if(!g){n&&(a+=1),o.push(f);continue}let y=Z(e,f.relativePath,g),S=Zw(e,f.relativePath),R=$u(e,f.relativePath,f.symbol,y,S);if(R!==null){let k=Xw(R);if(k){n&&(c+=1),k.length>0&&i.set(f.symbolId,k);continue}n&&(l+=1)}r.push({def:f,contentHash:y,depsDigest:S})}},()=>({definitions:t.length,skippedNonTs:s,sourceMissing:a,cacheHits:c,parseFailures:l,misses:r.length,unkeyed:o.length,resultRows:i.size})),r.length===0&&o.length===0)return i;let u=[...o,...r.map(f=>f.def)],d=0,m=T("semantic.callees.compute-misses",()=>{let f=Yo(e,u);return d=f.size,f},()=>({definitions:u.length,misses:r.length,unkeyed:o.length,rows:d}));for(let[f,g]of m)i.set(f,g);if(Zt(e).availability().available){let f=r.map(g=>({relativePath:g.def.relativePath,symbol:g.def.symbol,contentHash:g.contentHash,depsDigest:g.depsDigest,payload:JSON.stringify(m.get(g.def.symbolId)??[])}));T("semantic.callees.cache-write",()=>Ou(e,f),()=>({entries:f.length}))}else T("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:r.length}));return i}function Xw(e){try{return JSON.parse(e)}catch{return null}}var Yw=U("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function Zw(e,t){return Yw.get(e,t,()=>{let i=[...pe(e).get(t)??[]].sort().map(r=>`${r}:${Z(e,r,F(e,r))}`);return ii(i.join("|"))})}function eI(e,t){let n=new Map,i=tI(t,n),r=wn(e);for(let[o,s]of i){let a=si(e,o);if(!a)continue;let c=ka(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=nI(e,o,r,l.calleeLeaf,l.memberAccess);d&&d.symbol!==u.symbol&&n.get(u.symbolId).push({symbol:d.symbol,file:d.file,chunkId:l.line,source:"ast-callsite"})}}return n}function tI(e,t){let n=new Map;for(let i of e){let r=n.get(i.relativePath);r?r.push(i):n.set(i.relativePath,[i]),t.set(i.symbolId,[])}for(let i of n.values())i.sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine));return n}function nI(e,t,n,i,r){let o=zo(t,n.get(i)??[]);return o.length===0?null:Go(e,t,o,r)}function iI(e,t){if(t.length===0)return new Map;let i=Ya(t.map(m=>m.documentId)).flatMap(m=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
|
|
189
240
|
FROM mentions m
|
|
190
241
|
JOIN chunks c ON m.chunk_id = c.id
|
|
191
242
|
WHERE m.role != 1
|
|
192
|
-
AND c.document_id IN (${m.map(()=>"?").join(",")})`,...m)),
|
|
243
|
+
AND c.document_id IN (${m.map(()=>"?").join(",")})`,...m)),r=new Map;for(let m of i)r.has(m.document_id)||r.set(m.document_id,[]),r.get(m.document_id).push(m);let s=Ya(i.map(m=>m.symbol_id)).flatMap(m=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
|
|
193
244
|
COALESCE(der.document_id, def_chunk.document_id) AS document_id
|
|
194
245
|
FROM global_symbols gs
|
|
195
246
|
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
@@ -201,11 +252,11 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
201
252
|
AND m.symbol_id IN (${m.map(()=>"?").join(",")})
|
|
202
253
|
GROUP BY m.symbol_id
|
|
203
254
|
) def_chunk ON def_chunk.symbol_id = gs.id
|
|
204
|
-
WHERE gs.id IN (${m.map(()=>"?").join(",")})`,...m,...m)),a=
|
|
205
|
-
WHERE id IN (${m.map(()=>"?").join(",")})`,...m).map(
|
|
206
|
-
`);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&
|
|
207
|
-
`).slice(n,
|
|
208
|
-
`).trimEnd();return s.length>0?s:null}function
|
|
255
|
+
WHERE gs.id IN (${m.map(()=>"?").join(",")})`,...m,...m)),a=Ya([...t.map(m=>m.documentId),...s.flatMap(m=>m.document_id===null?[]:[m.document_id])]),c=new Map(a.flatMap(m=>e.all(`SELECT id, relative_path FROM documents
|
|
256
|
+
WHERE id IN (${m.map(()=>"?").join(",")})`,...m).map(p=>[p.id,p.relative_path]))),l=new Map;for(let m of s)l.has(m.symbol_id)||l.set(m.symbol_id,{symbol:m.symbol,file:m.document_id!==null?c.get(m.document_id)??"":""});let u=new Map,d=c;for(let m of t){let p=r.get(m.documentId)??[],f=new Set,g=[],y=null,S=()=>{if(y)return y;let R=d.get(m.documentId)??"",k=new Set;if(R){let x=bm(e,R),b=Math.max(0,m.startLine),C=Math.min(x.length-1,m.endLine);for(let D=b;D<=C;D+=1)for(let w of x[D])k.add(w)}return y=k,k};for(let R of p){if(R.symbol_id===m.symbolId)continue;let k=l.get(R.symbol_id);if(!k)continue;if(!(R.start_line>=m.startLine&&R.end_line<=m.endLine)){if(!(R.start_line<=m.endLine&&R.end_line>=m.startLine))continue;let D=M(k.symbol);if(!D||!S().has(D))continue}let b=`${k.symbol}|${R.chunk_id}`;f.has(b)||(f.add(b),g.push({...k,chunkId:R.chunk_id,source:"scip-chunk"}))}u.set(m.symbolId,g)}return u}var sp=500;function Ya(e){let t=[...new Set(e)],n=[];for(let i=0;i<t.length;i+=sp)n.push(t.slice(i,i+sp));return n}function rI(e){let t=new Map;for(let[n,i]of e){let r=[];for(let o of i)r.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee"});t.set(n,r)}return t}function cp(e,t,n={}){let i=new Map;if(t&&t.length===0)return i;let r=B(e,{includeIgnored:!1}),o=wn(e),s=t??bt(e),a=new Set(s.map(l=>l.symbolId)),c=dI(s);return oI(e,i,r,o,a,c),sI(e,i,s,a),uI(e,i,r,o,a,c),n.semantic!==!1&&pI(i,et(e,mI(s))),i}function oI(e,t,n,i,r,o){for(let s of n){if(!K(s))continue;let a=si(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=zo(s,i.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let u=Go(e,s,l,c.memberAccess);u&&r.has(u.symbolId)&&u.file!==s&&Za(t,u.symbolId,s)}}}function sI(e,t,n,i){let r=cI(n);for(let o of aI(e,i))e.isIgnored(o.relative_path)||lI(o,r.get(o.symbol_id))||Za(t,o.symbol_id,o.relative_path)}function aI(e,t){return wi(e,t?[...t]:void 0)}function cI(e){let t=new Map;for(let n of e)t.set(n.symbolId,{docId:n.documentId,startLine:n.startLine,endLine:n.endLine});return t}function lI(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function uI(e,t,n,i,r,o){for(let s of n){if(K(s)!=="rust")continue;let a=fn(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a){if(o&&!o.has(c))continue;let l=i.get(c);if(l)for(let u of l)r.has(u.symbolId)&&u.file!==s&&Za(t,u.symbolId,s)}}}function Za(e,t,n){let i=e.get(t);i||(i=new Set,e.set(t,i)),i.add(n)}function dI(e){let t=new Set;for(let n of e){let i="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?M(n.symbol):"";i&&t.add(i)}return t.size>0?t:null}function mI(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function pI(e,t){for(let[n,i]of t){let r=e.get(n);r||(r=new Set,e.set(n,r));for(let o of i)r.add(o)}}function tt(e,t,n={}){return ap(e,t,n)}function ec(e,t,n={}){return cp(e,t,n)}function tc(e,t){return rp(e,t)}function lp(e,t,n={}){let i=ec(e,t,{semantic:n.semantic});return n.sourceFallback===!1?i:Dn(i,tc(e,t))}function Dn(e,t){let n=new Map;for(let[i,r]of e)n.set(i,new Set(r));for(let[i,r]of t){let o=n.get(i)??new Set;for(let s of r)o.add(s);n.set(i,o)}return n}function up(e,t,n){let i=t.identifierResolution==="strict"?Li:np,r=t.candidateNames?ur(t.candidateNames):null;for(let o of t.paths)if(!(!K(o)&&!(t.includeVueSfc&&Nt(o)))&&!e.isIgnored(o)&&!t.skipPath?.(o))try{if(r&&!Jo(F(e,o),r))continue;let a=(l,u,d,m)=>{if(t.candidateNames&&!t.candidateNames.has(l))return;let p=t.resolveTargets?t.resolveTargets({sourceFile:o,name:l,kind:u,defaultTargets:m}):m();for(let f of p)n({sourceFile:o,name:l,target:f,occurrences:d,kind:u})},c=_t(e,o);for(let[l,u]of c)a(l,"identifier",u.length,()=>i(e,o,l));for(let l of fn(e,o,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let u=l.kind==="cross-language-dispatch"?()=>Li(e,o,l.name):()=>i(e,o,l.name);a(l.name,l.kind,l.occurrences,u)}}finally{t.afterPath?.(o)}}function G(e){return e.endLine-e.startLine+1}function dp(e,t={}){let{scope:n,files:i,minLoc:r=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:l=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:p=!1,sortByLocDesc:f=!1}=t,g=[],y=fI(e,{scope:n,files:i,requireCallableSymbol:d}),S=new Map,R=new Map,k=b=>{let C=S.get(b);if(C!==void 0)return C;let D=Oe(e,b);return S.set(b,D),D},x=b=>{let C=R.get(b);if(C!==void 0)return C;let D=X(b);return R.set(b,D),D};for(let b of y){let C=b.relativePath;if(e.isIgnored(C)||a&&k(C)||!gI(b,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&b.symbol===s)continue;let D=G(b);D<r||D>o||c&&hI(C)||l&&fe(e,b.symbol,C)||m&&Ro(b.symbol)||x(C)!=="test"&&(di(b.symbol)||!p&&mo(e,C,b.startLine)||g.push(b))}return f?g.sort((b,C)=>G(C)-G(b)):g}function fI(e,t){return t.files!==void 0?[...new Set(t.files.map(i=>i.replace(/\\/g,"/")))].sort().filter(i=>!t.scope||i.includes(t.scope)).flatMap(i=>Q(e,i)):t.requireCallableSymbol?Ed(e,{scope:t.scope,symbolMatches:le,sqlPrefilter:"callable"}):Nd(e,t.scope)}function gI(e,t){return t.requireCallableSymbol?le(e.symbol):t.requireFunctionLikeSymbol?ue(e.symbol):e.isFunctionLike}function hI(e){return(e.split("/").pop()??"").includes("types")}var A=class{constructor(t){this.db=t}db;scopedDefinitions(t){return ir(this.db,t)}definitionsForFile(t){return Q(this.db,t)}productionCallableDefinitions(t={}){return dp(this.db,t)}calleeMap(t,n={}){return es(this.db,t,n)}crossFileCallerMap(t,n={}){return ec(this.db,t,n)}sourceFallbackCallerFiles(t){return tc(this.db,t)}callerFileMap(t,n={}){return lp(this.db,t,n)}frameworkReferencedSymbolIds(t){let n=new Map;for(let r of t){if(!r.leaf)continue;let o=n.get(r.leaf)??[];o.push(r.symbolId),n.set(r.leaf,o)}let i=new Set;for(let r of B(this.db,{includeIgnored:!1}))if(K(r)==="rust")for(let{name:o}of fn(this.db,r,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])i.add(s);return i}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let i=new Map(t.map(o=>[o.symbolId,o.symbol])),r=this.calleeMap(t,n);return new Set([...r.entries()].filter(([o,s])=>{let a=i.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return pe(this.db,t)}fileKind(t){return X(t)}hasSuppressionComment(t){return mo(this.db,t.relativePath,t.startLine)}sourceFiles(){return $e(this.db)}scanSourceReferences(t,n){up(this.db,t,n)}callableSignature(t){let n=ye(this.db,t.relativePath)?.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};function nc(e,t){let n=V(e,t);if(!n)return[];let i=M(n.symbol),o=new A(e).definitionsForFile(n.relativePath).filter(c=>le(c.symbol)),s=o.filter(c=>c.parentTypeName===i||c.symbol.includes(i));return(s.length>0?s:bI(yI(n.relativePath))===i?o.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:M(c.symbol)}))}function bI(e){return e.replace(/\.[^.]+$/,"")}function ic(e,t,n={}){let i=V(e,t);if(!i)return[];let o=!ue(i.symbol)&&!e.isIgnored(i.relativePath)?[{relativePath:i.relativePath,line:i.startLine}]:[],s=en(e,i,{semantic:n.semantic}).map(u=>({relativePath:u.file,line:u.line})),a=SI(e,i),c=new Set,l=[];for(let u of[...o,...s,...a]){let d=`${u.relativePath}:${u.line}`;c.has(d)||(c.add(d),l.push(u))}return l}function SI(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=xI(t.symbol);if(n.length===0)return[];let i=[];for(let r of B(e,{extensions:[".rb"],includeIgnored:!1})){let o=F(e,r);if(!o)continue;let s=o.split(`
|
|
257
|
+
`);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&i.push({relativePath:r,line:a})}}return i}function xI(e){let n=(e.split(":").pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),i=n.split("_").filter(Boolean),r=new Set;return n&&r.add(n),i.length>=1&&r.add(i[i.length-1]),i.length>=2&&r.add(i.slice(-2).join("_")),[...r]}function xr(e,t,n={}){let i=V(e,t);if(!i)return{definitions:[],referencedBy:[]};let r=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",i.symbolId),o=hn(r?.documentation??null),s=e.isIgnored(i.relativePath)?[]:[{relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,signature:vI(o,r?.display_name??null,i.symbol),source:CI(e,i.relativePath,i.startLine,i.endLine)}],a=en(e,i,{semantic:n.semantic}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?v(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function CI(e,t,n,i){let r=F(e,t);if(!r)return null;let s=r.split(`
|
|
258
|
+
`).slice(n,i+1).join(`
|
|
259
|
+
`).trimEnd();return s.length>0?s:null}function vI(e,t,n){let i=gn(e);if(i&&!RI(i))return i;let r=(t??"").trim();return r?ue(n)&&!r.endsWith("()")?`${r}()`:r:v(n)}function RI(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Cr(e,t){let n=Be(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
|
|
209
260
|
FROM mentions m
|
|
210
261
|
JOIN chunks c ON m.chunk_id = c.id
|
|
211
262
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -221,7 +272,7 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
221
272
|
WHERE d1.relative_path = ?
|
|
222
273
|
AND d2.relative_path <> d1.relative_path
|
|
223
274
|
AND ${e.localSymbolPredicate}
|
|
224
|
-
ORDER BY d2.relative_path`,n).filter(
|
|
275
|
+
ORDER BY d2.relative_path`,n).filter(r=>!e.isIgnored(r.relative_path)).map(r=>({relativePath:r.relative_path})):[]}function vr(e,t){let n=Be(e,t);return n?e.all(`SELECT DISTINCT d1.relative_path
|
|
225
276
|
FROM mentions m
|
|
226
277
|
JOIN chunks c ON m.chunk_id = c.id
|
|
227
278
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -236,9 +287,9 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
236
287
|
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
237
288
|
WHERE d2.relative_path = ?
|
|
238
289
|
AND d1.relative_path != ?
|
|
239
|
-
ORDER BY d1.relative_path`,n,n).filter(
|
|
240
|
-
WHERE relative_path IN (${
|
|
241
|
-
ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),s=
|
|
290
|
+
ORDER BY d1.relative_path`,n,n).filter(r=>!e.isIgnored(r.relative_path)).map(r=>({relativePath:r.relative_path})):[]}function Rr(e,t){let n=hi(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let i=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
|
|
291
|
+
WHERE relative_path IN (${i})
|
|
292
|
+
ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),s=ko(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:d,...m})=>m),c=e.all(`SELECT DISTINCT d2.relative_path
|
|
242
293
|
FROM mentions m
|
|
243
294
|
JOIN chunks c ON m.chunk_id = c.id
|
|
244
295
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -251,8 +302,8 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
251
302
|
GROUP BY m2.symbol_id
|
|
252
303
|
) sym_def ON sym_def.symbol_id = gs.id
|
|
253
304
|
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
254
|
-
WHERE d1.relative_path IN (${
|
|
255
|
-
AND d2.relative_path NOT IN (${
|
|
305
|
+
WHERE d1.relative_path IN (${i})
|
|
306
|
+
AND d2.relative_path NOT IN (${i})
|
|
256
307
|
AND ${e.localSymbolPredicate}
|
|
257
308
|
ORDER BY d2.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),u=e.all(`SELECT DISTINCT d1.relative_path
|
|
258
309
|
FROM mentions m
|
|
@@ -267,9 +318,9 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
267
318
|
GROUP BY m2.symbol_id
|
|
268
319
|
) sym_def ON sym_def.symbol_id = gs.id
|
|
269
320
|
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
270
|
-
WHERE d2.relative_path IN (${
|
|
271
|
-
AND d1.relative_path NOT IN (${
|
|
272
|
-
ORDER BY d1.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d));return{files:o,symbols:s,dependsOn:c,dependedOnBy:u}}function
|
|
321
|
+
WHERE d2.relative_path IN (${i})
|
|
322
|
+
AND d1.relative_path NOT IN (${i})
|
|
323
|
+
ORDER BY d1.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d));return{files:o,symbols:s,dependsOn:c,dependedOnBy:u}}function kr(e,t){let n=hi(e,t);return n.length===0?[]:II([...kI(e,n),...wI(e,n)]).filter(i=>!e.isIgnored(i.relative_path)).map(LI)}function kI(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
|
|
273
324
|
FROM mentions m
|
|
274
325
|
JOIN chunks c ON m.chunk_id = c.id
|
|
275
326
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -296,7 +347,7 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
296
347
|
AND m.role != 1
|
|
297
348
|
AND ${e.localSymbolPredicate}
|
|
298
349
|
${e.pathExclusionsFor("d1")}
|
|
299
|
-
ORDER BY d1.relative_path`,...t,...t,...t)}function pw(e,t){let n=new T(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>Ce(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function fw(e){let t=new Set;return e.filter(n=>{let r=`${n.relative_path}|${n.symbol}`;return t.has(r)?!1:(t.add(r),!0)})}function gw(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:b(e.symbol)}}var ci=new WeakMap;function Tm(e,t){let n=W(t);return n==="rust"?Rw(e,t):n==="typescript"||n==="tsx"||n==="javascript"?Sw(e,t):[]}var hw=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),yw=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,bw=/\b(?:export\s+)?(?:async\s+)?function\s+use[A-Z][A-Za-z0-9_$]*\b|\b(?:const|let|var)\s+use[A-Z][A-Za-z0-9_$]*\s*(?::[^=;]+)?=\s*(?:async\s*)?(?:function\b|(?:<[^=;{]+>\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>)/;function Sw(e,t){let n=F(e,t);if(!n||!xw(n))return[];let r=fe(e,t);if(!r)return[];let i=ci.get(r);if(i)return i;let o=!1,s=r.rootNode;for(let c of s.namedChildren){if(c.type!=="expression_statement")continue;let l=c.namedChild(0);if(!l||l.type!=="call_expression")continue;let u=l.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&hw.has(d)){o=!0;break}}let a=[];o&&a.push({startLine:0,endLine:s.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"});for(let c of s.namedChildren){let l=null,u=null;if(c.type==="function_declaration")l=c.namedChild(0)?.text??null,u=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(l=d.namedChild(0)?.text??null,u=d)}else if(c.type==="lexical_declaration"){let d=c.namedChild(0);if(d?.type==="variable_declarator"){let m=d.namedChild(0)?.text,f=d.namedChild(1);m&&(f?.type==="arrow_function"||f?.type==="function_expression")&&(l=m,u=d)}}l&&/^use[A-Z]/.test(l)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)"})}return a.push(..._m(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),ci.set(r,a),a}function xw(e){return e.includes("scip-query")||yw.test(e)||bw.test(e)}var Cw=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function vw(e){return Cw.test(e)}function _m(e,t,n){let r=[],i=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,c=-1;for(let l=0;l<a.length;l+=1)if(a[l].startIndex===o.startIndex&&a[l].type===o.type){c=l;break}if(c>0)for(let l=c-1;l>=0;l-=1){let u=a[l];if(n.has(u.type)){if(vw(u.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)i(s)};return i(e.rootNode),r}function Rw(e,t){let n=fe(e,t);if(!n)return[];let r=ci.get(n);if(r)return r;let i=[],o=kw(n);return o?(ci.set(n,o),o):(Fm(n.rootNode,i,!1,!1),i.push(..._m(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),i.push(...Tw(n.rootNode)),ci.set(n,i),i)}function kw(e){return _w(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function Fm(e,t,n,r){let i=n,o=r;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(o=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)"})),e.type==="function_item"||e.type==="function_signature_item"?ww(e,t,n,r):r&&Ew(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?Lw(e,t,n):e.type==="mod_item"&&ja(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)Fm(s,t,i,o)}function ww(e,t,n,r){let i=ja(e),o=null;r?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of i){let a=Dw(s);if(a){o=a;break}if($m(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function Lw(e,t,n){let r=ja(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(Nw)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:i}),r.some($m)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",containerName:i})}function ja(e){let t=e.parent;if(!t)return[];let n=t.children,r=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){r=o;break}if(r<=0)return[];let i=[];for(let o=r-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")i.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return i}var Iw=[{re:/#\[\s*tauri::command\b/,reason:"#[tauri::command]"},{re:/#\[\s*command\b/,reason:"#[command]"},{re:/#\[\s*test\b/,reason:"#[test]"},{re:/#\[\s*bench\b/,reason:"#[bench]"},{re:/#\[\s*tokio::test\b/,reason:"#[tokio::test]"},{re:/#\[\s*async_std::test\b/,reason:"#[async_std::test]"},{re:/#\[\s*wasm_bindgen\b/,reason:"#[wasm_bindgen]"},{re:/#\[\s*no_mangle\b/,reason:"#[no_mangle]"},{re:/#\[\s*napi\b/,reason:"#[napi]"},{re:/#\[\s*pyfunction\b/,reason:"#[pyfunction]"},{re:/#\[\s*pymethod\b/,reason:"#[pymethod]"},{re:/#\[\s*pyo3\b/,reason:"#[pyo3]"},{re:/#\[\s*cfg\s*\(\s*test\s*\)/,reason:"#[cfg(test)]"},{re:/#\[\s*doc\s*\(\s*hidden\s*\)/,reason:"#[doc(hidden)]"}];function Dw(e){return Iw.find(({re:t})=>t.test(e))?.reason??null}var Pw=[/\bSerialize\b/,/\bDeserialize\b/,/\bFromRow\b/,/\bsqlx::FromRow\b/,/\bDeriveEntityModel\b/,/\bIntoSchema\b/,/\bToSchema\b/,/\bDeriveValueType\b/,/\bError\b/,/\bthiserror::Error\b/];function Nw(e){return/#\[\s*derive\s*\(/.test(e)?Pw.some(t=>t.test(e)):!1}function $m(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function Ew(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function Tw(e){let t=$w(e);if(t.size===0)return[];let n=[];for(let r of e.descendantsOfType("mod_item")){let i=r.childForFieldName("name")?.text;i&&t.has(i)&&n.push({startLine:r.startPosition.row,endLine:r.endPosition.row,reason:'serde `with = "..."` module \u2014 body invoked via reflection',containerName:i})}return n}function _w(e){for(let t=0;t<Math.min(e.namedChildCount,12);t+=1){let n=e.namedChild(t);if(!n||n.type!=="line_comment"&&n.type!=="block_comment")break;if(/@generated\b/.test(n.text)||/This file is .*generated\b/i.test(n.text)||/Code generated by/i.test(n.text)||/Generated by:\s*https?:\/\/openapi-generator/i.test(n.text)||/openapi-generator/i.test(n.text)&&/Generated by/i.test(n.text))return!0}return!1}var Fw=/^#!?\[\s*serde\s*\(/,Em=/\bwith\s*=\s*"([^"]+)"/g;function $w(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!Fw.test(n.text))continue;Em.lastIndex=0;let r;for(;(r=Em.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function Am(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=Tm(e,r);return i={ranges:o.map(s=>({startLine:s.startLine,endLine:s.endLine})),containers:new Set(o.map(s=>s.containerName).filter(s=>!!s))},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r);for(let c of a.ranges)if(i>=c.startLine&&i<=c.endLine)return!0;if(s&&a.containers.has(s))return!0;for(let c of so(o))if(a.containers.has(c))return!0;return!1}}function Oa(e,t={}){Ys(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function Ba(e,t,n={}){Ys(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function jm(e,t){return t.isIgnoredPath(e.relativePath)?pt("ignored-file"):Ot(e.symbol)?pt("module-like-symbol"):Mm(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&Mm(e.enclosingSymbol)?pt("nested-non-callable-value"):!t.includeTests&&!Ha(e.relativePath)?pt("test-file"):!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName)?pt("excluded-file-region"):ro(e.symbol)?pt("rust-trait-impl-member"):tr(e.symbol)?pt("rust-test-module"):!t.includeMembers&&!Aw(e)?pt("member"):e.endLine-e.startLine+1<t.minLoc?pt("below-min-loc"):{accepted:!0}:pt("non-value-symbol")}function Ha(e){return J(e)!=="test"}function pt(e){return{accepted:!1,rejectionReason:e}}function Mm(e){return ce(e)||e.endsWith("().")||e.endsWith(".")}function Aw(e){return Ce(e.symbol)||so(e.symbol).length===0}function jo(e,t){return q(e)-q(t)||e.relativePath.localeCompare(t.relativePath)}function We(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function br(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}`;t.has(i)||(t.add(i),n.push(r))}return n}function Om(){return new Map}function Bm(e,t,n){let r=new Map;for(let i of Wd(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Oo(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function Hm(e,t,n){let r=new Set;for(let i of Gd(e,t))e.isIgnored(i.relative_path)||n.has(i.relative_path)||r.add(i.symbol_id);return r}function Va(e,t){let n=e.get(t);if(!n)return!1;for(let r of n.values())if(r.occurrences>0)return!0;return!1}function qa(e,t,n){let r=e.get(t);if(!r)return!1;for(let[i,o]of r)if(i!==n&&o.occurrences>0)return!0;return!1}function Vm(e){return e?.occurrences??0}function Oo(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=Um(e,t,n);o.occurrences+=r,o.sources.add(i)}function qm(e,t,n,r,i){if(r<=0)return;let o=Um(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function Um(e,t,n){let r=e.get(t);r||(r=new Map,e.set(t,r));let i=r.get(n);return i||(i={occurrences:0,sources:new Set},r.set(n,i)),i}var Mw=3e3,jw=1e3;function Dt(e,t={}){let{scope:n,minLoc:r=1,includeTests:i=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:l=!0}=t,u=We(Ow(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c),d=o?new Set(Hd(e)):new Set,m=a?Om():Bm(e,d,u.map(S=>S.symbolId)),f=a?Hm(e,u.map(S=>S.symbolId),d):new Set,h=a?u.filter(S=>!f.has(S.symbolId)):u.filter(S=>!qa(m,S.symbolId,S.relativePath));a?Uw(e,h,m,d):qw(e,h,m,d);let g=a?h.filter(S=>!Va(m,S.symbolId)):h.filter(S=>!qa(m,S.symbolId,S.relativePath));Kw(e,g,m,{includeTests:i,inactiveBarrelPaths:d,includeSemantic:!a&&l});let y=a?h.filter(S=>!Va(m,S.symbolId)):u;return Vw(e,Bw(y,m))}function Ow(e,t){let n=Am(e),r=[];for(let i of j(e,{scope:t.scope}))try{for(let o of z(e,i))jm(o,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:a=>e.isIgnored(a),isExcludedRegion:n}).accepted&&r.push(o)}finally{Ba(e,i,{definitions:!0})}return r}function Bw(e,t){return e.map(n=>Hw(n,t)).filter(n=>n.cross_file_refs===0).sort((n,r)=>r.loc-n.loc||n.relative_path.localeCompare(r.relative_path)||n.start_line-r.start_line)}function Hw(e,t){let n=t.get(e.symbolId)??new Map,r=Vm(n.get(e.relativePath)),i=0;for(let[o,s]of n)o!==e.relativePath&&(i+=s.occurrences);return{relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine,loc:e.endLine-e.startLine+1,symbol:e.symbol,same_file_refs:r,cross_file_refs:i}}function Vw(e,t){let n=[],r=0,i=0,o=0;for(let s of t){if(e.isIgnored(s.relative_path)||De(e,s.relative_path)||ie(e,s.symbol,s.relative_path))continue;let a=s.same_file_refs===0?"dead-code":"file-internal";a==="dead-code"?r++:i++,o+=s.loc,n.push({relativePath:s.relative_path,startLine:s.start_line,endLine:s.end_line,loc:s.loc,symbol:s.symbol,shortName:b(s.symbol),sameFileRefs:s.same_file_refs,kind:a})}return{symbols:n,counts:{total:n.length,deadCode:r,fileInternal:i,loc:o},totalCount:n.length,deadCodeCount:r,fileInternalCount:i,totalLoc:o}}function qw(e,t,n,r){if(t.length===0)return;let i=new T(e),o=new Set(t.map(c=>c.symbolId)),s=new Set(t.map(c=>c.leaf).filter(Boolean)),a=new Set(i.sourceFiles());for(let c of j(e))a.add(c);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>r.has(c)},c=>{o.has(c.target.symbolId)&&(zw(e,c)||Oo(n,c.target.symbolId,c.sourceFile,Jw(c),"source-fallback"))})}function Uw(e,t,n,r){if(t.length===0)return;let i=new T(e),o=Ww(t),s=new Set(i.sourceFiles());for(let u of j(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=$o(e,u),c.set(u,d)),d};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let f=o.get(d);return f?Gw(u,d,f,l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),Ba(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&Wm(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||Oo(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function Ww(e){let t=new Map;for(let n of e){if(!n.leaf)continue;let r=t.get(n.leaf)??[];r.push(n),t.set(n.leaf,r)}return t}function Gw(e,t,n,r,i){let o=n.filter(c=>c.relativePath===e);if(o.length>0)return o;if(!i.permissive&&n.length===1)return[...n];let s=r.get(t);if(s)for(let c of s){let l=n.filter(u=>Wt(c,u.relativePath));if(l.length>0)return l}let a=new Set;for(let c of r.values())for(let l of c)a.add(l);for(let c of a){let l=n.filter(u=>Wt(c,u.relativePath));if(l.length>0&&l.length===n.length)return l}return i.permissive?[...n]:[]}function zw(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&Wm(e,t)}function Jw(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function Wm(e,t){return t.occurrences>1?!1:he(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function Kw(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=Mw&&j(e).length>=jw,s=(c,l)=>{l===c.relativePath||e.isIgnored(l)||r.inactiveBarrelPaths.has(l)||!r.includeTests&&!Ha(l)||qm(n,c.symbolId,l,1,"caller-map")};for(let c of t){let l=Ue(e,c,{semantic:i&&!o});if(l.length!==0)for(let u of l)s(c,u.file)}if(!o)return;let a=mt(e,t);for(let c of t){let l=a.get(c.symbolId);if(l)for(let u of l)s(c,u)}}function Ua(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"",s=e.all(`SELECT
|
|
350
|
+
ORDER BY d1.relative_path`,...t,...t,...t)}function wI(e,t){let n=new A(e);return t.flatMap(i=>n.definitionsForFile(i).filter(r=>le(r.symbol)).map(r=>({relative_path:i,symbol:r.symbol})))}function II(e){let t=new Set;return e.filter(n=>{let i=`${n.relative_path}|${n.symbol}`;return t.has(i)?!1:(t.add(i),!0)})}function LI(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:v(e.symbol)}}var wr=new WeakMap;function pp(e,t){let n=K(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let r=F(e,t);if(!r)return[];let o=Z(e,t,r),s=ae(e,"definition-exclusions",t,o);if(s){let c=DI(s);if(c)return c}let a=n==="rust"?$I(e,t):TI(e,t);return ce(e,"definition-exclusions",t,o,JSON.stringify(a)),a}function DI(e){try{let t=JSON.parse(e);return!Array.isArray(t)||!t.every(PI)?null:t}catch{return null}}function PI(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.startLine!="number"||!Number.isFinite(t.startLine)||typeof t.endLine!="number"||!Number.isFinite(t.endLine)||typeof t.reason!="string"?!1:t.containerName===void 0||typeof t.containerName=="string"}var fp=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),NI=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,EI=/\b(?:export\s+)?(?:async\s+)?function\s+use[A-Z][A-Za-z0-9_$]*\b|\b(?:const|let|var)\s+use[A-Z][A-Za-z0-9_$]*\s*(?::[^=;]+)?=\s*(?:async\s*)?(?:function\b|(?:<[^=;{]+>\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>)/;function TI(e,t){let n=F(e,t);if(!n||!FI(n))return[];let i=ke(e,t);if(!i)return[];let r=wr.get(i);if(r)return r;let o=!1,s=i.rootNode;for(let c of s.namedChildren){if(c.type!=="expression_statement")continue;let l=c.namedChild(0);if(!l||l.type!=="call_expression")continue;let u=l.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&fp.has(d)){o=!0;break}}let a=[];o&&a.push({startLine:0,endLine:s.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"});for(let c of s.namedChildren){let l=null,u=null;if(c.type==="function_declaration")l=c.namedChild(0)?.text??null,u=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(l=d.namedChild(0)?.text??null,u=d)}else if(c.type==="lexical_declaration"){let d=c.namedChild(0);if(d?.type==="variable_declarator"){let m=d.namedChild(0)?.text,p=d.namedChild(1);m&&(p?.type==="arrow_function"||p?.type==="function_expression")&&(l=m,u=d)}}l&&/^use[A-Z]/.test(l)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)"})}return a.push(...gp(i,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),wr.set(i,a),a}function FI(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of fp)if(e.includes(n)){t=!0;break}return t&&NI.test(e)?!0:e.includes("use")&&EI.test(e)}var _I=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function AI(e){return _I.test(e)}function gp(e,t,n){let i=[],r=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,c=-1;for(let l=0;l<a.length;l+=1)if(a[l].startIndex===o.startIndex&&a[l].type===o.type){c=l;break}if(c>0)for(let l=c-1;l>=0;l-=1){let u=a[l];if(n.has(u.type)){if(AI(u.text)){i.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)r(s)};return r(e.rootNode),i}function $I(e,t){let n=ke(e,t);if(!n)return[];let i=wr.get(n);if(i)return i;let r=[],o=MI(n);return o?(wr.set(n,o),o):(hp(n.rootNode,r,!1,!1),r.push(...gp(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),r.push(...WI(n.rootNode)),wr.set(n,r),r)}function MI(e){return zI(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function hp(e,t,n,i){let r=n,o=i;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(o=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)"})),e.type==="function_item"||e.type==="function_signature_item"?OI(e,t,n,i):i&&UI(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?jI(e,t,n):e.type==="mod_item"&&rc(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(r=!0);for(let s of e.namedChildren)hp(s,t,r,o)}function OI(e,t,n,i){let r=rc(e),o=null;i?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of r){let a=HI(s);if(a){o=a;break}if(yp(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function jI(e,t,n){let i=rc(e),r=e.namedChildren.find(o=>o.type==="type_identifier")?.text;i.some(qI)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:r}),i.some(yp)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",containerName:r}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",containerName:r})}function rc(e){let t=e.parent;if(!t)return[];let n=t.children,i=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){i=o;break}if(i<=0)return[];let r=[];for(let o=i-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")r.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return r}var BI=[{re:/#\[\s*tauri::command\b/,reason:"#[tauri::command]"},{re:/#\[\s*command\b/,reason:"#[command]"},{re:/#\[\s*test\b/,reason:"#[test]"},{re:/#\[\s*bench\b/,reason:"#[bench]"},{re:/#\[\s*tokio::test\b/,reason:"#[tokio::test]"},{re:/#\[\s*async_std::test\b/,reason:"#[async_std::test]"},{re:/#\[\s*wasm_bindgen\b/,reason:"#[wasm_bindgen]"},{re:/#\[\s*no_mangle\b/,reason:"#[no_mangle]"},{re:/#\[\s*napi\b/,reason:"#[napi]"},{re:/#\[\s*pyfunction\b/,reason:"#[pyfunction]"},{re:/#\[\s*pymethod\b/,reason:"#[pymethod]"},{re:/#\[\s*pyo3\b/,reason:"#[pyo3]"},{re:/#\[\s*cfg\s*\(\s*test\s*\)/,reason:"#[cfg(test)]"},{re:/#\[\s*doc\s*\(\s*hidden\s*\)/,reason:"#[doc(hidden)]"}];function HI(e){return BI.find(({re:t})=>t.test(e))?.reason??null}var VI=[/\bSerialize\b/,/\bDeserialize\b/,/\bFromRow\b/,/\bsqlx::FromRow\b/,/\bDeriveEntityModel\b/,/\bIntoSchema\b/,/\bToSchema\b/,/\bDeriveValueType\b/,/\bError\b/,/\bthiserror::Error\b/];function qI(e){return/#\[\s*derive\s*\(/.test(e)?VI.some(t=>t.test(e)):!1}function yp(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function UI(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function WI(e){let t=JI(e);if(t.size===0)return[];let n=[];for(let i of e.descendantsOfType("mod_item")){let r=i.childForFieldName("name")?.text;r&&t.has(r)&&n.push({startLine:i.startPosition.row,endLine:i.endPosition.row,reason:'serde `with = "..."` module \u2014 body invoked via reflection',containerName:r})}return n}function zI(e){for(let t=0;t<Math.min(e.namedChildCount,12);t+=1){let n=e.namedChild(t);if(!n||n.type!=="line_comment"&&n.type!=="block_comment")break;if(/@generated\b/.test(n.text)||/This file is .*generated\b/i.test(n.text)||/Code generated by/i.test(n.text)||/Generated by:\s*https?:\/\/openapi-generator/i.test(n.text)||/openapi-generator/i.test(n.text)&&/Generated by/i.test(n.text))return!0}return!1}var GI=/^#!?\[\s*serde\s*\(/,mp=/\bwith\s*=\s*"([^"]+)"/g;function JI(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!GI.test(n.text))continue;mp.lastIndex=0;let i;for(;(i=mp.exec(n.text))!==null;){let r=i[1],o=r.split("::").pop()??r;o&&t.add(o)}}return t}function bp(e){let t=new Map,n=i=>{let r=t.get(i);if(r)return r;let o=pp(e,i);return r={ranges:o.map(s=>({startLine:s.startLine,endLine:s.endLine})),containers:new Set(o.map(s=>s.containerName).filter(s=>!!s))},t.set(i,r),r};return(i,r,o,s)=>{let a=n(i);for(let c of a.ranges)if(r>=c.startLine&&r<=c.endLine)return!0;if(s&&a.containers.has(s))return!0;for(let c of Io(o))if(a.containers.has(c))return!0;return!1}}function oc(e,t={}){ma(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function Sp(e,t,n={}){ma(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function Cp(e,t){return t.isIgnoredPath(e.relativePath)?xt("ignored-file"):Ut(e.symbol)?xt("module-like-symbol"):xp(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&xp(e.enclosingSymbol)?xt("nested-non-callable-value"):!t.includeTests&&!sc(e.relativePath)?xt("test-file"):!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName)?xt("excluded-file-region"):Ro(e.symbol)?xt("rust-trait-impl-member"):di(e.symbol)?xt("rust-test-module"):!t.includeMembers&&!KI(e)?xt("member"):e.endLine-e.startLine+1<t.minLoc?xt("below-min-loc"):{accepted:!0}:xt("non-value-symbol")}function sc(e){return X(e)!=="test"}function xt(e){return{accepted:!1,rejectionReason:e}}function xp(e){return ue(e)||e.endsWith("().")||e.endsWith(".")}function KI(e){return le(e.symbol)||Io(e.symbol).length===0}function ts(e,t){return G(e)-G(t)||e.relativePath.localeCompare(t.relativePath)}function qe(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Di(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.file}`;t.has(r)||(t.add(r),n.push(i))}return n}function vp(){return new Map}function Rp(e,t,n){let i=new Map;for(let r of Sm(e,n))e.isIgnored(r.relative_path)||t.has(r.relative_path)||is(i,r.symbol_id,r.relative_path,r.ref_count,"scip-mention");return i}function kp(e,t,n){let i=new Set;for(let r of xm(e,t))e.isIgnored(r.relative_path)||n.has(r.relative_path)||i.add(r.symbol_id);return i}function ac(e,t){let n=e.get(t);if(!n)return!1;for(let i of n.values())if(i.occurrences>0)return!0;return!1}function ns(e,t,n){let i=e.get(t);if(!i)return!1;for(let[r,o]of i)if(r!==n&&o.occurrences>0)return!0;return!1}function wp(e){return e?.occurrences??0}function is(e,t,n,i,r="source-fallback"){if(i<=0)return;let o=Lp(e,t,n);o.occurrences+=i,o.sources.add(r)}function Ip(e,t,n,i,r){if(i<=0)return;let o=Lp(e,t,n);o.occurrences=Math.max(i,o.occurrences),o.sources.add(r)}function Lp(e,t,n){let i=e.get(t);i||(i=new Map,e.set(t,i));let r=i.get(n);return r||(r={occurrences:0,sources:new Set},i.set(n,r)),r}var QI=3e3,XI=1e3;function At(e,t={}){let{scope:n,minLoc:i=1,includeTests:r=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:l=!0}=t,u=0,d=T("dead.candidates",()=>{let x=qe(YI(e,{scope:n,minLoc:i,includeTests:r,includeMembers:s}),c);return u=x.length,x},()=>({definitions:u})),m=o?new Set(gm(e)):new Set,p=0,f=a?vp():T("dead.mention-reference-counts",()=>{let x=Rp(e,m,d.map(b=>b.symbolId));return p=x.size,x},()=>({definitions:d.length,symbolsWithReferences:p})),g=0,y=a?T("dead.mentioned-symbol-ids",()=>{let x=kp(e,d.map(b=>b.symbolId),m);return g=x.size,x},()=>({definitions:d.length,referencedSymbols:g})):new Set,S=a?d.filter(x=>!y.has(x.symbolId)):d.filter(x=>!ns(f,x.symbolId,x.relativePath));a?T("dead.source-fallback.dead-code-only",()=>iL(e,S,f,m),()=>({definitions:S.length})):T("dead.source-fallback.ast",()=>nL(e,S,f,m),()=>({definitions:S.length}));let R=a?S.filter(x=>!ac(f,x.symbolId)):S.filter(x=>!ns(f,x.symbolId,x.relativePath));T("dead.caller-map-supplement",()=>cL(e,R,f,{includeTests:r,inactiveBarrelPaths:m,includeSemantic:!a&&l}),()=>({definitions:R.length,semantic:!a&&l}));let k=a?S.filter(x=>!ac(f,x.symbolId)):d;return tL(e,ZI(k,f))}function YI(e,t){let n=bp(e),i=[];for(let r of ir(e,t.scope))Cp(r,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n}).accepted&&i.push(r);return i}function ZI(e,t){return e.map(n=>eL(n,t)).filter(n=>n.cross_file_refs===0).sort((n,i)=>i.loc-n.loc||n.relative_path.localeCompare(i.relative_path)||n.start_line-i.start_line)}function eL(e,t){let n=t.get(e.symbolId)??new Map,i=wp(n.get(e.relativePath)),r=0;for(let[o,s]of n)o!==e.relativePath&&(r+=s.occurrences);return{relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine,loc:e.endLine-e.startLine+1,symbol:e.symbol,same_file_refs:i,cross_file_refs:r}}function tL(e,t){let n=[],i=0,r=0,o=0;for(let s of t){if(e.isIgnored(s.relative_path)||Oe(e,s.relative_path)||fe(e,s.symbol,s.relative_path))continue;let a=s.same_file_refs===0?"dead-code":"file-internal";a==="dead-code"?i++:r++,o+=s.loc,n.push({relativePath:s.relative_path,startLine:s.start_line,endLine:s.end_line,loc:s.loc,symbol:s.symbol,shortName:v(s.symbol),sameFileRefs:s.same_file_refs,kind:a})}return{symbols:n,counts:{total:n.length,deadCode:i,fileInternal:r,loc:o},totalCount:n.length,deadCodeCount:i,fileInternalCount:r,totalLoc:o}}function nL(e,t,n,i){if(t.length===0)return;let r=new A(e),o=new Set(t.map(c=>c.symbolId)),s=new Set(t.map(c=>c.leaf).filter(Boolean)),a=new Set(r.sourceFiles());for(let c of B(e))a.add(c);r.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>i.has(c)},c=>{o.has(c.target.symbolId)&&(sL(e,c)||is(n,c.target.symbolId,c.sourceFile,aL(c),"source-fallback"))})}function iL(e,t,n,i){if(t.length===0)return;let r=new A(e),o=rL(t),s=new Set(r.sourceFiles());for(let u of B(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=Zo(e,u),c.set(u,d)),d};r.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>i.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let p=o.get(d);return p?oL(u,d,p,()=>l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),Sp(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&Dp(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||is(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function rL(e){let t=new Map;for(let n of e){if(!n.leaf)continue;let i=t.get(n.leaf)??[];i.push(n),t.set(n.leaf,i)}return t}function oL(e,t,n,i,r){let o=n.filter(l=>l.relativePath===e);if(o.length>0)return o;if(!r.permissive&&n.length===1)return[...n];let s=i(),a=s.get(t);if(a)for(let l of a){let u=n.filter(d=>Qt(l,d.relativePath));if(u.length>0)return u}let c=new Set;for(let l of s.values())for(let u of l)c.add(u);for(let l of c){let u=n.filter(d=>Qt(l,d.relativePath));if(u.length>0&&u.length===n.length)return u}return r.permissive?[...n]:[]}function sL(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&Dp(e,t)}function aL(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function Dp(e,t){return t.occurrences>1?!1:Ie(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function cL(e,t,n,i){let r=i.includeSemantic!==!1,o=r&&t.length>=QI&&B(e).length>=XI,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||i.inactiveBarrelPaths.has(d)||!i.includeTests&&!sc(d)||Ip(n,u.symbolId,d,1,"caller-map")};if(o?T("dead.caller-map.mention-chunks",()=>lL(e,t,s),()=>({definitions:t.length})):T("dead.caller-map.per-symbol",()=>{for(let u of t){let d=tt(e,u,{semantic:r});if(d.length!==0)for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:r})),!o)return;let a=0,c=T("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!ns(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return;let l=et(e,c);for(let u of c){let d=l.get(u.symbolId);if(d)for(let m of d)s(u,m)}}function lL(e,t,n){let i=new Map(t.map(r=>[r.symbolId,r]));for(let r of wi(e,[...i.keys()])){let o=i.get(r.symbol_id);o&&n(o,r.relative_path)}}function cc(e,t={}){let{limit:n=30,scope:i}=t,r=i?`AND def_d.relative_path LIKE '%${i}%'`:"",s=e.all(`SELECT
|
|
300
351
|
gs.symbol,
|
|
301
352
|
COUNT(*) AS ref_count,
|
|
302
353
|
COUNT(DISTINCT ref_d.id) AS file_count,
|
|
@@ -316,17 +367,17 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
316
367
|
WHERE m.role != 1
|
|
317
368
|
${e.pathExclusionsFor("def_d")}
|
|
318
369
|
${e.symbolNoiseFor("gs")}
|
|
319
|
-
${
|
|
370
|
+
${r}
|
|
320
371
|
GROUP BY gs.id
|
|
321
372
|
ORDER BY ref_count DESC
|
|
322
|
-
LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:
|
|
373
|
+
LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:v(a.symbol),refCount:a.ref_count,fileCount:a.file_count,definedIn:a.defined_in}));return s.length>0?s:uL(e,i,n)}function uL(e,t,n){return bt(e,{scope:t}).filter(i=>!e.isIgnored(i.relativePath)).map(i=>dL(e,i)).filter(i=>i.refCount>0).sort((i,r)=>r.refCount-i.refCount||r.fileCount-i.fileCount).slice(0,n)}function dL(e,t){let n=tt(e,t,{limit:500});return{symbol:t.symbol,shortName:v(t.symbol),refCount:n.length,fileCount:new Set(n.map(i=>i.file)).size,definedIn:t.relativePath}}function lc(e,t,n={}){return Np(e,t,n)?.map(i=>({symbol:i.symbol,shortName:i.shortName,fromFile:i.fromFile}))??[]}function uc(e,t){let n=mL(e,t);return n.length>0?n:pL(e,t)}function dc(e,t,n={}){return Np(e,t,n)?.filter(i=>!i.used).map(i=>({symbol:i.symbol,shortName:i.shortName,importedIn:i.importer}))??[]}function mL(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
|
|
323
374
|
FROM mentions m
|
|
324
375
|
JOIN chunks c ON m.chunk_id = c.id
|
|
325
376
|
JOIN documents d ON c.document_id = d.id
|
|
326
377
|
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
327
378
|
WHERE gs.symbol LIKE ?
|
|
328
379
|
AND m.role = 2
|
|
329
|
-
ORDER BY d.relative_path`,`%${t}%`).filter(
|
|
380
|
+
ORDER BY d.relative_path`,`%${t}%`).filter(i=>!e.isIgnored(i.importer)).map(i=>({symbol:i.symbol,shortName:v(i.symbol),fromFile:i.importer}))}function pL(e,t){let n=V(e,t),i=n?.relativePath??null,r=n?M(n.symbol):t.replace(/\(\)$/,""),o=n?Ut(n.symbol):!1,s=new Set;for(let a of B(e,{includeIgnored:!1}))for(let c of Ie(e,a))fL(c,a,{targetFile:i,targetLeaf:r,targetIsModule:o})&&s.add(a);return[...s].sort().map(a=>({symbol:n?.symbol??r,shortName:n?v(n.symbol):r,fromFile:a}))}function fL(e,t,n){return!e.sourcePath||n.targetFile&&Pp(e.sourcePath)!==Pp(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&bL(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function Np(e,t,n={}){let i=Be(e,t);return i?gL(e,i,n)??(n.semantic===!1?null:hL(e,i))??yL(e,i):null}function gL(e,t,n){let r=e.all(`SELECT DISTINCT
|
|
330
381
|
gs.symbol,
|
|
331
382
|
def_d.relative_path AS from_file,
|
|
332
383
|
imp_d.relative_path AS importer,
|
|
@@ -352,11 +403,11 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
352
403
|
LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
353
404
|
WHERE imp_d.relative_path = ?
|
|
354
405
|
AND m.role = 2
|
|
355
|
-
ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(
|
|
406
|
+
ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(r.length>0){let o=n.semantic===!1?[]:yr(e,t);return r.map(s=>({symbol:s.symbol,shortName:v(s.symbol),fromFile:s.from_file??"(external)",importer:s.importer,used:s.used!==0||o.some(a=>a.isUsed&&a.sourcePath===s.from_file)}))}return null}function hL(e,t){let n=yr(e,t);return n.length>0?n.map(i=>{let r=Ep(i.importedName,i.localName,i.kind);return{symbol:r,shortName:r,fromFile:i.sourcePath??"(external)",importer:t,used:i.kind==="side-effect"?!0:i.isUsed}}):null}function yL(e,t){return Ie(e,t).map(n=>{let i=Ep(n.importedName,n.localName,n.kind),r=n.kind==="side-effect"?!0:n.used;return{symbol:i,shortName:i,fromFile:n.sourcePath??"(external)",importer:t,used:r}})}function Ep(e,t,n){return n==="namespace"&&e==="*"&&t?`* as ${t}`:n==="default"&&t?`default as ${t}`:n==="side-effect"?"(side effect import)":t&&t!==e?`${e} as ${t}`:e}function Pp(e){return e.replace(/\\/g,"/")}function bL(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function mc(e,t){let n=hi(e,t),i=ko(e,n,{sort:!0});if(i.length===0)return[];let r=i.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,signature:a.signature,children:[]})),o=new Map;for(let a of r)o.set(a.symbol,a);let s=[];for(let a=0;a<i.length;a++){let c=i[a],l=r[a];if(c.enclosingSymbol&&o.has(c.enclosingSymbol)){o.get(c.enclosingSymbol).children.push(l);continue}let u=null,d=1/0;for(let m of r)if(m!==l&&m.startLine<=l.startLine&&m.endLine>=l.endLine){if(m.startLine===l.startLine&&m.endLine===l.endLine&&!xd(m.symbol,l.symbol))continue;let f=m.endLine-m.startLine;f<d&&(d=f,u=m)}u?u.children.push(l):s.push(l)}return s}function pc(e,t){let n=V(e,t);return n?new A(e).definitionsForFile(n.relativePath).filter(r=>r.symbol!==n.symbol).filter(r=>Sd(n.symbol,r.symbol)).sort((r,o)=>r.startLine-o.startLine||r.endLine-o.endLine).map(r=>({symbol:r.symbol,shortName:v(r.symbol),startLine:r.startLine,endLine:r.endLine,kind:ee(r.symbol)??"unknown"})):[]}function fc(e,t){let n=V(e,t);if(!n)return[];let i=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
|
|
356
407
|
FROM mentions m
|
|
357
408
|
JOIN chunks c ON m.chunk_id = c.id
|
|
358
409
|
WHERE m.symbol_id = ?
|
|
359
|
-
AND m.role != 1`,n.symbolId);return[{name:
|
|
410
|
+
AND m.role != 1`,n.symbolId);return[{name:v(n.symbol),count:i?.file_count??0}]}function gc(e,t){let n=Be(e,t);if(!n)return[];let r=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
360
411
|
FROM mentions m
|
|
361
412
|
JOIN chunks c ON m.chunk_id = c.id
|
|
362
413
|
JOIN documents d ON c.document_id = d.id
|
|
@@ -373,7 +424,7 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
373
424
|
AND m.role != 1
|
|
374
425
|
AND def_d.id != d.id
|
|
375
426
|
GROUP BY d.id
|
|
376
|
-
ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(
|
|
427
|
+
ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(r.length>0)return r;let s=pe(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function hc(e,t={}){return SL(e,t).map(n=>({name:v(n.symbol),count:n.file_count}))}function SL(e,t){let{limit:n=30,scope:i}=t,r=i?`AND def_d.relative_path LIKE '%${i}%'`:"";return e.all(`SELECT gs.symbol, COUNT(DISTINCT c.document_id) AS file_count
|
|
377
428
|
FROM mentions m
|
|
378
429
|
JOIN chunks c ON m.chunk_id = c.id
|
|
379
430
|
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
@@ -388,11 +439,11 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
388
439
|
WHERE m.role != 1
|
|
389
440
|
${e.pathExclusionsFor("def_d")}
|
|
390
441
|
${e.symbolNoiseFor("gs")}
|
|
391
|
-
${
|
|
442
|
+
${r}
|
|
392
443
|
GROUP BY gs.id
|
|
393
444
|
HAVING file_count > 1
|
|
394
445
|
ORDER BY file_count DESC
|
|
395
|
-
LIMIT ?`,n)}function
|
|
446
|
+
LIMIT ?`,n)}function yc(e,t={}){let{limit:n=30,scope:i}=t,r=i?`AND d.relative_path LIKE '%${i}%'`:"";return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
396
447
|
FROM mentions m
|
|
397
448
|
JOIN chunks c ON m.chunk_id = c.id
|
|
398
449
|
JOIN documents d ON c.document_id = d.id
|
|
@@ -409,10 +460,10 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
409
460
|
AND def_d.id != d.id
|
|
410
461
|
${e.pathExclusionsFor("d")}
|
|
411
462
|
${e.symbolNoiseFor("gs")}
|
|
412
|
-
${
|
|
463
|
+
${r}
|
|
413
464
|
GROUP BY d.id
|
|
414
465
|
ORDER BY symbol_count DESC
|
|
415
|
-
LIMIT ?`,n).filter(s=>!e.isIgnored(s.relative_path)).map(s=>({name:s.relative_path,count:s.symbol_count}))}function
|
|
466
|
+
LIMIT ?`,n).filter(s=>!e.isIgnored(s.relative_path)).map(s=>({name:s.relative_path,count:s.symbol_count}))}function bc(e,t,n){let i=Be(e,t)??t,r=Be(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
|
|
416
467
|
FROM global_symbols gs
|
|
417
468
|
WHERE (
|
|
418
469
|
-- Defined in file1, referenced in file2
|
|
@@ -444,7 +495,7 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
444
495
|
JOIN documents d ON c.document_id = d.id
|
|
445
496
|
WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
|
|
446
497
|
)
|
|
447
|
-
)`,r,
|
|
498
|
+
)`,i,r,r,i);return{...Tp(i,r,o?.shared??0)}}function Sc(e,t={}){let{limit:n=20,scope:i}=t,r=i?`AND d1.relative_path LIKE '%${i}%' AND d2.relative_path LIKE '%${i}%'`:"";return e.all(`SELECT
|
|
448
499
|
def_d.relative_path AS file1,
|
|
449
500
|
ref_d.relative_path AS file2,
|
|
450
501
|
COUNT(DISTINCT gs.id) AS shared
|
|
@@ -463,18 +514,18 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
463
514
|
WHERE m.role != 1
|
|
464
515
|
AND def_d.id != ref_d.id
|
|
465
516
|
${e.pathExclusionsFor("def_d","ref_d")}
|
|
466
|
-
${
|
|
517
|
+
${r}
|
|
467
518
|
GROUP BY def_d.id, ref_d.id
|
|
468
519
|
ORDER BY shared DESC
|
|
469
|
-
LIMIT ?`,n).filter(s=>!e.isIgnored(s.file1)&&!e.isIgnored(s.file2)).map(s=>
|
|
520
|
+
LIMIT ?`,n).filter(s=>!e.isIgnored(s.file1)&&!e.isIgnored(s.file2)).map(s=>Tp(s.file1,s.file2,s.shared))}function Tp(e,t,n){return{file1:e,file2:t,sharedSymbols:n,actionTier:"signal",couplingKind:"shared-symbol-coupling",evidenceReasons:[`${n} symbol(s) are defined in one file and referenced by the other`],recommendation:"Review whether the shared symbol surface is an intentional boundary or hidden coordination pressure before moving code."}}function Pn(e,t={}){let{scope:n,maxDepth:i=10}=t,r=pe(e,n),o=[],s=new Set,a=new Set,c=[];function l(d,m){if(m>i)return;if(a.has(d)){let f=c.indexOf(d);if(f!==-1){let g=c.slice(f).concat(d),y=g.indexOf(g.reduce((k,x)=>k<x?k:x)),S=[...g.slice(y,-1),...g.slice(0,y),g[y]],R=S.join(" -> ");u.has(R)||(u.add(R),o.push({path:S,kind:xL(S)}))}return}if(s.has(d))return;s.add(d),a.add(d),c.push(d);let p=r.get(d);if(p)for(let f of p)l(f,m+1);c.pop(),a.delete(d)}let u=new Set;for(let d of r.keys())s.has(d)||l(d,0);return o.sort((d,m)=>d.kind!==m.kind?d.kind==="real"?-1:1:d.path.length-m.path.length),o}function xL(e){for(let i of e){let r=X(i);if(r==="test"||r==="barrel"||r==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":qo(t)||qo(n)||Fp(t,n)||Fp(n,t)||_p(t,n)||_p(n,t)||X(t)==="entry"||X(n)==="entry"?"module-hierarchy":"real"}function Fp(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function _p(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),i=t.replace(/\.rs$/,"");if(n===i+"_tests"||n===i+"/tests")return!0;let r=e.split("/"),o=t.split("/");if(r.length===o.length&&r.includes("tests")&&o.includes("src")){let s=r[r.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}function xc(e,t={}){let{limit:n=20,scope:i,minFanIn:r=2,minFanOut:o=2,scanLimit:s}=t,a=new A(e);return qe(a.productionCallableDefinitions({scope:i,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>CL(e,u,t.semantic!==!1)).filter(u=>u.fanIn>=r&&u.fanOut>=o).sort((u,d)=>d.score-u.score||d.fanIn-u.fanIn).slice(0,n)}function CL(e,t,n){let i=new Set(tt(e,t,{limit:500,semantic:n}).map(s=>s.file)).size,r=new Set(Ge(e,t,{limit:500,semantic:n}).filter(s=>s.file!==t.relativePath).map(s=>`${s.symbol}|${s.file}`)).size,o=i*r;return{symbol:t.symbol,shortName:v(t.symbol),fanIn:i,fanOut:r,score:o,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${i} incoming file(s) reference this symbol`,`${r} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${o} (fan-in * fan-out)`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function Nn(e,t={}){let{scope:n,minLoc:i=3,scanLimit:r}=t,o=new A(e),s=t.semantic!==!1,a=qe(o.productionCallableDefinitions({scope:n,minLoc:i,excludeEntrySurfaces:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,sortByLocDesc:typeof r=="number"&&r>0}),r),c=o.symbolsWithNonSelfCallees(a,{additive:!1,semantic:!1}),l=a.filter(y=>!c.has(y.symbolId)),u=o.crossFileCallerMap(l,{semantic:!1}),d=new Set(u.keys());for(let y of o.frameworkReferencedSymbolIds(l))d.add(y);let m=l.filter(y=>!d.has(y.symbolId));if(s&&m.length>0){for(let y of et(e,m).keys())d.add(y);for(let y of o.symbolsWithNonSelfCallees(m,{additive:!1,semantic:!0}))c.add(y);m=m.filter(y=>!d.has(y.symbolId)).filter(y=>!c.has(y.symbolId))}let p=o.sourceFallbackCallerFiles(m);for(let y of p.keys())d.add(y);let f=m.filter(y=>!d.has(y.symbolId)),g=o.symbolsWithNonSelfCallees(f,{additive:!0,semantic:s});for(let y of g)c.add(y);return f.filter(y=>!c.has(y.symbolId)).sort((y,S)=>G(S)-G(y)||y.relativePath.localeCompare(S.relativePath)||y.startLine-S.startLine).map(y=>({symbol:y.symbol,shortName:v(y.symbol),relativePath:y.relativePath,startLine:y.startLine,endLine:y.endLine,loc:G(y)}))}var vc={0:"UnspecifiedKind",1:"AbstractMethod",2:"Accessor",3:"Array",4:"Assertion",5:"AssociatedType",6:"Attribute",7:"Axiom",8:"Boolean",9:"Class",10:"Constant",11:"Constructor",12:"Contract",13:"DataFamily",14:"DefinitionMacro",15:"Delegate",16:"Enum",17:"EnumMember",18:"Error",19:"Event",20:"Fact",21:"Field",22:"File",23:"Function",24:"Getter",25:"Grammar",26:"Instance",27:"Interface",28:"Key",29:"Lang",30:"Lemma",31:"Library",32:"Macro",33:"Method",34:"MethodAlias",35:"MethodReceiver",36:"MethodSpecification",37:"Message",38:"Modifier",39:"Module",40:"Namespace",41:"Null",42:"Number",43:"Object",44:"Operator",45:"Package",46:"PackageObject",47:"Parameter",48:"ParameterLabel",49:"Pattern",50:"Predicate",51:"Property",52:"Protocol",53:"ProtocolMethod",54:"PureVirtualMethod",55:"Quasiquoter",56:"SelfParameter",57:"Setter",58:"Signature",59:"SingletonClass",60:"SingletonMethod",61:"StaticDataMember",62:"StaticEvent",63:"StaticField",64:"StaticMethod",65:"StaticProperty",66:"StaticVariable",67:"String",68:"Struct",69:"Subscript",70:"Tactic",71:"Theorem",72:"ThisParameter",73:"Trait",74:"TraitMethod",75:"Type",76:"TypeAlias",77:"TypeClass",78:"TypeClassMethod",79:"TypeFamily",80:"TypeParameter",81:"Union",82:"Value",83:"Variable"},Cc=new Map;for(let[e,t]of Object.entries(vc))Cc.set(t.toLowerCase(),Number(e));var Ap=500;function vL(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),i=Cc.get(n);if(i!==void 0)return i;for(let[r,o]of Cc)if(r.includes(n))return o;return null}function Rc(e,t,n={}){let{scope:i,limit:r=100}=n,o=vL(t);return o===null?[]:RL(e,i).map(a=>({row:a,resolvedKind:Mp(a)})).filter(a=>a.resolvedKind===o).slice(0,r).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:v(a.symbol),kind:c,kindName:vc[c]??"Unknown",relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function kc(e,t={}){let n=kL(e,t.scope);for(let i of wL(e,t.scope)){let r=Mp(i);r===null||r===0||n.set(r,(n.get(r)??0)+1)}return[...n.entries()].sort((i,r)=>r[1]-i[1]||i[0]-r[0]).map(([i,r])=>({kind:i,kindName:vc[i]??"Unknown",count:r}))}function RL(e,t){return bt(e,{scope:t}).map(IL)}function kL(e,t){let n=new Map;for(let i of $p(B(e,{scope:t,includeIgnored:!1}))){let r=i.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
|
|
470
521
|
FROM defn_enclosing_ranges der
|
|
471
522
|
JOIN global_symbols gs ON der.symbol_id = gs.id
|
|
472
523
|
JOIN documents d ON der.document_id = d.id
|
|
473
524
|
WHERE gs.kind IS NOT NULL
|
|
474
525
|
AND gs.kind != 0
|
|
475
526
|
AND gs.symbol NOT LIKE '%#'
|
|
476
|
-
AND d.relative_path IN (${
|
|
477
|
-
GROUP BY gs.kind`,...
|
|
527
|
+
AND d.relative_path IN (${r})
|
|
528
|
+
GROUP BY gs.kind`,...i);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function wL(e,t){let n=[];for(let i of $p(B(e,{scope:t,includeIgnored:!1}))){let r=i.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
|
|
478
529
|
gs.kind,
|
|
479
530
|
gs.documentation,
|
|
480
531
|
gs.enclosing_symbol,
|
|
@@ -486,12 +537,12 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
486
537
|
JOIN documents d ON der.document_id = d.id
|
|
487
538
|
WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
|
|
488
539
|
${e.symbolNoiseFor("gs")}
|
|
489
|
-
AND d.relative_path IN (${
|
|
490
|
-
ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...
|
|
491
|
-
WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:b(r.symbol),depth:0}],o=r.enclosing_symbol,s=1,a=new Set([r.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!d)break;i.push({symbol:d.symbol,shortName:b(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=ge(r.symbol);if("kind"in c)return i;let l=c.descriptors;if(l.length<=1)return i;let u=[i[0]];for(let d=l.length-2,m=1;d>=0;d--,m++){let h=l.slice(0,d+1).map(g=>g.suffix==="method"?`${g.name}()`:g.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:h,shortName:h,depth:m})}return u}function li(e,t,n={}){let r=B(e,t);if(!r)return null;let i=n.semantic!==!1,o=Ue(e,r,{limit:50,semantic:i}),s=br(je(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i}));return{symbol:r.symbol,shortName:b(r.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:b(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:b(a.symbol),file:a.file}))}}function Ge(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function ye(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function Xt(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);let r=e.size+t.size-n;return r===0?0:n/r}function tp(e,t){if(e.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);return n/e.size}function lc(e,t){if(t<=0)return new Map;let n=new Map;for(let[r,i]of e)i>0&&n.set(r,Math.log(t/i));return n}function ui(e){let t=[...e.values()].sort((r,i)=>r-i);if(t.length===0)return 0;let n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function Bo(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function np(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??ui(n),c=[],l=[];for(let m of e){let f=n.get(m)??0;o+=f*f,t.has(m)&&(i+=f*f,f>=a?c.push(m):l.push(m))}if(c.length===0&&l.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let f=n.get(m)??0;s+=f*f}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?i/u:0;return c.sort((m,f)=>(n.get(f)??0)-(n.get(m)??0)),{similarity:d,significantShared:c,trivialShared:l}}function rp(e,t,n,r){let i=0,o=r.medianIdf??ui(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;i+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let c=r.magnitudeA*r.magnitudeB,l=c>0?i/c:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:l,significantShared:s,trivialShared:a}}function mi(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=vL(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!ce(o.symbol))return[];let s=bL(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):NL(e,t,{minSimilarity:r,limit:i})}function bL(e,t,n,r){let i=Ho(e,{minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=IL(t,i),s=SL(t,i),a=ui(s),c=Bo(t.callees,s),l=[];for(let u of o){if(u.callees.size<3)continue;let d=Bo(u.callees,s),m=sp(t,u,s,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:a,magnitudeA:c,magnitudeB:d});m&&l.push(m)}return l.sort((u,d)=>d.similarity-u.similarity),l}function SL(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return lc(n,t.corpus.length+1)}function sp(e,t,n,r){let i=r.magnitudeA===void 0||r.magnitudeB===void 0?np(e.callees,t.callees,n,{medianIdf:r.medianIdf}):rp(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB}),{similarity:o,significantShared:s,trivialShared:a}=i;if(o<r.minSimilarity)return null;let c=s.length+a.length;if(s.length<r.requireSignificantShared&&c<r.requireSharedCount)return null;let l=s.length>0?s:a,u=ap(l,"callees");return{symbolA:e.symbol,shortNameA:b(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:b(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:l.map(b),uniqueToA:[...ye(e.callees,t.callees)].map(b),uniqueToB:[...ye(t.callees,e.callees)].map(b),...u}}function Pt(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=Ho(e,{minCallees:o,scope:i,scanLimit:a,semantic:t.semantic!==!1}),l=c.corpus,u=[],d=0;for(let m=0;m<l.length;m+=1){let f=l[m],h=c.weightedMagnitudes[m],g=new Set;for(let y of f.callees){let S=c.candidateIndexesByCallee.get(y);if(S)for(let C of S)C>m&&g.add(C)}for(let y of g){let S=l[y];if(s&&f.file===S.file)continue;if(f.paramCount>=0&&S.paramCount>=0){let k=Math.abs(f.paramCount-S.paramCount),D=Math.max(2,Math.ceil(Math.max(f.paramCount,S.paramCount)*.5));if(k>D)continue}let C=sp(f,S,c.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:c.medianIdf,magnitudeA:h,magnitudeB:c.weightedMagnitudes[y]});C&&(xL(u,C,r,d),d+=1)}}return u.sort((m,f)=>f.result.similarity-m.result.similarity||m.order-f.order),u.map(m=>m.result)}function xL(e,t,n,r){if(n<=0)return;if(e.length<n){e.push({result:t,order:r});return}let i=0;for(let s=1;s<e.length;s+=1){let a=e[s],c=e[i];(a.result.similarity<c.result.similarity||a.result.similarity===c.result.similarity&&a.order>c.order)&&(i=s)}let o=e[i];t.similarity<=o.result.similarity||(e[i]={result:t,order:r})}var CL=["ScipDatabase#all","ScipDatabase#get","ScipDatabase#prepare","ScipDatabase#pathExclusionsFor","ScipDatabase#isIgnored","ScipDatabase#symbolNoiseFor","PerDbValue#get","PerDbValue#has",":storage:db:ScipDatabase:all",":storage:db:ScipDatabase:get",":storage:db:ScipDatabase:prepare",":storage:db:ScipDatabase:pathExclusionsFor",":storage:db:ScipDatabase:isIgnored",":storage:db:ScipDatabase:symbolNoiseFor",":storage:per-db-cache:PerDbValue:get",":storage:per-db-cache:PerDbValue:has"];function vL(e,t,n){let r=B(e,t),i=new T(e);if(!r)return null;let o=je(e,r,{semantic:n.semantic});return{symbol:r.symbol,file:r.relativePath,callees:Vo(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var RL=Y("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),kL=Y("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function wL(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=RL.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=a.get(c);return l||(l=DL(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,l)),i===void 0?l:l.filter(u=>u.symbol!==i)}function Ho(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=kL.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=s.get(a);return c||(c=LL(wL(e,{minCallees:n,scope:r,scanLimit:i,semantic:o})),s.set(a,c)),c}function LL(e){let t=new Map;for(let s of e)for(let a of s.callees)t.set(a,(t.get(a)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),r=lc(t,e.length),i=e.map(s=>Bo(s.callees,r)),o=new Map;for(let s=0;s<e.length;s+=1){let a=e[s];for(let c of a.callees){if((t.get(c)??0)>n)continue;let l=o.get(c);l||(l=[],o.set(c,l)),l.push(s)}}return{corpus:e,candidateIndexesByCallee:o,docFreq:t,idfWeights:r,weightedMagnitudes:i,medianIdf:ui(r),ubiquityThreshold:n}}function IL(e,t){let n=new Map;for(let r of e.callees)for(let i of t.candidateIndexesByCallee.get(r)??[]){let o=t.corpus[i];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function DL(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=new T(e),a=We(s.productionCallableDefinitions({scope:r,minLoc:5,sortByLocDesc:typeof i=="number"&&i>0}),i),c=s.calleeMap(a,{semantic:o});return a.map(l=>({symbol:l.symbol,file:l.relativePath,callees:Vo((c.get(l.symbolId)??[]).map(u=>u.symbol)),paramCount:s.callableSignature(l)?.paramCount??-1})).filter(l=>l.callees.size>=n)}function Vo(e){return new Set([...e].filter(t=>!PL(t)))}function PL(e){return CL.some(t=>e.includes(t))}function NL(e,t,n){let r=FL(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=HL(r,OL(e));for(let a of s){if(a.symbol===r.symbol||a.tokens.size<3)continue;let c=Ge(r.tokens,a.tokens);if(c.size<2)continue;let l=new Set([...r.tokens,...a.tokens]),u=l.size>0?c.size/l.size:0;u<i||o.push({symbolA:r.symbol,shortNameA:b(r.symbol),fileA:r.file,symbolB:a.symbol,shortNameB:b(a.symbol),fileB:a.file,similarity:u,similarityBasis:"source-tokens",sharedCallees:[...c].sort(),uniqueToA:[...ye(r.tokens,a.tokens)].sort(),uniqueToB:[...ye(a.tokens,r.tokens)].sort(),...ap([...c],"source-tokens")})}return o.sort((a,c)=>c.similarity-a.similarity||a.shortNameB.localeCompare(c.shortNameB)),o.slice(0,n.limit)}function ap(e,t){let n=e.flatMap(dc),r=e.flatMap(y=>ip(y,t)),i=uc(n,cp),o=uc(n,lp),s=uc(r,mc),a=[...new Set(r.filter(op))],c=e.filter(y=>{let S=ip(y,t);return S.some(C=>mc.has(C))&&S.some(op)}).length,l=[];i.length>0&&l.push(`access/query scaffolding: ${i.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(y=>up.has(y));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=i.length+o.length>0,f=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,h=f?"domain-behavior":d?m?"mixed":"domain-behavior":i.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";h==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=h==="domain-behavior"&&(e.length>=3||f)?"direct":"signal";return{evidenceClass:h,actionTier:g,evidenceClassReasons:l,recommendation:EL(h,g)}}function EL(e,t){return t==="direct"?"Shared domain behavior looks concrete; review for an extract/reuse opportunity.":e==="mixed"?"Shared evidence mixes domain behavior with scaffolding; review semantics before extracting anything.":e==="access-query-scaffolding"?"Shared evidence is mostly access/query scaffolding; compare product semantics before reusing code.":e==="structural-overlap"?"Shared structure has no domain or scaffolding classification; inspect names and behavior before reusing code.":"Shared evidence is mostly framework or generic scaffolding; treat as a contextual signal."}function uc(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function dc(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function ip(e,t){if(t==="source-tokens")return dc(e);let n=$(e);return dc(n.length>0?n:TL(e))}function TL(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(r=>r.trim()).filter(r=>/[A-Za-z]/.test(r)).at(-1)?.replace(/\.$/,"")??e}function op(e){return e.length>3&&!mc.has(e)&&!cp.has(e)&&!lp.has(e)&&!up.has(e)&&!_L.has(e)}var mc=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),cp=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),lp=new Set(["bytes","computed","crypto","describe","effect","expect","fetch","filter","hex","hook","json","map","mounted","on","promise","random","react","reduce","ref","render","state","test","token","trim","uuid","vue","watch"]),up=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),_L=new Set(["best","backend","conflict","database","effect","effects","error","errors","frontend","found","helpers","javascript","module","modules","scip","shared","source","typescript","utils","with","workflow","workflows"]);function FL(e,t){let n=B(e,t);if(!n||!ce(n.symbol))return null;let r=$L(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function $L(e,t){let n=$(t.symbol),r=dp(e,t.relativePath,t.startLine,t.endLine,n),i=mp(r,n);return i.size>0?i:null}var AL=Y("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),ML=Y("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function jL(e){return AL.get(e,()=>VL(e))}function OL(e){return ML.get(e,()=>BL(jL(e)))}function BL(e){let t=new Map;for(let i of e)for(let o of i.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),r=new Map;for(let i of e)for(let o of i.tokens){if((t.get(o)??0)>n)continue;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}return{corpus:e,candidateByToken:r,docFreq:t,ubiquityThreshold:n}}function HL(e,t){let n=new Map;for(let r of e.tokens)for(let i of t.candidateByToken.get(r)??[])i.symbol!==e.symbol&&n.set(i.symbol,i);return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function VL(e){return new T(e).productionCallableDefinitions().map(n=>({symbol:n.symbol,file:n.relativePath,tokens:mp(dp(e,n.relativePath,n.startLine,n.endLine,n.leaf),n.leaf)})).filter(n=>n.tokens.size>0)}function dp(e,t,n,r,i){let o=Qe(e,t);if(o.length===0)return"";if(r>=n&&r-n<=12)return o.slice(n,r+1).join(`
|
|
492
|
-
`);let
|
|
493
|
-
`)}return
|
|
494
|
-
`)}function mp(e,t){if(!e)return new Set;let n=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),r=qL(t),o=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(s=>s.trim()).filter(s=>s.length>1).filter(s=>!n.has(s)).filter(s=>!r.has(s));return new Set(o)}function qL(e){return new Set(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9_]+|_/).map(t=>t.toLowerCase()).filter(t=>t.length>1))}function UL(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function di(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ft(e){let t=[];if(e.filePattern){let n=e.profiles.find(r=>r.file.includes(e.filePattern));if(!n)return[];for(let r of e.profiles){if(r.file===n.file)continue;let i=e.compare(n,r);i&&t.push(i)}}else{let n=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let r=0;r<e.profiles.length;r+=1){for(let i=r+1;i<e.profiles.length;i+=1){let o=e.compare(e.profiles[r],e.profiles[i]);o&&t.push(o)}if(t.length>n)break}}return t.sort(e.sort??((n,r)=>r.similarity-n.similarity)),t.slice(0,e.limit)}function pc(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=WL(e,{scope:i,minDeps:s});return ft({profiles:a,limit:r,filePattern:o,overrunFactor:5,compare:(l,u)=>zL(l,u,n,c)})}function WL(e,t){let{scope:n,minDeps:r}=t,i=re(e,n),{universalDeps:o,distinctiveDeps:s}=GL(i),a=[];for(let[c,l]of i)l.size>=r&&a.push({file:c,deps:new Set([...l].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function GL(e){let t=new Set,n=new Set,r=e.size;if(r===0)return{universalDeps:t,distinctiveDeps:n};let i=new Map;for(let s of e.values())for(let a of s)i.set(a,(i.get(a)??0)+1);let o=Math.max(3,Math.ceil(r*.03));for(let[s,a]of i)a>=5&&a/r>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function zL(e,t,n,r){let i=new Set;for(let l of e.deps)t.deps.has(l)&&i.add(l);if(i.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let l of i)r.has(l)&&o++;if(o<2)return null;let s=Xt(e.deps,t.deps);if(s<n)return null;let a=[];for(let l of e.deps)t.deps.has(l)||a.push(l);let c=[];for(let l of t.deps)e.deps.has(l)||c.push(l);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...i],uniqueToA:a,uniqueToB:c}}function qo(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&pp(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)JL(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,pp(l.fallbackBucket,n,r));let i=t.length>0,o=n.length>0,s=r.length>0,a=i?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...r,...n].slice(0,6),recommendation:e.recommendation(a)}}function Uo(e,t){if(e.size===0||t.size===0)return 0;let r=Ge(e,t).size/Math.min(e.size,t.size);return Math.max(Xt(e,t),r)}function V(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function ve(e){return[...e].sort()}function JL(e,t,n,r,i,o){let s=[],a=[];for(let c of e)KL(c,r).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&i.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function KL(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let r of t)n=n.replace(r,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function pp(e,t,n){return e==="generic"?t:n}function Cn(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=er(e,{scope:o,minJsxTokens:r,scanLimit:s}).filter(l=>l.kind==="component").map(l=>({file:l.file,component:l.name,tokens:l.jsxTokens,profile:l}));return ft({profiles:c,limit:i,filePattern:a,compare:(l,u)=>XL(l,u,n),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.componentA.localeCompare(u.componentA)||l.fileB.localeCompare(u.fileB)||l.componentB.localeCompare(u.componentB)})}function XL(e,t,n){let r=Ge(e.tokens,t.tokens);if(r.size<6||!QL(r))return null;let i=Xt(e.tokens,t.tokens);return i<n?null:{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:i,sharedTokens:ve(r),sharedComponents:V(r,"component:"),sharedNativeTags:V(r,"native:"),sharedProps:V(r,"prop:"),sharedEvents:V(r,"event:"),sharedBindings:V(r,"binding:"),uniqueToA:ve(ye(e.tokens,t.tokens)).slice(0,25),uniqueToB:ve(ye(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function QL(e){let t=0,n=0;for(let r of e)r.startsWith("component:")&&(t+=1),(r.startsWith("prop:")||r.startsWith("event:")||r.startsWith("native:")||r.startsWith("jsx:"))&&(n+=1);return t>=1||n>=4}function vn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=er(e,{scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(l=>({file:l.file,component:l.name,tokens:l.behaviorTokens,profile:l}));return ft({profiles:c,limit:i,filePattern:a,compare:(l,u)=>YL(l,u,n,r),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.componentA.localeCompare(u.componentA)||l.fileB.localeCompare(u.fileB)||l.componentB.localeCompare(u.componentB)})}function YL(e,t,n,r){let i=Ge(e.tokens,t.tokens);if(i.size<r||!tI(i))return null;let o=Uo(e.tokens,t.tokens);if(o<n)return null;let s=V(i,"hook:"),a=V(i,"react-hook:"),c=V(i,"effect:"),l=V(i,"state:"),u=V(i,"request:"),d=V(i,"handler:"),m=V(i,"handler-verb:"),f=ZL({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,sharedTokens:ve(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:f.evidenceClass,actionTier:f.actionTier,evidenceClassReasons:f.reasons,recommendation:f.recommendation,uniqueToA:ve(ye(e.tokens,t.tokens)).slice(0,25),uniqueToB:ve(ye(t.tokens,e.tokens)).slice(0,25),reason:nI({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function ZL(e){return qo({genericWords:rI,stripPrefixes:iI,primitiveGroups:[{values:e.sharedReactHooks,reasonPrefix:"shared React primitives",bucket:"generic"},{values:e.sharedEffects,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedHooks,label:"shared hook",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedState,label:"shared state",fallbackBucket:"generic"},{names:e.sharedHandlers,label:"shared handler",fallbackBucket:"generic"},{names:e.sharedHandlerVerbs,label:"shared action verb",fallbackBucket:"generic"}],recommendation:eI})}function eI(e){switch(e){case"domain-behavior":return"Review for a shared hook, controller, or feature module around the named domain behavior.";case"mixed":return"Separate generic React mechanics from domain-specific behavior before extracting a shared hook.";case"shared-abstraction":return"Review the existing shared hook usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct hook-extraction evidence."}}function tI(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("hook:")?t+=1:u.startsWith("react-hook:")?n+=1:u.startsWith("effect:")?r+=1:u.startsWith("request:")?i+=1:u.startsWith("handler:")||u.startsWith("handler-verb:")?o+=1:u.startsWith("state:")?s+=1:u.startsWith("state-hook:")&&(a+=1);let c=s+a,l=t+n+r+i+o+c;return i>=1&&l>=4||t>=1&&(i>=1||s>=1||o>=2)&&l>=5||s>=1&&o>=2&&(r>=1||n>=2)&&l>=5}function nI(e){let t=[];return e.sharedHooks.length&&t.push(`shared hooks: ${e.sharedHooks.join(", ")}`),e.sharedReactHooks.length&&t.push(`shared React hooks: ${e.sharedReactHooks.join(", ")}`),e.sharedEffects.length&&t.push(`shared effects: ${e.sharedEffects.join(", ")}`),e.sharedState.length&&t.push(`shared state: ${e.sharedState.join(", ")}`),e.sharedRequests.length&&t.push(`shared requests: ${e.sharedRequests.join(", ")}`),e.sharedHandlers.length&&t.push(`shared handlers: ${e.sharedHandlers.slice(0,6).join(", ")}`),e.sharedHandlerVerbs.length&&t.push(`shared action verbs: ${e.sharedHandlerVerbs.slice(0,6).join(", ")}`),t.join("; ")||"shared React behavior profile"}var rI=new Set(["add","apply","async","callback","cancel","change","clear","close","create","data","delete","draft","edit","effect","error","fetch","filter","form","handle","has","is","item","items","load","loader","loading","memo","name","open","reducer","refresh","ref","remove","request","reset","resource","row","rows","save","saving","search","select","selected","state","store","submit","toggle","update","use","value"]),iI=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function pi(e,t={}){let{minComponentLines:n=300,minFileLines:r=800,minJsxTokens:i=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return er(e,{scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>oI(d,{minComponentLines:n,minFileLines:r,minJsxTokens:i,minBehaviorTokens:o})).filter(d=>d!==null).sort((d,m)=>m.componentLines-d.componentLines||m.fileLines-d.fileLines||d.file.localeCompare(m.file)).slice(0,s)}function oI(e,t){let n=[];e.loc>=t.minComponentLines&&n.push(`${e.loc} component line(s)`);let r=Math.max(80,Math.floor(t.minComponentLines/2));if(e.fileLines>=t.minFileLines&&e.loc>=r&&n.push(`${e.fileLines} file line(s)`),e.jsxTokens.size>=t.minJsxTokens&&n.push(`${e.jsxTokens.size} JSX structure token(s)`),e.behaviorTokens.size>=t.minBehaviorTokens&&n.push(`${e.behaviorTokens.size} behavior token(s)`),n.length===0)return null;let i=sI(e),o=aI(e,t,i),s=cI(e),a=lI(i,o,s);return{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:i,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:uI(a,s),reasons:n,loc:e.loc}}function sI(e){let t=[{axis:"component",value:e.loc},{axis:"file",value:e.fileLines},{axis:"jsx-structure",value:e.jsxTokens.size*3},{axis:"hook-behavior",value:e.behaviorTokens.size*4}];return t.sort((n,r)=>r.value-n.value),t[0]?.axis??"component"}function aI(e,t,n){let r=[];e.loc>=t.minComponentLines&&r.push("component");let i=Math.max(80,Math.floor(t.minComponentLines/2));return e.fileLines>=t.minFileLines&&e.loc>=i&&r.push("file"),e.jsxTokens.size>=t.minJsxTokens&&r.push("jsx-structure"),e.behaviorTokens.size>=t.minBehaviorTokens&&r.push("hook-behavior"),[...new Set(r.length>0?r:[n])]}function cI(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(l=>l.toLowerCase()),r=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),i=`${r} ${e.name}`.split(/[^A-Za-z0-9]+/).filter(Boolean).map(l=>l.toLowerCase()),o=n.findIndex(l=>mI.has(l)),s=o>=0&&n.slice(o+1).some(l=>dI.has(l)),a=fp(r)||fp(e.name);return/(?:Page|Route|Screen|View)$/.test(r)||/(?:Page|Route|Screen|View)$/.test(e.name)||i.some(l=>pI.has(l))||o>=0&&!s&&!a?"route-page":"component"}function fp(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&gp.has(t.at(-1))?!0:[...gp].some(n=>e.endsWith(fI(n)))}function lI(e,t,n){return e==="hook-behavior"?"behavior-extraction":n==="route-page"?"route-page-decomposition":t.includes("hook-behavior")?"behavior-extraction":t.includes("jsx-structure")?"jsx-decomposition":t.includes("file")?"file-decomposition":e==="jsx-structure"?"jsx-decomposition":e==="file"&&!t.includes("component")?"file-decomposition":"component-decomposition"}function uI(e,t){switch(e){case"behavior-extraction":return"Extract independent state, effects, requests, or handlers into hooks, controllers, or feature modules.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"jsx-decomposition":return t==="route-page"?"Split page JSX into named layout sections before extracting behavior.":"Split repeated JSX sections into named presentational components.";case"file-decomposition":return"Review file-level decomposition; split colocated panels or helpers before changing behavior.";case"component-decomposition":return"Review component boundaries around props, state ownership, and independently changing UI sections."}}var dI=new Set(["component","components","panel","panels","partial","partials"]),gp=new Set(["banner","button","card","dialog","drawer","filter","form","grid","header","item","list","menu","modal","nav","panel","picker","rail","row","section","selector","shell","sidebar","table","toolbar"]),mI=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),pI=new Set(["landing","page","route","screen","view"]);function fI(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Rn(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=gI(e,{scope:o,minTokens:r,scanLimit:s});return ft({profiles:c,limit:i,filePattern:a,compare:(l,u)=>yI(l,u,n),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.fileB.localeCompare(u.fileB)})}function gI(e,t){return Zn(e,{scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:hI(n)}))}function hI(e){return e.totalLines}function yI(e,t,n){let r=Ge(e.tokens,t.tokens);if(r.size<6||!bI(r))return null;let i=Xt(e.tokens,t.tokens);return i<n?null:{fileA:e.file,fileB:t.file,similarity:i,sharedTokens:ve(r),sharedComponents:V(r,"component:"),sharedProps:V(r,"prop:"),sharedEvents:V(r,"event:"),sharedDirectives:V(r,"directive:"),sharedSlots:V(r,"slot:"),sharedIdentifiers:V(r,"id:"),uniqueToA:ve(ye(e.tokens,t.tokens)).slice(0,25),uniqueToB:ve(ye(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function bI(e){let t=0,n=0;for(let r of e)r.startsWith("component:")&&(t+=1),(r.startsWith("prop:")||r.startsWith("event:")||r.startsWith("directive:")||r.startsWith("slot:"))&&(n+=1);return t>=1||n>=3}function kn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=Zn(e,{scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(l=>({file:l.file,tokens:l.behaviorTokens,profile:l}));return ft({profiles:c,limit:i,filePattern:a,compare:(l,u)=>SI(l,u,n,r),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.fileB.localeCompare(u.fileB)})}function SI(e,t,n,r){let i=Ge(e.tokens,t.tokens);if(i.size<r||!vI(i))return null;let o=Uo(e.tokens,t.tokens);if(o<n)return null;let s=V(i,"composable:"),a=V(i,"store:"),c=V(i,"reactivity:"),l=V(i,"lifecycle:"),u=V(i,"request:"),d=V(i,"function:"),m=V(i,"function-verb:"),f=V(i,"template-binding:"),h=V(i,"template-event:"),g=xI({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:h});return{fileA:e.file,fileB:t.file,similarity:o,sharedTokens:ve(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:h,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:ve(ye(e.tokens,t.tokens)).slice(0,25),uniqueToB:ve(ye(t.tokens,e.tokens)).slice(0,25),reason:RI({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function xI(e){return qo({genericWords:kI,primitiveGroups:[{values:e.sharedReactivity,reasonPrefix:"shared reactivity primitive",bucket:"generic"},{values:e.sharedLifecycle,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedComposables,label:"shared composable",fallbackBucket:"shared-abstraction"},{names:e.sharedStores,label:"shared store",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedFunctions,label:"shared function",fallbackBucket:"generic"},{names:e.sharedFunctionVerbs,label:"shared action verb",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"},{names:e.sharedTemplateEvents,label:"shared template event",fallbackBucket:"generic"}],recommendation:CI})}function CI(e){switch(e){case"domain-behavior":return"Review for a shared composable, store, or feature module around the named domain behavior.";case"mixed":return"Separate generic Vue mechanics from domain-specific behavior before extracting a composable.";case"shared-abstraction":return"Review the existing composable/store usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct composable-extraction evidence."}}function vI(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("composable:")?t+=1:u.startsWith("store:")?n+=1:u.startsWith("request:")?r+=1:u.startsWith("lifecycle:")?i+=1:u.startsWith("function:")?o+=1:u.startsWith("reactivity:")?s+=1:(u.startsWith("function-verb:")||u.startsWith("template-binding:")||u.startsWith("template-event:"))&&(a+=1);let c=t+n,l=c+r+i+o+a;return r>=1&&l>=4||i>=1&&o>=2&&l>=4||c>=2&&(r>=1||o>=2)&&l>=5||o>=2&&s>=1&&l>=4}function RI(e){let t=[];return e.sharedComposables.length&&t.push(`shared composables: ${e.sharedComposables.join(", ")}`),e.sharedStores.length&&t.push(`shared stores: ${e.sharedStores.join(", ")}`),e.sharedRequests.length&&t.push(`shared request helpers: ${e.sharedRequests.join(", ")}`),e.sharedLifecycle.length&&t.push(`shared lifecycle: ${e.sharedLifecycle.join(", ")}`),e.sharedFunctions.length&&t.push(`shared functions: ${e.sharedFunctions.slice(0,6).join(", ")}`),e.sharedFunctionVerbs.length&&t.push(`shared action verbs: ${e.sharedFunctionVerbs.slice(0,6).join(", ")}`),e.sharedBindings.length&&t.push(`shared template bindings: ${e.sharedBindings.slice(0,6).join(", ")}`),t.join("; ")||"shared Vue behavior profile"}var kI=new Set(["add","apply","cancel","change","clear","close","composable","create","data","delete","draft","edit","error","fetch","filter","form","item","items","load","loading","name","open","reactive","ref","refresh","remove","request","reset","resource","row","rows","save","saving","search","select","selected","store","submit","toggle","update","use","value","watch"]);function fi(e,t={}){let{minTotalLines:n=800,minTemplateLines:r=300,minScriptLines:i=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return Zn(e,{scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>wI(d,{minTotalLines:n,minTemplateLines:r,minScriptLines:i,minStyleLines:o})).filter(d=>d!==null).sort((d,m)=>m.totalLines-d.totalLines||d.file.localeCompare(m.file)).slice(0,s)}function wI(e,t){let n=[];if(e.totalLines>=t.minTotalLines&&n.push(`${e.totalLines} total component line(s)`),e.templateLines>=t.minTemplateLines&&n.push(`${e.templateLines} template line(s)`),e.scriptLines>=t.minScriptLines&&n.push(`${e.scriptLines} script line(s)`),e.styleLines>=t.minStyleLines&&n.push(`${e.styleLines} style line(s)`),n.length===0)return null;let r=LI(e),i=II(e,t,r),o=DI(e.file),s=PI(r,o);return{file:e.file,totalLines:e.totalLines,sfcLines:e.sfcLines,templateLines:e.templateLines,scriptLines:e.scriptLines,styleLines:e.styleLines,externalScriptLines:e.externalScriptLines,externalScriptPaths:e.externalScriptPaths,customBlockLines:e.customBlockLines,dominantPressure:r,pressureKinds:i,contextKind:o,recommendationKind:s,recommendation:NI(s,o),reasons:n,loc:e.totalLines}}function LI(e){let t=[{axis:"template",lines:e.templateLines},{axis:"script",lines:e.scriptLines-e.externalScriptLines},{axis:"style",lines:e.styleLines},{axis:"external-script",lines:e.externalScriptLines},{axis:"custom-block",lines:e.customBlockLines}];return t.sort((n,r)=>r.lines-n.lines),t[0]?.lines?t[0].axis:"total"}function II(e,t,n){let r=[];return e.totalLines>=t.minTotalLines&&(r.push("total"),n!=="total"&&r.push(n)),e.templateLines>=t.minTemplateLines&&r.push("template"),e.scriptLines>=t.minScriptLines&&r.push("script"),e.styleLines>=t.minStyleLines&&r.push("style"),(e.externalScriptLines>=t.minScriptLines||n==="external-script")&&r.push("external-script"),e.customBlockLines>0&&n==="custom-block"&&r.push("custom-block"),[...new Set(r.length>0?r:[n])]}function DI(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>EI.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function PI(e,t){return e==="style"?"style-decomposition":e==="template"?"template-decomposition":e==="external-script"?"external-script-boundary":e==="custom-block"?"custom-block-review":t==="route-page"?"route-page-decomposition":e==="script"?"script-behavior-extraction":"total-size-review"}function NI(e,t){switch(e){case"template-decomposition":return t==="route-page"?"Split route template sections into named panels before extracting script behavior.":"Split repeated template sections into named presentational components.";case"script-behavior-extraction":return"Extract independent script behavior into composables, controllers, or feature modules.";case"style-decomposition":return"Review UI/style decomposition; move repeated styling to component or style primitives, not composables.";case"external-script-boundary":return"Review the external script boundary and split controller/composable modules by workflow.";case"custom-block-review":return"Review custom block ownership before splitting template or script code.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"total-size-review":return"Review the largest block first, then split by the dominant reason to change."}}var EI=new Set(["landing","page","pages","route","routes","view","views"]);function fc(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=re(e,i),c=OI(a,o,s);if(c.length===0)return[];let l=TI(c);return l.length<2?[]:jI($I(l,n,r),r)}function TI(e){let t=_I(e),n=[];for(let r of e){let i=r.filter(o=>!t.has(o));i.length>=2&&n.push({original:r,filtered:i})}return n}function _I(e){let{nodeFreq:t,tailFreq:n}=FI(e),r=e.length*.9,i=e.length*.8,o=new Set;for(let[a,c]of t)c>r&&o.add(a);for(let[a,c]of n)c>i&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let c=a.split("/").pop()??"";s.includes(c)&&o.add(a)}return o}function FI(e){let t=new Map,n=new Map;for(let r of e){let i=new Set;for(let o of r)i.has(o)||(t.set(o,(t.get(o)??0)+1),i.add(o));for(let o=Math.max(0,r.length-2);o<r.length;o++)n.set(r[o],(n.get(r[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function $I(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=AI(e[i],e[o],t);s&&r.push(s)}if(r.length>n*10)break}return r.sort((i,o)=>Math.abs(o.similarity-i.similarity)>.01?o.similarity-i.similarity:i.divergencePoints.length-o.divergencePoints.length),r}function AI(e,t,n){if(!MI(e.filtered,t.filtered))return null;let{distance:r,ops:i}=BI(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-r/o;if(s<n||r===0)return null;let a=i.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||i.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:r,divergencePoints:a,commonPrefix:HI(e.original,t.original),commonSuffix:VI(e.original,t.original)}}function MI(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function jI(e,t){let n=[];for(let r of e)if(n.some(o=>hp(r.chainA,o.chainA)&&hp(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function OI(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;yp(e,o,[o],new Set([o]),t,n,r,500)}return r}function yp(e,t,n,r,i,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=i&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=i&&s.push([...n]);return}let l=!1;for(let u of c)if(!r.has(u)&&(r.add(u),n.push(u),yp(e,u,n,r,i,o,s,a),n.pop(),r.delete(u),l=!0,s.length>=a))return;!l&&n.length>=i&&s.push([...n])}function BI(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let c=0;c<=n;c++)i[c][0]=c;for(let c=0;c<=r;c++)i[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=r;l++)e[c-1]===t[l-1]?i[c][l]=i[c-1][l-1]:i[c][l]=1+Math.min(i[c-1][l],i[c][l-1],i[c-1][l-1]);let o=[],s=n,a=r;for(;s>0||a>0;)s>0&&a>0&&e[s-1]===t[a-1]?(o.unshift({type:"match",indexA:s-1,indexB:a-1}),s--,a--):s>0&&a>0&&i[s][a]===i[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&i[s][a]===i[s][a-1]+1?(o.unshift({type:"insert",indexA:s,indexB:a-1}),a--):(o.unshift({type:"delete",indexA:s-1,indexB:a}),s--);return{distance:i[n][r],ops:o}}function HI(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}function VI(e,t){let n=[],r=e.length-1,i=t.length-1;for(;r>=0&&i>=0&&e[r]===t[i];)n.unshift(e[r]),r--,i--;return n}function hp(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function ze(e){let t=e.orderCandidates?[...e.candidates()].sort(e.orderCandidates):e.candidates(),n=We(t,e.scanLimit),r=e.prepare?.(n)??void 0,i=[];for(let o of n){let s=e.evaluate(o,r);s&&i.push(s)}return e.orderResults&&i.sort(e.orderResults),typeof e.limit=="number"?i.slice(0,e.limit):i}function wn(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new T(e);return ze({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>qI(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function qI(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=JI(r,t),o=KI(r,i);if(o.length<2)return null;let s=XI(o,i);if(s.length===0)return null;let a=b(e.symbol),c=UI(a,r.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:q(e),totalCallees:r.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function UI(e,t,n,r){let i=Math.max(...r.map(c=>c.callees.length)),o=Math.max(...r.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${r.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${i} callees at ${Math.round(o*100)}% isolation`],a=WI(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:i>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function WI(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let r=GI(e);return zI.has(r)?`caller verb suggests orchestration: ${r}`:null}function GI(e){return e.split(":").pop()?.replace(/\(\)$/,"").replace(/[^A-Za-z0-9_]/g,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\s-]+/).filter(Boolean)[0]?.toLowerCase()??""}var zI=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function JI(e,t){let n=new Map;for(let i of e)n.set(i,new Set);let r=new Map;for(let i of t){let o=r.get(i.chunkId);o||(o=new Set,r.set(i.chunkId,o)),o.add(i.symbol)}for(let i of r.values()){let o=[...i];for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++)n.get(o[s]).add(o[a]),n.get(o[a]).add(o[s])}return n}function KI(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=new Set,s=[i];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let c of t.get(a)??[])n.has(c)||s.push(c)}}r.push(o)}return r}function XI(e,t){return e.filter(n=>n.size>=3).map(n=>QI(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function QI(e,t,n){let r=new Set;for(let a of t)if(a!==e)for(let c of a)r.add(c);let i=0;for(let a of e)for(let c of n.get(a)??[])r.has(c)&&i++;let o=e.size*r.size,s=o>0?1-i/o:1;return{callees:[...e].map(b),isolation:s}}import{posix as Sr}from"path";var YI=U("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]});function Ln(e,t,n){return e.callerFileMap(t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function Wo(e,t,n){let r=[],i=0,o=0,s=$(t.symbol);for(let a of n)iD(e,a,t.relativePath,s)?i++:gc(e,a,s)?o++:r.push(a);return{realConsumers:r,barrelConsumers:i,importOnlyConsumers:o}}function gc(e,t,n){if(!n)return!1;let r=W(t);if(!r)return!1;let i=YI.get(e,t,()=>ZI(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function ZI(e,t,n){let r=F(e,t);if(!r)return tD();let i=Ye(e,t,r),o=Mt(e,"consumer-file-usage",t,i);if(o){let a=rD(o);if(a)return a}let s=eD(e,t,n);return jt(e,"consumer-file-usage",t,i,nD(s)),s}function eD(e,t,n){let r=new Set,i=new Set,o=fe(e,t);if(!o)return{importedLeaves:r,usedLeaves:i};let s=n==="rust"?new Set(["use_declaration"]):n==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),a=(c,l)=>{let u=l||s.has(c.type);(c.type==="identifier"||c.type==="type_identifier"||c.type==="property_identifier"||c.type==="field_identifier")&&(u?r.add(c.text):i.add(c.text));for(let d of c.children)a(d,u)};return a(o.rootNode,!1),{importedLeaves:r,usedLeaves:i}}function tD(){return{importedLeaves:new Set,usedLeaves:new Set}}function nD(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function rD(e){try{let t=JSON.parse(e);return!Array.isArray(t.importedLeaves)||!Array.isArray(t.usedLeaves)?null:{importedLeaves:new Set(t.importedLeaves.filter(n=>typeof n=="string")),usedLeaves:new Set(t.usedLeaves.filter(n=>typeof n=="string"))}}catch{return null}}function iD(e,t,n,r){if(!r)return!1;let i=Qe(e,t);if(i.length===0)return!1;let o=Jr(e,t);if(o.length===0)return!1;let s=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`\\b${s}\\b`),c=0;for(let l=0;l<i.length;l++){if(!a.test(i[l]??""))continue;if(c++,!o.find(d=>d.startLine<=l&&l<=d.endLine))return!1}return c>0}var oD=20,sD=1,aD=new Map([["app","app"],["apps","app"],["component","component"],["components","component"],["composable","composable"],["composables","composable"],["contract","contract"],["contracts","contract"],["domain","domain"],["domains","domain"],["feature","feature"],["features","feature"],["hook","hook"],["hooks","hook"],["lib","library"],["module","module"],["modules","module"],["package","package"],["packages","package"],["page","page"],["pages","page"],["route","route"],["routes","route"],["screen","screen"],["screens","screen"],["service","service"],["services","service"],["shared","shared"],["src","source-root"],["store","state"],["stores","state"],["test","test"],["tests","test"],["util","utility"],["utils","utility"],["view","view"],["views","view"]]),cD=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),lD=new Set(["access","api","auth","config","db","effect","errors","hooks","lib","middleware","permissions","routes","schemas","servicetasks","services","startup","store","stores","test-utils","repository","repositories","tests","types","ui","utils","workflow","workflows"]);function Sc(e,t={}){let n=bc(t.limit,oD),r=bc(t.minConsumers,sD),i=new T(e),o=i.fileDependencyGraph(t.scope),s=PD(j(e,{includeIgnored:!1})),a=TD(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?uD(e,i,t.target):dD(e,t.scope,t.scanLimit)).map(u=>mD(i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(DD).slice(0,n)}function uD(e,t,n){let r=gD(e,n);if(r)return[vp(r)];let i=B(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[hD(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:b(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function dD(e,t,n){let r=j(e,{scope:t,includeIgnored:!1}),i=bc(n,r.length);return r.slice(0,i).map(o=>vp(o))}function mD(e,t,n,r,i,o){let s=n.definition?pD(e,n.definition,r.semantic):fD(t,n.unit.file),a=n.definition?s.length>0?"exact":"none":s.length>0?"file-level":"none",c=n.unit.file,l=rt(Sr.dirname(c)),u=bD(s),d=yD(l),m=vc([...bp(l),...u?bp(u):[]]),f=SD(n.unit,l,u,s),h=xD(f,n.unit,l,u,s,i,o),g=wD(n.unit,a,u,s,l,h.whyNoSuggestedHome),y=LD(n.unit,l,u,s,h.suggestedHome,h.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:n.unit,candidatePath:c,currentDirectory:l,directoryAncestry:d,consumerFiles:s,consumerCoverage:a,nearestCommonOwner:u,boundaryMarkers:m,recommendedTier:f,suggestedHome:h.suggestedHome,destinationConfidence:h.confidence,whyNoSuggestedHome:h.whyNoSuggestedHome,counterevidence:g,reasons:y,recommendation:ID(f,h.suggestedHome,a)}}function pD(e,t,n){let r=Ln(e,[t],{semantic:n!==!1,sourceFallback:!0});return Ip(r.get(t.symbolId)??[])}function fD(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return Ip(n)}function gD(e,t){let n=Cc(t),r=j(e,{includeIgnored:!1}),i=r.find(s=>s===n);if(i)return i;let o=r.find(s=>s.endsWith(`/${n}`));return o||(r.find(s=>s.includes(n))??null)}function hD(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:b(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function vp(e){return{unit:{kind:"file",file:e,shortName:Sr.basename(e)}}}function yD(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let r=0;r<n.length;r+=1){let i=n.slice(0,r+1).join("/");t.push({path:i,depth:r,markers:xc(i)})}return t}function bp(e){return e==="."?[]:Rp(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function xc(e){return vc(Rp(e).map(({marker:t})=>t))}function Rp(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=aD.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function bD(e){if(e.length===0)return null;let t=e.map(r=>rt(Sr.dirname(r))),n=t[0].split("/").filter(Boolean);for(let r of t.slice(1)){let i=r.split("/").filter(Boolean),o=[],s=Math.min(n.length,i.length);for(let a=0;a<s&&n[a]===i[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function SD(e,t,n,r){return n?e.kind==="symbol"&&r.length===1?r[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":xp(n,"package")?"package-level-shared":xp(n,"app")?"app-level-shared":Cp(n,["feature","domain","module"])||Cp(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function xD(e,t,n,r,i,o,s){let a=CD(e,r);if(a)return Qt(a);let c=ND(t.file),l=vD(e,n,c,i,s);if(l)return l;let u=r;if(rt(n)===rt(u))return Qt(`${n} is already the nearest common owner for its consumers.`);let d=RD(u,n,c,s);return d||kD(u,n,c,o,s)}function CD(e,t){return t?e==="no-exact-consumers"||e==="repository-level-review"?"The inferred owner is too broad or unsupported for an exact destination.":null:"No consumer owner could be inferred from the current index."}function vD(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?hc(o):Qt("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=rt(Sr.dirname(r[0])),s=Lp(t,n,o,i);return s?Qt(s):hc(o)}return null}function RD(e,t,n,r){return FD(e)?kp(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function kD(e,t,n,r,i){if(e===".")return Qt("The nearest common owner is the repository root.");let o=`${e}/shared`,s=kp(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:Qt(`${o} does not exist in the indexed project.`)}function kp(e,t,n,r,i){if(!wp(e,n))return Qt(i);let o=Lp(t,n,e,r);return o?Qt(o):hc(e)}function hc(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function Qt(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function wD(e,t,n,r,i,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),r.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&i.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function LD(e,t,n,r,i,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${r.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),i?s.push(`Suggested home is ${i}.`):o&&s.push(`No exact suggested home: ${o}`),s}function ID(e,t,n){return e==="no-exact-consumers"?"Review references before moving; no consumers were found.":e==="repository-level-review"?"Keep this as a broad locality signal; the inferred owner is too general for automatic relocation.":t?`Review whether ${n==="exact"?"symbol usage":"module import"} supports moving or extracting toward ${t}.`:"Review ownership manually before changing structure."}function DD(e,t){return Sp(t)-Sp(e)||e.candidatePath.localeCompare(t.candidatePath)}function Sp(e){let t=e.consumerFiles.length*10;return e.consumerCoverage==="exact"&&(t+=5),e.suggestedHome&&(t+=3),e.recommendedTier==="repository-level-review"&&(t-=8),e.recommendedTier==="no-exact-consumers"&&(t-=12),t}function PD(e){let t=new Set(["."]);for(let n of e){let r=rt(Sr.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=rt(Sr.dirname(r))}return t}function ND(e){let t=yc(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function wp(e,t){let n=rt(e),r=rt(t);return r==="."||n===r||n.startsWith(`${r}/`)}function ED(e,t,n){let r=yc(e),i=yc(t);return(wp(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function Lp(e,t,n,r){return rt(e)===rt(n)||!ED(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function TD(...e){let t=new Set(lD);for(let n of e)for(let r of n??[]){let i=_D(r);i&&t.add(i)}return t}function _D(e){let t=e.trim().toLowerCase();return t===""?null:t}function xp(e,t){return xc(e).includes(t)}function Cp(e,t){let n=xc(e);return t.some(r=>n.includes(r))}function FD(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?cD.has(n):!1}function Cc(e){return e.replaceAll("\\","/").replace(/^\.\//,"")}function rt(e){let t=Cc(e);return t===""?".":t}function yc(e){let t=Cc(e);return t==="."?[]:t.split("/").filter(Boolean)}function bc(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function Ip(e){return vc([...e]).sort((t,n)=>t.localeCompare(n))}function vc(e){return[...new Set(e)]}function gi(e,t,n={}){let{maxDepth:r=5,scope:i}=n,o=B(e,t);if(!o)return[];let s=[],a=new Set([o.symbolId]),c=new Set,l=[o];for(let u=1;u<=r&&l.length!==0;u++){let d=[];for(let m of l)for(let f of $D(e,m,i)){let h=`${f.file}|${f.shortName}`;if(f.symbolId!==null){if(a.has(f.symbolId))continue;a.add(f.symbolId)}else if(c.has(h))continue;c.add(h),s.push({symbol:f.symbol,shortName:f.shortName,file:f.file,depth:u}),f.symbolId!==null&&f.symbolMatch&&d.push(f.symbolMatch)}l=d}return s.sort((u,d)=>u.depth-d.depth||u.file.localeCompare(d.file)),s}function $D(e,t,n){let r=Ue(e,t,{limit:500}).filter(l=>!e.isIgnored(l.file)).filter(l=>!n||l.file.includes(n)),i=new Set(r.map(l=>l.file)),o=[];for(let l of AD(e,t,n)){if(i.has(l))continue;let u=z(e,l),d=u.length>0?Be(u,u[0].startLine):null;o.push({symbol:d?.symbol??l,file:l})}let s=[...r,...o],a=[],c=new Set;for(let l of s){let u=sr(e,l.symbol);if(!u){let m=`${l.file}|${l.symbol}`;if(c.has(m))continue;c.add(m),a.push({symbolId:null,symbol:l.symbol,shortName:b(l.symbol),file:l.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!MD(u.symbol))continue;let d=`${u.symbolId}|${u.relativePath}`;c.has(d)||(c.add(d),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:b(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function AD(e,t,n){let r=n?"AND consumer_d.relative_path LIKE ?":"",i=[t.symbolId,t.documentId];return n&&i.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
540
|
+
AND d.relative_path IN (${r})
|
|
541
|
+
ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...i))}return n}function $p(e){let t=[];for(let n=0;n<e.length;n+=Ap)t.push(e.slice(n,n+Ap));return t}function IL(e){return{symbol:e.symbol,kind:e.kind,documentation:e.documentation,enclosing_symbol:e.enclosingSymbol,relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine}}function Mp(e){return e.kind!==null&&e.kind!==0?LL(e.kind,e.symbol,e.documentation):DL(e.symbol,e.documentation,e.enclosing_symbol)}function LL(e,t,n){let i=(n??"").toLowerCase();if(ee(t)==="type"){if(i.includes("type "))return 76;if(i.includes("interface "))return 27;if(i.includes("struct "))return 68;if(i.includes("trait "))return 73;if(i.includes("class "))return 9}return e}function DL(e,t,n){let i=we(e);if("kind"in i)return null;let r=i.descriptors,o=r[r.length-2]??null,s=ee(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?76:a.includes("interface ")?27:a.includes("struct ")?68:a.includes("trait ")?73:(a.includes("class "),9):s==="method"?o?.suffix==="type"?33:23:s==="namespace"?39:s!=="term"?null:a.includes("async def ")||a.includes("def ")?23:(n?ee(n):o?.suffix??null)==="type"?21:83}function wc(e,t={}){let{limit:n=10,scope:i,minDepth:r=3}=t,o=pe(e,i),s=new Map,a=[],c=new Map,l=new Map,u=new Set,d=[],m=0;for(let b of o.keys()){if(c.has(b))continue;let C=[],D=(o.get(b)??new Set).values();for(c.set(b,m),l.set(b,m),m+=1,d.push(b),u.add(b),C.push({node:b,iter:D,pendingChild:null});C.length>0;){let w=C[C.length-1];if(w.pendingChild!==null){let Re=w.pendingChild;w.pendingChild=null,l.set(w.node,Math.min(l.get(w.node),l.get(Re)))}let j=w.iter.next();if(j.done){if(l.get(w.node)===c.get(w.node)){let Re=[];for(;;){let ie=d.pop();if(u.delete(ie),Re.push(ie),s.set(ie,a.length),ie===w.node)break}a.push(Re)}C.pop();continue}let J=j.value;if(c.has(J))u.has(J)&&l.set(w.node,Math.min(l.get(w.node),c.get(J)));else{c.set(J,m),l.set(J,m),m+=1,d.push(J),u.add(J);let Re=(o.get(J)??new Set).values();w.pendingChild=J,C.push({node:J,iter:Re,pendingChild:null})}}}let p=new Map,f=new Array(a.length);for(let b=0;b<a.length;b++)f[b]=a[b].length,p.set(b,new Set);for(let[b,C]of o){let D=s.get(b);for(let w of C){let j=s.get(w);j!==D&&p.get(D).add(j)}}let g=new Array(a.length),y=new Array(a.length);for(let b=0;b<a.length;b++){let C=[],D=0;for(let w of p.get(b)){let j=y[w];j>D&&(D=j,C=g[w])}g[b]=[b,...C],y[b]=f[b]+D}function S(b){return g[b]}let R=a.map(b=>[...b].sort()),k=new Set,x=[];for(let b=0;b<a.length;b++){let C=S(b),D=[];for(let j of C)D.push(...R[j]);if(D.length<r)continue;let w=D.join(" ");k.has(w)||(k.add(w),x.push(PL(D)))}return x.sort((b,C)=>C.depth-b.depth),NL(x).slice(0,n)}function PL(e){return{chain:e,depth:e.length,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${e.length} file(s) form the representative transitive dependency path`,"cycles are condensed before longest-path calculation"],recommendation:"Review whether the chain crosses ownership or layer boundaries; shorten it only when the dependency direction is accidental."}}function NL(e){let t=[];for(let n of e)t.some(i=>EL(n.chain,i.chain))||t.push(n);return t}function EL(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let i=0;i<e.length;i++)if(e[i]!==t[n+i])return!1;return!0}function Ic(e,t){let n=V(e,t);if(!n)return[];let i=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
|
|
542
|
+
WHERE id = ? LIMIT 1`,n.symbolId);if(!i)return[];let r=[{symbol:i.symbol,shortName:v(i.symbol),depth:0}],o=i.enclosing_symbol,s=1,a=new Set([i.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!d)break;r.push({symbol:d.symbol,shortName:v(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(r.length>1)return r;let c=we(i.symbol);if("kind"in c)return r;let l=c.descriptors;if(l.length<=1)return r;let u=[r[0]];for(let d=l.length-2,m=1;d>=0;d--,m++){let f=l.slice(0,d+1).map(g=>g.suffix==="method"?`${g.name}()`:g.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:f,shortName:f,depth:m})}return u}function Ir(e,t,n={}){let i=V(e,t);if(!i)return null;let r=n.semantic!==!1,o=tt(e,i,{limit:50,semantic:r}),s=Di(Ge(e,i,{limit:50,additive:!0,callableOnly:!0,semantic:r}));return{symbol:i.symbol,shortName:v(i.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:v(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:v(a.symbol),file:a.file}))}}function nt(e,t){let n=new Set;for(let i of e)t.has(i)&&n.add(i);return n}function Le(e,t){let n=new Set;for(let i of e)t.has(i)||n.add(i);return n}function tn(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);let i=e.size+t.size-n;return i===0?0:n/i}function Op(e,t){if(e.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);return n/e.size}function Lc(e,t){if(t<=0)return new Map;let n=new Map;for(let[i,r]of e)r>0&&n.set(i,Math.log(t/r));return n}function Pi(e){let t=[...e.values()].sort((i,r)=>i-r);if(t.length===0)return 0;let n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function Ni(e,t){let n=0;for(let i of e){let r=t.get(i)??0;n+=r*r}return Math.sqrt(n)}function jp(e,t,n,i={}){let r=0,o=0,s=0,a=i.medianIdf??Pi(n),c=[],l=[];for(let m of e){let p=n.get(m)??0;o+=p*p,t.has(m)&&(r+=p*p,p>=a?c.push(m):l.push(m))}if(c.length===0&&l.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let p=n.get(m)??0;s+=p*p}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?r/u:0;return c.sort((m,p)=>(n.get(p)??0)-(n.get(m)??0)),{similarity:d,significantShared:c,trivialShared:l}}function Bp(e,t,n,i){let r=0,o=i.medianIdf??Pi(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;r+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let c=i.magnitudeA*i.magnitudeB,l=c>0?r/c:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:l,significantShared:s,trivialShared:a}}function Dr(e,t,n={}){let{minSimilarity:i=.4,limit:r=20}=n,o=jL(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!ue(o.symbol))return[];if(o.callees.size===0)return Hp(e,t,{minSimilarity:i,limit:r,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=TL(e,o,i,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,r):Hp(e,t,{minSimilarity:i,limit:r,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"})}function TL(e,t,n,i){let r=Pr(e,{minCallees:3,scanLimit:i.scanLimit,semantic:i.semantic}),o=UL(t,r),s=FL(t,r),a=Pi(s),c=Ni(t.callees,s),l=[];for(let u of o){if(u.callees.size<3)continue;let d=Ni(u.callees,s),m=Up(t,u,s,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:a,magnitudeA:c,magnitudeB:d});m&&l.push(m)}return l.sort((u,d)=>d.similarity-u.similarity),l}function FL(e,t){let n=new Map(t.docFreq);for(let i of e.callees)n.set(i,(n.get(i)??0)+1);return Lc(n,t.corpus.length+1)}function Up(e,t,n,i){let r=AL(e,t,n,i);if(!$L(r,i))return null;let{similarity:o,significantShared:s,trivialShared:a}=r,c=s.length>0?s:a,l=zp(c,"callees");return{symbolA:e.symbol,shortNameA:v(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:v(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(v),uniqueToA:[...Le(e.callees,t.callees)].map(v),uniqueToB:[...Le(t.callees,e.callees)].map(v),...l}}function _L(e,t,n,i){let r=i.magnitudeA??Ni(e.callees,n),o=i.magnitudeB??Ni(t.callees,n),s=0,a=0,c=0,l=i.medianIdf??Pi(n);for(let m of e.callees){if(!t.callees.has(m))continue;let p=n.get(m)??0;s+=p*p,c+=1,p>=l&&(a+=1)}if(c===0)return!1;let u=r*o;return(u>0?s/u:0)<i.minSimilarity?!1:a>=i.requireSignificantShared||c>=i.requireSharedCount}function AL(e,t,n,i){return i.magnitudeA===void 0||i.magnitudeB===void 0?jp(e.callees,t.callees,n,{medianIdf:i.medianIdf}):Bp(e.callees,t.callees,n,{medianIdf:i.medianIdf,magnitudeA:i.magnitudeA,magnitudeB:i.magnitudeB})}function $L(e,t){if(e.similarity<t.minSimilarity)return!1;let n=e.significantShared.length+e.trivialShared.length;return e.significantShared.length>=t.requireSignificantShared||n>=t.requireSharedCount}function En(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=t.semantic!==!1,l=se(),u=0,d=0,m=0,p=0,f=0,g=0,y=0;return T("similar.all",()=>{let S=Pr(e,{minCallees:o,scope:r,scanLimit:a,semantic:c}),R=S.corpus;u=R.length;let k=t.focusFiles,x=[],b=0;return T("similar.all.pair-scan",()=>{for(let C=0;C<R.length;C+=1){let D=R[C],w=k?.has(D.file)??!1,j=S.weightedMagnitudes[C],J=new Set;for(let Re of D.callees){let ie=S.candidateIndexesByCallee.get(Re);if(ie)for(let _e of ie)_e<=C||k&&!w&&!k.has(R[_e].file)||J.add(_e)}l&&(m+=J.size,J.size>0&&(d+=1));for(let Re of J){let ie=R[Re];if(s&&D.file===ie.file){l&&(f+=1);continue}if(Wp(D,ie)){l&&(g+=1);continue}l&&(p+=1);let _e=Up(D,ie,S.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:S.medianIdf,magnitudeA:j,magnitudeB:S.weightedMagnitudes[Re]});_e&&(ML(x,_e,i,b),l&&(y+=1),b+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:y,topResults:x.length})),T("similar.all.sort-project",()=>(x.sort((C,D)=>D.result.similarity-C.result.similarity||C.order-D.order),x.map(C=>C.result)),()=>({topResults:x.length}))},()=>({minSimilarity:n,limit:i,scope:r,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:y}))}function Ec(e,t={}){let{minSimilarity:n=.5,scope:i,minCallees:r=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=se(),l=0,u=0,d=0,m=0,p=0,f=0,g=0;return T("similar.all-count",()=>{let y=Pr(e,{minCallees:r,scope:i,scanLimit:s,semantic:a}),S=y.corpus;l=S.length;let R=t.focusFiles;return T("similar.all-count.pair-scan",()=>{for(let k=0;k<S.length;k+=1){let x=S[k],b=R?.has(x.file)??!1,C=y.weightedMagnitudes[k],D=new Set;for(let w of x.callees){let j=y.candidateIndexesByCallee.get(w);if(j)for(let J of j)J<=k||R&&!b&&!R.has(S[J].file)||D.add(J)}c&&(d+=D.size,D.size>0&&(u+=1));for(let w of D){let j=S[w];if(o&&x.file===j.file){c&&(p+=1);continue}if(Wp(x,j)){c&&(f+=1);continue}c&&(m+=1),_L(x,j,y.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:y.medianIdf,magnitudeA:C,magnitudeB:y.weightedMagnitudes[w]})&&(g+=1)}}},()=>({corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g})),g},()=>({minSimilarity:n,scope:i,minCallees:r,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g}))}function Wp(e,t){if(e.paramCount<0||t.paramCount<0)return!1;let n=Math.abs(e.paramCount-t.paramCount),i=Math.max(2,Math.ceil(Math.max(e.paramCount,t.paramCount)*.5));return n>i}function ML(e,t,n,i){if(n<=0)return;if(e.length<n){e.push({result:t,order:i});return}let r=0;for(let s=1;s<e.length;s+=1){let a=e[s],c=e[r];(a.result.similarity<c.result.similarity||a.result.similarity===c.result.similarity&&a.order>c.order)&&(r=s)}let o=e[r];t.similarity<=o.result.similarity||(e[r]={result:t,order:i})}var OL=["ScipDatabase#all","ScipDatabase#get","ScipDatabase#prepare","ScipDatabase#pathExclusionsFor","ScipDatabase#isIgnored","ScipDatabase#symbolNoiseFor","PerDbValue#get","PerDbValue#has",":storage:db:ScipDatabase:all",":storage:db:ScipDatabase:get",":storage:db:ScipDatabase:prepare",":storage:db:ScipDatabase:pathExclusionsFor",":storage:db:ScipDatabase:isIgnored",":storage:db:ScipDatabase:symbolNoiseFor",":storage:per-db-cache:PerDbValue:get",":storage:per-db-cache:PerDbValue:has"];function jL(e,t,n){let i=V(e,t);if(!i||!ue(i.symbol))return null;let r=new A(e),o=Ge(e,i,{semantic:n.semantic});return{symbol:i.symbol,file:i.relativePath,callees:rs(o.map(s=>s.symbol)),paramCount:r.callableSignature(i)?.paramCount??-1}}var BL=re("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),HL=re("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function VL(e,t){let{minCallees:n,scope:i,excludeSymbol:r,scanLimit:o}=t,s=t.semantic!==!1,a=BL.get(e,()=>new Map),c=`${n}|${i??""}|${o??""}|${s}`,l=!0,u=0,d=0;return T("similar.callee-fingerprints.resolve",()=>{let m=a.get(c);if(l=m!==void 0,m||(m=WL(e,{minCallees:n,scope:i,scanLimit:o,semantic:s}),a.set(c,m)),u=m.length,r===void 0)return m;let p=m.filter(f=>f.symbol!==r);return d=m.length-p.length,p},()=>({minCallees:n,scope:i,scanLimit:o,semantic:s,cacheHit:l,corpusSize:u,excludeSymbol:r!==void 0,excludedSymbols:d}))}function Pr(e,t){let{minCallees:n,scope:i,scanLimit:r}=t,o=t.semantic!==!1,s=HL.get(e,()=>new Map),a=`${n}|${i??""}|${r??""}|${o}`,c=!0,l=0,u=0,d=0;return T("similar.callee-index.resolve",()=>{let m=s.get(a);return c=m!==void 0,m||(m=qL(VL(e,{minCallees:n,scope:i,scanLimit:r,semantic:o})),s.set(a,m)),l=m.corpus.length,u=m.docFreq.size,d=m.candidateIndexesByCallee.size,m},()=>({minCallees:n,scope:i,scanLimit:r,semantic:o,cacheHit:c,corpusSize:l,indexedCallees:u,candidateBuckets:d}))}function qL(e){let t=se(),n=0,i=T("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let p of e)for(let f of p.callees)m.set(f,(m.get(f)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),r=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=T("similar.callee-index.idf-weights",()=>Lc(i,e.length),()=>({corpusSize:e.length,uniqueCallees:i.size})),s=T("similar.callee-index.weighted-magnitudes",()=>e.map(m=>Ni(m.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,u=T("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let p=0;p<e.length;p+=1){let f=e[p];for(let g of f.callees){if((i.get(g)??0)>r){t&&(c+=1);continue}let y=m.get(g);y||(y=[],m.set(g,y)),y.push(p),t&&(a+=1)}}return t&&(l=m.size),m},()=>({corpusSize:e.length,buckets:l,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:r})),d=T("similar.callee-index.median-idf",()=>Pi(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:i,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:r}}function UL(e,t){let n=new Map;for(let i of e.callees)for(let r of t.candidateIndexesByCallee.get(i)??[]){let o=t.corpus[r];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function WL(e,t){let{minCallees:n,scope:i,scanLimit:r,semantic:o}=t,s=se(),a=new A(e),c=0,l=T("similar.callee-fingerprints.candidates",()=>{let f=qe(a.productionCallableDefinitions({scope:i,minLoc:5,sortByLocDesc:typeof r=="number"&&r>0}),r);return c=f.length,f},()=>({scope:i,scanLimit:r,candidateCount:c})),u=0,d=T("similar.callee-fingerprints.callee-map",()=>{let f=a.calleeMap(l,{semantic:o});if(s)for(let g of f.values())u+=g.length;return f},()=>({candidateCount:c,semantic:o,calleeEdges:u})),m=0,p=0;return T("similar.callee-fingerprints.shape",()=>{let f=l.map(g=>({symbol:g.symbol,file:g.relativePath,callees:rs((d.get(g.symbolId)??[]).map(y=>y.symbol)),paramCount:a.callableSignature(g)?.paramCount??-1})).filter(g=>g.callees.size>=n);return m=f.length,s&&(p=f.reduce((g,y)=>g+y.callees.size,0)),f},()=>({candidateCount:c,fingerprintCount:m,retainedCalleeCount:p,minCallees:n}))}function rs(e){return new Set([...e].filter(t=>!zL(t)))}function zL(e){return OL.some(t=>e.includes(t))}function Hp(e,t,n){let i=QL(e,t);if(!i||i.tokens.size<3)return[];let r=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,c=0,l=0,u=0;return T("similar.source-shape",()=>{let d=s==="target-pruned"?rD(e,i,{minSimilarity:r,scanLimit:n.scanLimit}):iD(i,tD(e,{scanLimit:n.scanLimit}));a=d.length;for(let m of d){if(m.symbol===i.symbol||m.tokens.size<3)continue;c+=1;let p=nt(i.tokens,m.tokens);if(p.size<2){l+=1;continue}let f=new Set([...i.tokens,...m.tokens]),g=f.size>0?p.size/f.size:0;if(g<r){u+=1;continue}o.push({symbolA:i.symbol,shortNameA:v(i.symbol),fileA:i.file,symbolB:m.symbol,shortNameB:v(m.symbol),fileB:m.file,similarity:g,similarityBasis:"source-tokens",sharedCallees:[...p].sort(),uniqueToA:[...Le(i.tokens,m.tokens)].sort(),uniqueToB:[...Le(m.tokens,i.tokens)].sort(),...zp([...p],"source-tokens")})}return o.sort((m,p)=>p.similarity-m.similarity||m.shortNameB.localeCompare(p.shortNameB)),o.slice(0,n.limit)},()=>({symbol:i.symbol,file:i.file,targetTokens:i.tokens.size,candidateMode:s,candidates:a,comparedPairs:c,sharedSkips:l,similaritySkips:u,results:o.length}))}function zp(e,t){let n=e.flatMap(Pc),i=e.flatMap(y=>Vp(y,t)),r=Dc(n,Gp),o=Dc(n,Jp),s=Dc(i,Nc),a=[...new Set(i.filter(qp))],c=e.filter(y=>{let S=Vp(y,t);return S.some(R=>Nc.has(R))&&S.some(qp)}).length,l=[];r.length>0&&l.push(`access/query scaffolding: ${r.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(y=>Kp.has(y));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=r.length+o.length>0,p=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,f=p?"domain-behavior":d?m?"mixed":"domain-behavior":r.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";f==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=f==="domain-behavior"&&(e.length>=3||p)?"direct":"signal";return{evidenceClass:f,actionTier:g,evidenceClassReasons:l,recommendation:GL(f,g)}}function GL(e,t){return t==="direct"?"Shared domain behavior looks concrete; review for an extract/reuse opportunity.":e==="mixed"?"Shared evidence mixes domain behavior with scaffolding; review semantics before extracting anything.":e==="access-query-scaffolding"?"Shared evidence is mostly access/query scaffolding; compare product semantics before reusing code.":e==="structural-overlap"?"Shared structure has no domain or scaffolding classification; inspect names and behavior before reusing code.":"Shared evidence is mostly framework or generic scaffolding; treat as a contextual signal."}function Dc(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function Pc(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function Vp(e,t){if(t==="source-tokens")return Pc(e);let n=M(e);return Pc(n.length>0?n:JL(e))}function JL(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(i=>i.trim()).filter(i=>/[A-Za-z]/.test(i)).at(-1)?.replace(/\.$/,"")??e}function qp(e){return e.length>3&&!Nc.has(e)&&!Gp.has(e)&&!Jp.has(e)&&!Kp.has(e)&&!KL.has(e)}var Nc=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),Gp=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),Jp=new Set(["bytes","computed","crypto","describe","effect","expect","fetch","filter","hex","hook","json","map","mounted","on","promise","random","react","reduce","ref","render","state","test","token","trim","uuid","vue","watch"]),Kp=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),KL=new Set(["best","backend","conflict","database","effect","effects","error","errors","frontend","found","helpers","javascript","module","modules","scip","shared","source","typescript","utils","with","workflow","workflows"]);function QL(e,t){let n=V(e,t);if(!n||!ue(n.symbol))return null;let i=XL(e,n);return i?{symbol:n.symbol,file:n.relativePath,tokens:i}:null}function XL(e,t){let n=M(t.symbol),i=lD(e,t.relativePath,t.startLine,t.endLine,n),r=Zp(i,n);return r.size>0?r:null}var YL=re("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),ZL=re("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function Qp(e){return`${e.scanLimit??""}`}function eD(e,t={}){let n=YL.get(e,()=>new Map),i=Qp(t),r=n.get(i);return r||(r=cD(e,t),n.set(i,r)),r}function tD(e,t={}){let n=ZL.get(e,()=>new Map),i=Qp(t),r=n.get(i);return r||(r=nD(eD(e,t)),n.set(i,r)),r}function nD(e){let t=new Map;for(let r of e)for(let o of r.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),i=new Map;for(let r of e)for(let o of r.tokens){if((t.get(o)??0)>n)continue;let s=i.get(o);s||(s=[],i.set(o,s)),s.push(r)}return{corpus:e,candidateByToken:i,docFreq:t,ubiquityThreshold:n}}function iD(e,t){let n=new Map;for(let i of e.tokens)for(let r of t.candidateByToken.get(i)??[])r.symbol!==e.symbol&&n.set(r.symbol,r);return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function rD(e,t,n){let i=se(),r=new A(e),o=oD(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=T("similar.source-shape.target-files",()=>{let f=[...t.tokens],g=[];for(let y of B(e,{includeIgnored:!1})){s+=1;let S=F(e,y);S&&(a+=1,sD(S,f,o)&&g.push(y))}return c=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:c})),u=0,d=T("similar.source-shape.target-definitions",()=>{let f=qe(r.productionCallableDefinitions({files:l,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=f.length,f},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:u})),m=0;return T("similar.source-shape.target-fingerprints",()=>{let f=Xp(e,d);return i&&(m=f.length),f},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(f=>f.symbol!==t.symbol)}function oD(e,t){return Math.max(2,Math.ceil(e*t))}function sD(e,t,n){if(t.length<n)return!1;let i=e.toLowerCase(),r=0;for(let o of t)if(aD(i,o)&&(r+=1,r>=n))return!0;return!1}function aD(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function cD(e,t={}){let n=new A(e),{scanLimit:i}=t,r=qe(n.productionCallableDefinitions({sortByLocDesc:typeof i=="number"&&i>0}),i);return Xp(e,r)}function Xp(e,t){let n=new Map;for(let r of t){let o=n.get(r.relativePath)??[];o.push(r),n.set(r.relativePath,o)}let i=new Map;for(let[r,o]of n){let s=F(e,r);if(!s)continue;let a=Z(e,r,s),c=dD(e,r,a),l=!1,u=null;for(let d of o){let m=uD(d),p=c.get(m),f=p?new Set(p.tokens):null;f||(u??=Ke(e,r),f=Zp(Yp(u,d.startLine,d.endLine,d.leaf),d.leaf),c.set(m,{key:m,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...f].sort()}),l=!0),f.size>0&&i.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:f})}l&&mD(e,r,a,c)}return t.map(r=>i.get(r.symbol)).filter(r=>!!r)}function lD(e,t,n,i,r){let o=Ke(e,t);return o.length===0?"":Yp(o,n,i,r)}function Yp(e,t,n,i){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
|
|
543
|
+
`);let r=[new RegExp(`\\bdef\\s+${Lr(i)}\\b`),new RegExp(`\\bfun\\s+${Lr(i)}\\b`),new RegExp(`\\bfn\\s+${Lr(i)}\\b`),new RegExp(`\\bfunction\\s+${Lr(i)}\\b`),new RegExp(`\\b${Lr(i)}\\s*\\(`)],o=e.findIndex(s=>r.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let c=e[a]??"";if(a>o&&fD(c)||(s=a,c.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
|
|
544
|
+
`)}return e.slice(t,Math.min(e.length,t+8)).join(`
|
|
545
|
+
`)}function uD(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function dD(e,t,n){let i=ae(e,"source-fingerprints",t,n);if(!i)return new Map;try{let r=JSON.parse(i);if(!Array.isArray(r.entries))return new Map;let o=new Map;for(let s of r.entries){if(!s||typeof s.key!="string"||typeof s.symbol!="string"||typeof s.startLine!="number"||typeof s.endLine!="number"||typeof s.leaf!="string"||!Array.isArray(s.tokens)||!s.tokens.every(a=>typeof a=="string"))return new Map;o.set(s.key,s)}return o}catch{return new Map}}function mD(e,t,n,i){let r={entries:[...i.values()].sort((o,s)=>o.key.localeCompare(s.key))};ce(e,"source-fingerprints",t,n,JSON.stringify(r))}function Zp(e,t){if(!e)return new Set;let n=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),i=pD(t),o=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(s=>s.trim()).filter(s=>s.length>1).filter(s=>!n.has(s)).filter(s=>!i.has(s));return new Set(o)}function pD(e){return new Set(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9_]+|_/).map(t=>t.toLowerCase()).filter(t=>t.length>1))}function fD(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Lr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ct(e){let t=[];if(e.filePattern){let n=e.profiles.find(i=>i.file.includes(e.filePattern));if(!n)return[];for(let i of e.profiles){if(i.file===n.file||e.focusFiles&&!e.focusFiles.has(n.file)&&!e.focusFiles.has(i.file))continue;let r=e.compare(n,i);r&&t.push(r)}}else{if(e.focusFiles?.size===0)return[];let n=e.focusFiles?e.profiles.map((r,o)=>e.focusFiles.has(r.file)?o:-1).filter(r=>r>=0):[],i=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let r=0;r<e.profiles.length;r+=1){let o=e.profiles[r];if(e.focusFiles&&!e.focusFiles.has(o.file))for(let s of n){if(s<=r)continue;let a=e.compare(o,e.profiles[s]);a&&t.push(a)}else for(let s=r+1;s<e.profiles.length;s+=1){let a=e.compare(o,e.profiles[s]);a&&t.push(a)}if(t.length>i)break}}return t.sort(e.sort??((n,i)=>i.similarity-n.similarity)),t.slice(0,e.limit)}function Tc(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=gD(e,{scope:r,minDeps:s});return Ct({profiles:a,limit:i,filePattern:o,overrunFactor:5,compare:(l,u)=>yD(l,u,n,c)})}function gD(e,t){let{scope:n,minDeps:i}=t,r=pe(e,n),{universalDeps:o,distinctiveDeps:s}=hD(r),a=[];for(let[c,l]of r)l.size>=i&&a.push({file:c,deps:new Set([...l].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function hD(e){let t=new Set,n=new Set,i=e.size;if(i===0)return{universalDeps:t,distinctiveDeps:n};let r=new Map;for(let s of e.values())for(let a of s)r.set(a,(r.get(a)??0)+1);let o=Math.max(3,Math.ceil(i*.03));for(let[s,a]of r)a>=5&&a/i>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function yD(e,t,n,i){let r=new Set;for(let l of e.deps)t.deps.has(l)&&r.add(l);if(r.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let l of r)i.has(l)&&o++;if(o<2)return null;let s=tn(e.deps,t.deps);if(s<n)return null;let a=[];for(let l of e.deps)t.deps.has(l)||a.push(l);let c=[];for(let l of t.deps)e.deps.has(l)||c.push(l);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...r],uniqueToA:a,uniqueToB:c}}function os(e){let t=[],n=[],i=[];for(let l of e.primitiveGroups)l.values.length!==0&&ef(l.bucket,n,i).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)bD(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,ef(l.fallbackBucket,n,i));let r=t.length>0,o=n.length>0,s=i.length>0,a=r?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...i,...n].slice(0,6),recommendation:e.recommendation(a)}}function ss(e,t){if(e.size===0||t.size===0)return 0;let i=nt(e,t).size/Math.min(e.size,t.size);return Math.max(tn(e,t),i)}function W(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function Ne(e){return[...e].sort()}function bD(e,t,n,i,r,o){let s=[],a=[];for(let c of e)SD(c,i).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&r.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function SD(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let i of t)n=n.replace(i,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function ef(e,t,n){return e==="generic"?t:n}function Tn(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=ui(e,{scope:o,minJsxTokens:i,scanLimit:s}).filter(u=>u.kind==="component").map(u=>({file:u.file,component:u.name,tokens:u.jsxTokens,profile:u}));return Ct({profiles:l,limit:r,filePattern:a,focusFiles:c,compare:(u,d)=>xD(u,d,n),sort:(u,d)=>d.similarity-u.similarity||u.fileA.localeCompare(d.fileA)||u.componentA.localeCompare(d.componentA)||u.fileB.localeCompare(d.fileB)||u.componentB.localeCompare(d.componentB)})}function xD(e,t,n){let i=nt(e.tokens,t.tokens);if(i.size<6||!CD(i))return null;let r=tn(e.tokens,t.tokens);return r<n?null:{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:r,sharedTokens:Ne(i),sharedComponents:W(i,"component:"),sharedNativeTags:W(i,"native:"),sharedProps:W(i,"prop:"),sharedEvents:W(i,"event:"),sharedBindings:W(i,"binding:"),uniqueToA:Ne(Le(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ne(Le(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function CD(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("native:")||i.startsWith("jsx:"))&&(n+=1);return t>=1||n>=4}function Fn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=ui(e,{scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(u=>({file:u.file,component:u.name,tokens:u.behaviorTokens,profile:u}));return Ct({profiles:l,limit:r,filePattern:a,focusFiles:c,compare:(u,d)=>vD(u,d,n,i),sort:(u,d)=>d.similarity-u.similarity||u.fileA.localeCompare(d.fileA)||u.componentA.localeCompare(d.componentA)||u.fileB.localeCompare(d.fileB)||u.componentB.localeCompare(d.componentB)})}function vD(e,t,n,i){let r=nt(e.tokens,t.tokens);if(r.size<i||!wD(r))return null;let o=ss(e.tokens,t.tokens);if(o<n)return null;let s=W(r,"hook:"),a=W(r,"react-hook:"),c=W(r,"effect:"),l=W(r,"state:"),u=W(r,"request:"),d=W(r,"handler:"),m=W(r,"handler-verb:"),p=RD({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,sharedTokens:Ne(r),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:p.evidenceClass,actionTier:p.actionTier,evidenceClassReasons:p.reasons,recommendation:p.recommendation,uniqueToA:Ne(Le(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ne(Le(t.tokens,e.tokens)).slice(0,25),reason:ID({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function RD(e){return os({genericWords:LD,stripPrefixes:DD,primitiveGroups:[{values:e.sharedReactHooks,reasonPrefix:"shared React primitives",bucket:"generic"},{values:e.sharedEffects,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedHooks,label:"shared hook",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedState,label:"shared state",fallbackBucket:"generic"},{names:e.sharedHandlers,label:"shared handler",fallbackBucket:"generic"},{names:e.sharedHandlerVerbs,label:"shared action verb",fallbackBucket:"generic"}],recommendation:kD})}function kD(e){switch(e){case"domain-behavior":return"Review for a shared hook, controller, or feature module around the named domain behavior.";case"mixed":return"Separate generic React mechanics from domain-specific behavior before extracting a shared hook.";case"shared-abstraction":return"Review the existing shared hook usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct hook-extraction evidence."}}function wD(e){let t=0,n=0,i=0,r=0,o=0,s=0,a=0;for(let u of e)u.startsWith("hook:")?t+=1:u.startsWith("react-hook:")?n+=1:u.startsWith("effect:")?i+=1:u.startsWith("request:")?r+=1:u.startsWith("handler:")||u.startsWith("handler-verb:")?o+=1:u.startsWith("state:")?s+=1:u.startsWith("state-hook:")&&(a+=1);let c=s+a,l=t+n+i+r+o+c;return r>=1&&l>=4||t>=1&&(r>=1||s>=1||o>=2)&&l>=5||s>=1&&o>=2&&(i>=1||n>=2)&&l>=5}function ID(e){let t=[];return e.sharedHooks.length&&t.push(`shared hooks: ${e.sharedHooks.join(", ")}`),e.sharedReactHooks.length&&t.push(`shared React hooks: ${e.sharedReactHooks.join(", ")}`),e.sharedEffects.length&&t.push(`shared effects: ${e.sharedEffects.join(", ")}`),e.sharedState.length&&t.push(`shared state: ${e.sharedState.join(", ")}`),e.sharedRequests.length&&t.push(`shared requests: ${e.sharedRequests.join(", ")}`),e.sharedHandlers.length&&t.push(`shared handlers: ${e.sharedHandlers.slice(0,6).join(", ")}`),e.sharedHandlerVerbs.length&&t.push(`shared action verbs: ${e.sharedHandlerVerbs.slice(0,6).join(", ")}`),t.join("; ")||"shared React behavior profile"}var LD=new Set(["add","apply","async","callback","cancel","change","clear","close","create","data","delete","draft","edit","effect","error","fetch","filter","form","handle","has","is","item","items","load","loader","loading","memo","name","open","reducer","refresh","ref","remove","request","reset","resource","row","rows","save","saving","search","select","selected","state","store","submit","toggle","update","use","value"]),DD=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function Nr(e,t={}){let{minComponentLines:n=300,minFileLines:i=800,minJsxTokens:r=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return ui(e,{scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>PD(d,{minComponentLines:n,minFileLines:i,minJsxTokens:r,minBehaviorTokens:o})).filter(d=>d!==null).sort((d,m)=>m.componentLines-d.componentLines||m.fileLines-d.fileLines||d.file.localeCompare(m.file)).slice(0,s)}function PD(e,t){let n=[];e.loc>=t.minComponentLines&&n.push(`${e.loc} component line(s)`);let i=Math.max(80,Math.floor(t.minComponentLines/2));if(e.fileLines>=t.minFileLines&&e.loc>=i&&n.push(`${e.fileLines} file line(s)`),e.jsxTokens.size>=t.minJsxTokens&&n.push(`${e.jsxTokens.size} JSX structure token(s)`),e.behaviorTokens.size>=t.minBehaviorTokens&&n.push(`${e.behaviorTokens.size} behavior token(s)`),n.length===0)return null;let r=ND(e),o=ED(e,t,r),s=TD(e),a=FD(r,o,s);return{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:r,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:_D(a,s),reasons:n,loc:e.loc}}function ND(e){let t=[{axis:"component",value:e.loc},{axis:"file",value:e.fileLines},{axis:"jsx-structure",value:e.jsxTokens.size*3},{axis:"hook-behavior",value:e.behaviorTokens.size*4}];return t.sort((n,i)=>i.value-n.value),t[0]?.axis??"component"}function ED(e,t,n){let i=[];e.loc>=t.minComponentLines&&i.push("component");let r=Math.max(80,Math.floor(t.minComponentLines/2));return e.fileLines>=t.minFileLines&&e.loc>=r&&i.push("file"),e.jsxTokens.size>=t.minJsxTokens&&i.push("jsx-structure"),e.behaviorTokens.size>=t.minBehaviorTokens&&i.push("hook-behavior"),[...new Set(i.length>0?i:[n])]}function TD(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(l=>l.toLowerCase()),i=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),r=`${i} ${e.name}`.split(/[^A-Za-z0-9]+/).filter(Boolean).map(l=>l.toLowerCase()),o=n.findIndex(l=>$D.has(l)),s=o>=0&&n.slice(o+1).some(l=>AD.has(l)),a=tf(i)||tf(e.name);return/(?:Page|Route|Screen|View)$/.test(i)||/(?:Page|Route|Screen|View)$/.test(e.name)||r.some(l=>MD.has(l))||o>=0&&!s&&!a?"route-page":"component"}function tf(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&nf.has(t.at(-1))?!0:[...nf].some(n=>e.endsWith(OD(n)))}function FD(e,t,n){return e==="hook-behavior"?"behavior-extraction":n==="route-page"?"route-page-decomposition":t.includes("hook-behavior")?"behavior-extraction":t.includes("jsx-structure")?"jsx-decomposition":t.includes("file")?"file-decomposition":e==="jsx-structure"?"jsx-decomposition":e==="file"&&!t.includes("component")?"file-decomposition":"component-decomposition"}function _D(e,t){switch(e){case"behavior-extraction":return"Extract independent state, effects, requests, or handlers into hooks, controllers, or feature modules.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"jsx-decomposition":return t==="route-page"?"Split page JSX into named layout sections before extracting behavior.":"Split repeated JSX sections into named presentational components.";case"file-decomposition":return"Review file-level decomposition; split colocated panels or helpers before changing behavior.";case"component-decomposition":return"Review component boundaries around props, state ownership, and independently changing UI sections."}}var AD=new Set(["component","components","panel","panels","partial","partials"]),nf=new Set(["banner","button","card","dialog","drawer","filter","form","grid","header","item","list","menu","modal","nav","panel","picker","rail","row","section","selector","shell","sidebar","table","toolbar"]),$D=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),MD=new Set(["landing","page","route","screen","view"]);function OD(e){return e.charAt(0).toUpperCase()+e.slice(1)}function _n(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=jD(e,{scope:o,minTokens:i,scanLimit:s});return Ct({profiles:l,limit:r,filePattern:a,focusFiles:c,compare:(u,d)=>HD(u,d,n),sort:(u,d)=>d.similarity-u.similarity||u.fileA.localeCompare(d.fileA)||u.fileB.localeCompare(d.fileB)})}function jD(e,t){return li(e,{scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:BD(n)}))}function BD(e){return e.totalLines}function HD(e,t,n){let i=nt(e.tokens,t.tokens);if(i.size<6||!VD(i))return null;let r=tn(e.tokens,t.tokens);return r<n?null:{fileA:e.file,fileB:t.file,similarity:r,sharedTokens:Ne(i),sharedComponents:W(i,"component:"),sharedProps:W(i,"prop:"),sharedEvents:W(i,"event:"),sharedDirectives:W(i,"directive:"),sharedSlots:W(i,"slot:"),sharedIdentifiers:W(i,"id:"),uniqueToA:Ne(Le(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ne(Le(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function VD(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("directive:")||i.startsWith("slot:"))&&(n+=1);return t>=1||n>=3}function An(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=li(e,{scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(u=>({file:u.file,tokens:u.behaviorTokens,profile:u}));return Ct({profiles:l,limit:r,filePattern:a,focusFiles:c,compare:(u,d)=>qD(u,d,n,i),sort:(u,d)=>d.similarity-u.similarity||u.fileA.localeCompare(d.fileA)||u.fileB.localeCompare(d.fileB)})}function qD(e,t,n,i){let r=nt(e.tokens,t.tokens);if(r.size<i||!zD(r))return null;let o=ss(e.tokens,t.tokens);if(o<n)return null;let s=W(r,"composable:"),a=W(r,"store:"),c=W(r,"reactivity:"),l=W(r,"lifecycle:"),u=W(r,"request:"),d=W(r,"function:"),m=W(r,"function-verb:"),p=W(r,"template-binding:"),f=W(r,"template-event:"),g=UD({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f});return{fileA:e.file,fileB:t.file,similarity:o,sharedTokens:Ne(r),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:Ne(Le(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ne(Le(t.tokens,e.tokens)).slice(0,25),reason:GD({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function UD(e){return os({genericWords:JD,primitiveGroups:[{values:e.sharedReactivity,reasonPrefix:"shared reactivity primitive",bucket:"generic"},{values:e.sharedLifecycle,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedComposables,label:"shared composable",fallbackBucket:"shared-abstraction"},{names:e.sharedStores,label:"shared store",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedFunctions,label:"shared function",fallbackBucket:"generic"},{names:e.sharedFunctionVerbs,label:"shared action verb",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"},{names:e.sharedTemplateEvents,label:"shared template event",fallbackBucket:"generic"}],recommendation:WD})}function WD(e){switch(e){case"domain-behavior":return"Review for a shared composable, store, or feature module around the named domain behavior.";case"mixed":return"Separate generic Vue mechanics from domain-specific behavior before extracting a composable.";case"shared-abstraction":return"Review the existing composable/store usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct composable-extraction evidence."}}function zD(e){let t=0,n=0,i=0,r=0,o=0,s=0,a=0;for(let u of e)u.startsWith("composable:")?t+=1:u.startsWith("store:")?n+=1:u.startsWith("request:")?i+=1:u.startsWith("lifecycle:")?r+=1:u.startsWith("function:")?o+=1:u.startsWith("reactivity:")?s+=1:(u.startsWith("function-verb:")||u.startsWith("template-binding:")||u.startsWith("template-event:"))&&(a+=1);let c=t+n,l=c+i+r+o+a;return i>=1&&l>=4||r>=1&&o>=2&&l>=4||c>=2&&(i>=1||o>=2)&&l>=5||o>=2&&s>=1&&l>=4}function GD(e){let t=[];return e.sharedComposables.length&&t.push(`shared composables: ${e.sharedComposables.join(", ")}`),e.sharedStores.length&&t.push(`shared stores: ${e.sharedStores.join(", ")}`),e.sharedRequests.length&&t.push(`shared request helpers: ${e.sharedRequests.join(", ")}`),e.sharedLifecycle.length&&t.push(`shared lifecycle: ${e.sharedLifecycle.join(", ")}`),e.sharedFunctions.length&&t.push(`shared functions: ${e.sharedFunctions.slice(0,6).join(", ")}`),e.sharedFunctionVerbs.length&&t.push(`shared action verbs: ${e.sharedFunctionVerbs.slice(0,6).join(", ")}`),e.sharedBindings.length&&t.push(`shared template bindings: ${e.sharedBindings.slice(0,6).join(", ")}`),t.join("; ")||"shared Vue behavior profile"}var JD=new Set(["add","apply","cancel","change","clear","close","composable","create","data","delete","draft","edit","error","fetch","filter","form","item","items","load","loading","name","open","reactive","ref","refresh","remove","request","reset","resource","row","rows","save","saving","search","select","selected","store","submit","toggle","update","use","value","watch"]);function Er(e,t={}){let{minTotalLines:n=800,minTemplateLines:i=300,minScriptLines:r=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return li(e,{scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>KD(d,{minTotalLines:n,minTemplateLines:i,minScriptLines:r,minStyleLines:o})).filter(d=>d!==null).sort((d,m)=>m.totalLines-d.totalLines||d.file.localeCompare(m.file)).slice(0,s)}function KD(e,t){let n=[];if(e.totalLines>=t.minTotalLines&&n.push(`${e.totalLines} total component line(s)`),e.templateLines>=t.minTemplateLines&&n.push(`${e.templateLines} template line(s)`),e.scriptLines>=t.minScriptLines&&n.push(`${e.scriptLines} script line(s)`),e.styleLines>=t.minStyleLines&&n.push(`${e.styleLines} style line(s)`),n.length===0)return null;let i=QD(e),r=XD(e,t,i),o=YD(e.file),s=ZD(i,o);return{file:e.file,totalLines:e.totalLines,sfcLines:e.sfcLines,templateLines:e.templateLines,scriptLines:e.scriptLines,styleLines:e.styleLines,externalScriptLines:e.externalScriptLines,externalScriptPaths:e.externalScriptPaths,customBlockLines:e.customBlockLines,dominantPressure:i,pressureKinds:r,contextKind:o,recommendationKind:s,recommendation:eP(s,o),reasons:n,loc:e.totalLines}}function QD(e){let t=[{axis:"template",lines:e.templateLines},{axis:"script",lines:e.scriptLines-e.externalScriptLines},{axis:"style",lines:e.styleLines},{axis:"external-script",lines:e.externalScriptLines},{axis:"custom-block",lines:e.customBlockLines}];return t.sort((n,i)=>i.lines-n.lines),t[0]?.lines?t[0].axis:"total"}function XD(e,t,n){let i=[];return e.totalLines>=t.minTotalLines&&(i.push("total"),n!=="total"&&i.push(n)),e.templateLines>=t.minTemplateLines&&i.push("template"),e.scriptLines>=t.minScriptLines&&i.push("script"),e.styleLines>=t.minStyleLines&&i.push("style"),(e.externalScriptLines>=t.minScriptLines||n==="external-script")&&i.push("external-script"),e.customBlockLines>0&&n==="custom-block"&&i.push("custom-block"),[...new Set(i.length>0?i:[n])]}function YD(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(i=>tP.has(i))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function ZD(e,t){return e==="style"?"style-decomposition":e==="template"?"template-decomposition":e==="external-script"?"external-script-boundary":e==="custom-block"?"custom-block-review":t==="route-page"?"route-page-decomposition":e==="script"?"script-behavior-extraction":"total-size-review"}function eP(e,t){switch(e){case"template-decomposition":return t==="route-page"?"Split route template sections into named panels before extracting script behavior.":"Split repeated template sections into named presentational components.";case"script-behavior-extraction":return"Extract independent script behavior into composables, controllers, or feature modules.";case"style-decomposition":return"Review UI/style decomposition; move repeated styling to component or style primitives, not composables.";case"external-script-boundary":return"Review the external script boundary and split controller/composable modules by workflow.";case"custom-block-review":return"Review custom block ownership before splitting template or script code.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"total-size-review":return"Review the largest block first, then split by the dominant reason to change."}}var tP=new Set(["landing","page","pages","route","routes","view","views"]);function Fc(e,t={}){let{minSimilarity:n=.5,limit:i=15,scope:r,minChainLength:o=3,maxChainLength:s=8}=t,a=pe(e,r),c=lP(a,o,s);if(c.length===0)return[];let l=nP(c);return l.length<2?[]:cP(oP(l,n,i),i)}function nP(e){let t=iP(e),n=[];for(let i of e){let r=i.filter(o=>!t.has(o));r.length>=2&&n.push({original:i,filtered:r})}return n}function iP(e){let{nodeFreq:t,tailFreq:n}=rP(e),i=e.length*.9,r=e.length*.8,o=new Set;for(let[a,c]of t)c>i&&o.add(a);for(let[a,c]of n)c>r&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let c=a.split("/").pop()??"";s.includes(c)&&o.add(a)}return o}function rP(e){let t=new Map,n=new Map;for(let i of e){let r=new Set;for(let o of i)r.has(o)||(t.set(o,(t.get(o)??0)+1),r.add(o));for(let o=Math.max(0,i.length-2);o<i.length;o++)n.set(i[o],(n.get(i[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function oP(e,t,n){let i=[];for(let r=0;r<e.length;r++){for(let o=r+1;o<e.length;o++){let s=sP(e[r],e[o],t);s&&i.push(s)}if(i.length>n*10)break}return i.sort((r,o)=>Math.abs(o.similarity-r.similarity)>.01?o.similarity-r.similarity:r.divergencePoints.length-o.divergencePoints.length),i}function sP(e,t,n){if(!aP(e.filtered,t.filtered))return null;let{distance:i,ops:r}=uP(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-i/o;if(s<n||i===0)return null;let a=r.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||r.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:i,divergencePoints:a,commonPrefix:dP(e.original,t.original),commonSuffix:mP(e.original,t.original)}}function aP(e,t){let n=new Set(e);return t.some(i=>n.has(i))}function cP(e,t){let n=[];for(let i of e)if(n.some(o=>rf(i.chainA,o.chainA)&&rf(i.chainB,o.chainB))||n.push(i),n.length>=t)break;return n}function lP(e,t,n){let i=[];for(let o of e.keys()){if(i.length>=500)break;of(e,o,[o],new Set([o]),t,n,i,500)}return i}function of(e,t,n,i,r,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=r&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=r&&s.push([...n]);return}let l=!1;for(let u of c)if(!i.has(u)&&(i.add(u),n.push(u),of(e,u,n,i,r,o,s,a),n.pop(),i.delete(u),l=!0,s.length>=a))return;!l&&n.length>=r&&s.push([...n])}function uP(e,t){let n=e.length,i=t.length,r=Array.from({length:n+1},()=>Array(i+1).fill(0));for(let c=0;c<=n;c++)r[c][0]=c;for(let c=0;c<=i;c++)r[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=i;l++)e[c-1]===t[l-1]?r[c][l]=r[c-1][l-1]:r[c][l]=1+Math.min(r[c-1][l],r[c][l-1],r[c-1][l-1]);let o=[],s=n,a=i;for(;s>0||a>0;)s>0&&a>0&&e[s-1]===t[a-1]?(o.unshift({type:"match",indexA:s-1,indexB:a-1}),s--,a--):s>0&&a>0&&r[s][a]===r[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&r[s][a]===r[s][a-1]+1?(o.unshift({type:"insert",indexA:s,indexB:a-1}),a--):(o.unshift({type:"delete",indexA:s-1,indexB:a}),s--);return{distance:r[n][i],ops:o}}function dP(e,t){let n=[];for(let i=0;i<Math.min(e.length,t.length)&&e[i]===t[i];i++)n.push(e[i]);return n}function mP(e,t){let n=[],i=e.length-1,r=t.length-1;for(;i>=0&&r>=0&&e[i]===t[r];)n.unshift(e[i]),i--,r--;return n}function rf(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),i=e.join("\u2192");return n.includes(i)}function it(e){let t=e.orderCandidates?[...e.candidates()].sort(e.orderCandidates):e.candidates(),n=qe(t,e.scanLimit),i=e.prepare?.(n)??void 0,r=[];for(let o of n){let s=e.evaluate(o,i);s&&r.push(s)}return e.orderResults&&r.sort(e.orderResults),typeof e.limit=="number"?r.slice(0,e.limit):r}function $n(e,t={}){let{scope:n,minLoc:i=10,minCallees:r=6,limit:o=20,scanLimit:s}=t,a=new A(e);return it({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:i,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>pP(c,l.get(c.symbolId)??[],r),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function pP(e,t,n){let i=new Set(t.map(l=>l.symbol));if(i.size<n)return null;let r=bP(i,t),o=SP(i,r);if(o.length<2)return null;let s=xP(o,r);if(s.length===0)return null;let a=v(e.symbol),c=fP(a,i.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:G(e),totalCallees:i.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function fP(e,t,n,i){let r=Math.max(...i.map(c=>c.callees.length)),o=Math.max(...i.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${i.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${r} callees at ${Math.round(o*100)}% isolation`],a=gP(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:r>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function gP(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let i=hP(e);return yP.has(i)?`caller verb suggests orchestration: ${i}`:null}function hP(e){return e.split(":").pop()?.replace(/\(\)$/,"").replace(/[^A-Za-z0-9_]/g,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\s-]+/).filter(Boolean)[0]?.toLowerCase()??""}var yP=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function bP(e,t){let n=new Map;for(let r of e)n.set(r,new Set);let i=new Map;for(let r of t){let o=i.get(r.chunkId);o||(o=new Set,i.set(r.chunkId,o)),o.add(r.symbol)}for(let r of i.values()){let o=[...r];for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++)n.get(o[s]).add(o[a]),n.get(o[a]).add(o[s])}return n}function SP(e,t){let n=new Set,i=[];for(let r of e){if(n.has(r))continue;let o=new Set,s=[r];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let c of t.get(a)??[])n.has(c)||s.push(c)}}i.push(o)}return i}function xP(e,t){return e.filter(n=>n.size>=3).map(n=>CP(n,e,t)).filter(n=>n.isolation>.5).sort((n,i)=>i.isolation-n.isolation)}function CP(e,t,n){let i=new Set;for(let a of t)if(a!==e)for(let c of a)i.add(c);let r=0;for(let a of e)for(let c of n.get(a)??[])i.has(c)&&r++;let o=e.size*i.size,s=o>0?1-r/o:1;return{callees:[...e].map(v),isolation:s}}import{posix as Ei}from"path";var vP=U("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]});function nn(e,t,n){return e.callerFileMap(t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function as(e,t,n){let i=[],r=0,o=0,s=M(t.symbol);for(let a of n)DP(e,a,t.relativePath,s)?r++:_c(e,a,s)?o++:i.push(a);return{realConsumers:i,barrelConsumers:r,importOnlyConsumers:o}}function _c(e,t,n){if(!n)return!1;let i=K(t);if(!i)return!1;let r=vP.get(e,t,()=>RP(e,t,i));return r.importedLeaves.has(n)&&!r.usedLeaves.has(n)}function RP(e,t,n){let i=F(e,t);if(!i)return wP();let r=Z(e,t,i),o=ae(e,"consumer-file-usage",t,r);if(o){let a=LP(o);if(a)return a}let s=kP(e,t,n);return ce(e,"consumer-file-usage",t,r,IP(s)),s}function kP(e,t,n){let i=new Set,r=new Set,o=ke(e,t);if(!o)return{importedLeaves:i,usedLeaves:r};let s=n==="rust"?new Set(["use_declaration"]):n==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),a=(c,l)=>{let u=l||s.has(c.type);(c.type==="identifier"||c.type==="type_identifier"||c.type==="property_identifier"||c.type==="field_identifier")&&(u?i.add(c.text):r.add(c.text));for(let d of c.children)a(d,u)};return a(o.rootNode,!1),{importedLeaves:i,usedLeaves:r}}function wP(){return{importedLeaves:new Set,usedLeaves:new Set}}function IP(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function LP(e){try{let t=JSON.parse(e);return!Array.isArray(t.importedLeaves)||!Array.isArray(t.usedLeaves)?null:{importedLeaves:new Set(t.importedLeaves.filter(n=>typeof n=="string")),usedLeaves:new Set(t.usedLeaves.filter(n=>typeof n=="string"))}}catch{return null}}function DP(e,t,n,i){if(!i)return!1;let r=Ke(e,t);if(r.length===0)return!1;let o=cr(e,t);if(o.length===0)return!1;let s=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`\\b${s}\\b`),c=0;for(let l=0;l<r.length;l++){if(!a.test(r[l]??""))continue;if(c++,!o.find(d=>d.startLine<=l&&l<=d.endLine))return!1}return c>0}var PP=20,NP=1,EP=new Map([["app","app"],["apps","app"],["component","component"],["components","component"],["composable","composable"],["composables","composable"],["contract","contract"],["contracts","contract"],["domain","domain"],["domains","domain"],["feature","feature"],["features","feature"],["hook","hook"],["hooks","hook"],["lib","library"],["module","module"],["modules","module"],["package","package"],["packages","package"],["page","page"],["pages","page"],["route","route"],["routes","route"],["screen","screen"],["screens","screen"],["service","service"],["services","service"],["shared","shared"],["src","source-root"],["store","state"],["stores","state"],["test","test"],["tests","test"],["util","utility"],["utils","utility"],["view","view"],["views","view"]]),TP=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),FP=new Set(["access","api","auth","config","db","effect","errors","hooks","lib","middleware","permissions","routes","schemas","servicetasks","services","startup","store","stores","test-utils","repository","repositories","tests","types","ui","utils","workflow","workflows"]);function Oc(e,t={}){let n=Mc(t.limit,PP),i=Mc(t.minConsumers,NP),r=new A(e),o=r.fileDependencyGraph(t.scope),s=ZP(B(e,{includeIgnored:!1})),a=nN(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?_P(e,r,t.target):AP(e,t.scope,t.scanLimit)).map(u=>$P(r,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=i||t.target).sort(YP).slice(0,n)}function _P(e,t,n){let i=jP(e,n);if(i)return[uf(i)];let r=V(e,n);if(!r)return[];let o=t.definitionsForFile(r.relativePath).find(s=>s.symbolId===r.symbolId);return o?[BP(o)]:[{unit:{kind:"symbol",file:r.relativePath,shortName:v(r.symbol),symbol:r.symbol,startLine:r.startLine,endLine:r.endLine}}]}function AP(e,t,n){let i=B(e,{scope:t,includeIgnored:!1}),r=Mc(n,i.length);return i.slice(0,r).map(o=>uf(o))}function $P(e,t,n,i,r,o){let s=n.definition?MP(e,n.definition,i.semantic):OP(t,n.unit.file),a=n.definition?s.length>0?"exact":"none":s.length>0?"file-level":"none",c=n.unit.file,l=dt(Ei.dirname(c)),u=VP(s),d=HP(l),m=Hc([...sf(l),...u?sf(u):[]]),p=qP(n.unit,l,u,s),f=UP(p,n.unit,l,u,s,r,o),g=KP(n.unit,a,u,s,l,f.whyNoSuggestedHome),y=QP(n.unit,l,u,s,f.suggestedHome,f.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:n.unit,candidatePath:c,currentDirectory:l,directoryAncestry:d,consumerFiles:s,consumerCoverage:a,nearestCommonOwner:u,boundaryMarkers:m,recommendedTier:p,suggestedHome:f.suggestedHome,destinationConfidence:f.confidence,whyNoSuggestedHome:f.whyNoSuggestedHome,counterevidence:g,reasons:y,recommendation:XP(p,f.suggestedHome,a)}}function MP(e,t,n){let i=nn(e,[t],{semantic:n!==!1,sourceFallback:!0});return gf(i.get(t.symbolId)??[])}function OP(e,t){let n=[];for(let[i,r]of e.entries())i!==t&&r.has(t)&&n.push(i);return gf(n)}function jP(e,t){let n=Bc(t),i=B(e,{includeIgnored:!1}),r=i.find(s=>s===n);if(r)return r;let o=i.find(s=>s.endsWith(`/${n}`));return o||(i.find(s=>s.includes(n))??null)}function BP(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:v(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function uf(e){return{unit:{kind:"file",file:e,shortName:Ei.basename(e)}}}function HP(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let i=0;i<n.length;i+=1){let r=n.slice(0,i+1).join("/");t.push({path:r,depth:i,markers:jc(r)})}return t}function sf(e){return e==="."?[]:df(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function jc(e){return Hc(df(e).map(({marker:t})=>t))}function df(e){let t=e.split("/").filter(Boolean),n=[];for(let i=0;i<t.length;i+=1){let r=EP.get(t[i]);r&&n.push({marker:r,prefix:t.slice(0,i+1).join("/")})}return n}function VP(e){if(e.length===0)return null;let t=e.map(i=>dt(Ei.dirname(i))),n=t[0].split("/").filter(Boolean);for(let i of t.slice(1)){let r=i.split("/").filter(Boolean),o=[],s=Math.min(n.length,r.length);for(let a=0;a<s&&n[a]===r[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function qP(e,t,n,i){return n?e.kind==="symbol"&&i.length===1?i[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":cf(n,"package")?"package-level-shared":cf(n,"app")?"app-level-shared":lf(n,["feature","domain","module"])||lf(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function UP(e,t,n,i,r,o,s){let a=WP(e,i);if(a)return rn(a);let c=eN(t.file),l=zP(e,n,c,r,s);if(l)return l;let u=i;if(dt(n)===dt(u))return rn(`${n} is already the nearest common owner for its consumers.`);let d=GP(u,n,c,s);return d||JP(u,n,c,o,s)}function WP(e,t){return t?e==="no-exact-consumers"||e==="repository-level-review"?"The inferred owner is too broad or unsupported for an exact destination.":null:"No consumer owner could be inferred from the current index."}function zP(e,t,n,i,r){if(e==="same-file"){let o=i[0]??null;return o?Ac(o):rn("No same-file consumer path was available.")}if(e==="sibling-folder"&&i.length===1){let o=dt(Ei.dirname(i[0])),s=ff(t,n,o,r);return s?rn(s):Ac(o)}return null}function GP(e,t,n,i){return rN(e)?mf(e,t,n,i,`Nearest shared owner ${e} is outside source root ${n}.`):null}function JP(e,t,n,i,r){if(e===".")return rn("The nearest common owner is the repository root.");let o=`${e}/shared`,s=mf(o,t,n,r,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||i.has(o)?s:rn(`${o} does not exist in the indexed project.`)}function mf(e,t,n,i,r){if(!pf(e,n))return rn(r);let o=ff(t,n,e,i);return o?rn(o):Ac(e)}function Ac(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function rn(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function KP(e,t,n,i,r,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),i.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&r.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function QP(e,t,n,i,r,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${i.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),r?s.push(`Suggested home is ${r}.`):o&&s.push(`No exact suggested home: ${o}`),s}function XP(e,t,n){return e==="no-exact-consumers"?"Review references before moving; no consumers were found.":e==="repository-level-review"?"Keep this as a broad locality signal; the inferred owner is too general for automatic relocation.":t?`Review whether ${n==="exact"?"symbol usage":"module import"} supports moving or extracting toward ${t}.`:"Review ownership manually before changing structure."}function YP(e,t){return af(t)-af(e)||e.candidatePath.localeCompare(t.candidatePath)}function af(e){let t=e.consumerFiles.length*10;return e.consumerCoverage==="exact"&&(t+=5),e.suggestedHome&&(t+=3),e.recommendedTier==="repository-level-review"&&(t-=8),e.recommendedTier==="no-exact-consumers"&&(t-=12),t}function ZP(e){let t=new Set(["."]);for(let n of e){let i=dt(Ei.dirname(n));for(;!t.has(i)&&(t.add(i),i!==".");)i=dt(Ei.dirname(i))}return t}function eN(e){let t=$c(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function pf(e,t){let n=dt(e),i=dt(t);return i==="."||n===i||n.startsWith(`${i}/`)}function tN(e,t,n){let i=$c(e),r=$c(t);return(pf(e,t)?i.slice(r.length):i).some(s=>n.has(s.toLowerCase()))}function ff(e,t,n,i){return dt(e)===dt(n)||!tN(e,t,i)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function nN(...e){let t=new Set(FP);for(let n of e)for(let i of n??[]){let r=iN(i);r&&t.add(r)}return t}function iN(e){let t=e.trim().toLowerCase();return t===""?null:t}function cf(e,t){return jc(e).includes(t)}function lf(e,t){let n=jc(e);return t.some(i=>n.includes(i))}function rN(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?TP.has(n):!1}function Bc(e){return e.replaceAll("\\","/").replace(/^\.\//,"")}function dt(e){let t=Bc(e);return t===""?".":t}function $c(e){let t=Bc(e);return t==="."?[]:t.split("/").filter(Boolean)}function Mc(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function gf(e){return Hc([...e]).sort((t,n)=>t.localeCompare(n))}function Hc(e){return[...new Set(e)]}function Tr(e,t,n={}){let{maxDepth:i=5,scope:r}=n,o=V(e,t);if(!o)return[];let s=[],a=new Set([o.symbolId]),c=new Set,l=[o];for(let u=1;u<=i&&l.length!==0;u++){let d=[];for(let m of l)for(let p of oN(e,m,r)){let f=`${p.file}|${p.shortName}`;if(p.symbolId!==null){if(a.has(p.symbolId))continue;a.add(p.symbolId)}else if(c.has(f))continue;c.add(f),s.push({symbol:p.symbol,shortName:p.shortName,file:p.file,depth:u}),p.symbolId!==null&&p.symbolMatch&&d.push(p.symbolMatch)}l=d}return s.sort((u,d)=>u.depth-d.depth||u.file.localeCompare(d.file)),s}function oN(e,t,n){let i=tt(e,t,{limit:500}).filter(l=>!e.isIgnored(l.file)).filter(l=>!n||l.file.includes(n)),r=new Set(i.map(l=>l.file)),o=[];for(let l of sN(e,t,n)){if(r.has(l))continue;let u=Q(e,l),d=u.length>0?Qe(u,u[0].startLine):null;o.push({symbol:d?.symbol??l,file:l})}let s=[...i,...o],a=[],c=new Set;for(let l of s){let u=gi(e,l.symbol);if(!u){let m=`${l.file}|${l.symbol}`;if(c.has(m))continue;c.add(m),a.push({symbolId:null,symbol:l.symbol,shortName:v(l.symbol),file:l.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!aN(u.symbol))continue;let d=`${u.symbolId}|${u.relativePath}`;c.has(d)||(c.add(d),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:v(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function sN(e,t,n){let i=n?"AND consumer_d.relative_path LIKE ?":"",r=[t.symbolId,t.documentId];return n&&r.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
495
546
|
FROM mentions m
|
|
496
547
|
JOIN chunks c ON m.chunk_id = c.id
|
|
497
548
|
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
@@ -499,48 +550,50 @@ ${m}`,l+=1+m.length,u+=Gr(m),r+=m.length+1}let d=Uv(c);d&&n.push({...d,start:a,e
|
|
|
499
550
|
AND m.role != 1
|
|
500
551
|
AND c.document_id != ?
|
|
501
552
|
${e.pathExclusionsFor("consumer_d")}
|
|
502
|
-
${
|
|
553
|
+
${i}`,...r).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function aN(e){let t=ee(e);return t==="method"||t==="type"||e.endsWith("().")}function Fr(e,t,n={}){let i=Be(e,t);if(!i)return null;let r=cN(e,i);if(!r||e.isIgnored(r.relative_path))return null;let o=[],s=0,a=lN(e,r.relative_path),c=n.semantic===!1?new Map:et(e,a);for(let l of a){let u=uN(e,r,l,c.get(l.symbolId)??new Set);s+=u,o.push({symbol:l.symbol,shortName:v(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:u,riskLevel:dN(u)})}return{file:r.relative_path,symbols:o,totalExternalConsumers:s}}function cN(e,t){return e.get(`SELECT id, relative_path FROM documents
|
|
503
554
|
WHERE relative_path = ?
|
|
504
555
|
${e.pathExclusionsFor("documents")}
|
|
505
|
-
LIMIT 1`,t)??null}function
|
|
556
|
+
LIMIT 1`,t)??null}function lN(e,t){return new A(e).definitionsForFile(t).sort((n,i)=>n.startLine-i.startLine||n.endLine-i.endLine)}function uN(e,t,n,i){let r=e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
506
557
|
FROM mentions m
|
|
507
558
|
JOIN chunks c ON m.chunk_id = c.id
|
|
508
559
|
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
509
560
|
WHERE m.symbol_id = ?
|
|
510
561
|
AND m.role != 1
|
|
511
|
-
AND c.document_id != ?`,n.symbolId,t.id);return new Set([...
|
|
562
|
+
AND c.document_id != ?`,n.symbolId,t.id);return new Set([...r.map(o=>o.relative_path),...[...i].filter(o=>o!==t.relative_path)]).size}function dN(e){return e>10?"high":e>0?"medium":"low"}function cs(e,t={}){let{scope:n,minLoc:i=1,maxDepth:r=5,scanLimit:o}=t,s=new A(e),a=mN(e,n,i,o),c=new Vc;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(hf(e,0,a,c));let d=a.map(g=>g.definition).filter(g=>g!==null),m=new Set(a.map(g=>g.symbol));for(let g=1;g<=r&&d.length>0;g++){let y=s.calleeMap(d,{semantic:!1}),S=new Set;for(let k of d)for(let x of y.get(k.symbolId)??[])m.has(x.symbol)||S.add(x.symbol);let R=[];for(let k of S){m.add(k);let x=yf(e,k);if(!x||e.isIgnored(x.relativePath)||Oe(e,x.relativePath)||fe(e,x.symbol,x.relativePath)||s.fileKind(x.relativePath)==="test"||s.hasSuppressionComment(x))continue;let b=fN(e,x,c);b.removable?R.push(pN(x,"cascade")):b.blockingFiles.length>0&&u.push({shortName:v(x.symbol),file:x.relativePath,blockingFiles:b.blockingFiles.slice(0,3)})}if(R.length===0)break;for(let k of R)c.add(k);l.push(hf(e,g,R,c)),d=R.map(k=>k.definition).filter(k=>k!==null)}let p=l.reduce((g,y)=>g+y.loc,0),f=l.reduce((g,y)=>g+y.entries.length,0);return{batches:l,totalSymbols:f,totalLoc:p,blocked:u}}function mN(e,t,n,i){let r=At(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:i,semantic:!1}),o=[];for(let s of r.symbols)s.kind==="dead-code"&&(Oe(e,s.relativePath)||fe(e,s.symbol,s.relativePath)||o.push({symbol:s.symbol,shortName:s.shortName,file:s.relativePath,startLine:s.startLine,endLine:s.endLine,loc:s.loc,evidence:"graph-fact",definition:yf(e,s.symbol)}));return o}function pN(e,t){return{symbol:e.symbol,shortName:v(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function yf(e,t){let n=e.get(`SELECT d.relative_path
|
|
512
563
|
FROM global_symbols gs
|
|
513
564
|
JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
514
565
|
JOIN documents d ON d.id = der.document_id
|
|
515
566
|
WHERE gs.symbol = ?
|
|
516
|
-
LIMIT 1`,t);return n?
|
|
517
|
-
`),
|
|
518
|
-
`).
|
|
519
|
-
`).
|
|
520
|
-
`)
|
|
521
|
-
`)){let u=l.trim();u!==""&&n.set(u,{commitsAgo:r,addedAt:c})}}return n}function $p(e,t={}){let n=Yt(e);return n?Mp(n,t):null}function Ap(e,t,n={}){let r=Yt(e);return r?t.size===0?[]:Mp(r,n,t):null}function Mp(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=Tp}=t,s=new Map,a=new Map,c=0;for(let d of e.commits){let m=[...new Set(d.files)].sort();if(m.length>o)continue;d.timestamp>c&&(c=d.timestamp);let f=sP(m),h=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(h)for(let g=0;g<m.length;g++)for(let y=g+1;y<m.length;y++){if(n&&!n.has(m[g])&&!n.has(m[y]))continue;let S=`${m[g]}\0${m[y]}`,C=a.get(S)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};C.together+=1,f?C.broadTogether+=1:C.focusedTogether+=1,d.timestamp>C.lastTogetherAt&&(C.lastTogetherAt=d.timestamp),C.timestamps.push(d.timestamp),C.subjects.push(d.subject),a.set(S,C)}}let l=[],u=c-JD;for(let[d,m]of a){let f=m.together;if(f<r)continue;let[h,g]=d.split("\0"),y=s.get(h)??f,S=s.get(g)??f,C=Math.max(f/y,f/S);if(C<i)continue;let k=m.broadTogether/f,D=m.timestamps.filter(x=>x>=u).length;l.push({fileA:h,fileB:g,together:f,confidence:C,changesA:y,changesB:S,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:k,lastTogetherAt:m.lastTogetherAt,recentTogether:D,commitScope:cP(m.broadTogether,f),recency:D>0?"recent":"stale",subjectContext:lP(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function sP(e){return e.length>=GD?!0:aP(e).size>=zD}function aP(e){let t=new Set;for(let n of e){let r=n.indexOf("/");t.add(r>=0?n.slice(0,r):".")}return t}function cP(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function lP(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<XD&&r.push(i);for(let o of uP(i))t.add(o);for(let o of i.match(QD)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function uP(e){let t=new Set,n=YD.exec(e)?.[1]?.toLowerCase();return n&&t.add(dP(n)),/\b(?:feat|feature)\b/i.test(e)&&t.add("feature"),/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i.test(e)&&t.add("fix"),/\b(?:docs?|documentation|guide|readme)\b/i.test(e)&&t.add("docs"),/\brefactor(?:ing|ed)?\b/i.test(e)&&t.add("refactor"),/\btests?\b/i.test(e)&&t.add("test"),/\b(?:release|version|v\d+\.\d+)\b/i.test(e)&&t.add("release"),/\bchore\b/i.test(e)&&t.add("chore"),/\bbuild\b/i.test(e)&&t.add("build"),/\bci\b/i.test(e)&&t.add("ci"),/\bperf(?:ormance)?\b/i.test(e)&&t.add("perf"),[...t]}function dP(e){return e==="feat"?"feature":e}import{existsSync as mP}from"fs";import{join as pP}from"path";function Ic(e){return Lc.test(e)}var Lc=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|CHANGELOG(?:\.[a-z]+)?|.*\.map)$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function In(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=Yt(e),c=t!==void 0,l=$p(e,{minTogether:c?Math.min(r,2):r,minConfidence:c?0:i,maxFilesPerCommit:s});if(!a||!l)return{available:!1,commitsAnalyzed:0,findings:[]};let u=re(e),d=Hp(e),m=Nc(e,u,d),f=n.includeLinked===!0||c,h=[];for(let g of l){if(Lc.test(g.fileA)||Lc.test(g.fileB)||!jp(e,g.fileA)||!jp(e,g.fileB)||c&&!g.fileA.includes(t)&&!g.fileB.includes(t)||!c&&(J(g.fileA)==="test"||J(g.fileB)==="test"||fP(g.fileA,g.fileB)))continue;let y=m(g.fileA,g.fileB);if(!f&&y)continue;let S=Dc(g.fileA,g.fileB),C=Pc(g,S,y);if(h.push({...g,structurallyLinked:y,partnerClass:S.partnerClass,partnerClassReasons:S.reasons,...C?{declaredCouplingSuggestion:C}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:a.commits.length,findings:h}}function jp(e,t){return mP(pP(e.config.projectRoot,t))}function Dc(e,t){let n=Op(e),r=Op(t),i=[],o=c=>{i.includes(c)||i.push(c)},s=(c,l)=>n.tags.has(c)&&r.tags.has(l)||n.tags.has(l)&&r.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:i};if(n.tags.has("test")||r.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:i};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:i};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:i};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:i};let a=wP(n.tokens,r.tokens).filter(c=>!RP.has(c));return Bp(e,t)||a.length>=2?(o(Bp(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:i}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:i})}function Pc(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!vP.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${LP(r)}`,files:r,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function Nc(e,t=re(e),n=Hp(e)){return(r,i)=>gP(t,n,r,i)}function fP(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,r))return!1;let i=e.slice(n+1).split(".")[0],o=t.slice(r+1).split(".")[0];return i!==""&&i===o}function Hp(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function gP(e,t,n,r){return e.get(n)?.has(r)===!0||e.get(r)?.has(n)===!0?!0:t.some(i=>i.has(n)&&i.has(r))}var hP=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,yP=/(?:^|\/)(?:\.[a-z0-9-]+rc|config|configs|settings|\.github)(?:\/|$)|(?:^|\/)(?:package\.json|tsconfig(?:\.[^.]+)?\.json|vite\.config\.[cm]?[jt]s|rollup\.config\.[cm]?[jt]s|eslint\.config\.[cm]?[jt]s)$|\.(?:json|ya?ml|toml|ini|env)$/i,bP=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,SP=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,xP=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,CP=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,vP=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),RP=new Set(["src","lib","app","test","tests","spec","index","main","utils","util","types","type","config","docs","doc"]);function Op(e){let t=e.replace(/\\/g,"/"),n=new Set;return hP.test(t)&&n.add("doc"),yP.test(t)&&n.add("config"),bP.test(t)&&n.add("schema"),SP.test(t)&&n.add("script"),xP.test(t)&&n.add("model"),CP.test(t)&&n.add("view"),J(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:kP(t)}}function Bp(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/"),i=n>=0?e.slice(0,n):"",o=r>=0?t.slice(0,r):"";return i!==""&&i===o}function kP(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}function wP(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function LP(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as it}from"child_process";import{existsSync as IP,readFileSync as DP}from"fs";import{basename as Vp}from"path";function Ko(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=[],t.set(n.file,r)),r.push(n)}return t}var Ec="Unable to compute git diff.";function xr(e,t={}){let n=t.plan??gt(e,t);return n.note?PP(n.note,n.changedFileLines):n.changedFiles.length===0?NP(n.changedFileLines):Qo(n.changedFiles,[Xo(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function gt(e,t={}){let{base:n="HEAD"}=t;try{let r=EP(e.config.projectRoot,n),i=OP(e,r),o=BP(e,TP(e.config.projectRoot,n));return{changedFileLines:r,changedFiles:i,changedRanges:o,renamedFiles:$P(e.config.projectRoot,n,i),note:r.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Ec}}}function Xo(e,t,n,r=[]){let i=new T(e),o=new Set(n),s=Ko(r),a=[],c=new Map,l=t.flatMap(h=>i.definitionsForFile(h)).filter(JP).filter(h=>VP(h,s)).sort((h,g)=>h.relativePath.localeCompare(g.relativePath)||h.startLine-g.startLine),u=l.map(h=>h.symbolId),d=WP(e,u),m=GP(e,u,n),f=mt(e,l.filter(h=>d.get(h.symbolId)===0));for(let h of l)UP(e,h,o,a,c,f.get(h.symbolId)??new Set,d.get(h.symbolId)??0,m.get(h.symbolId)??new Set);return{changedSymbols:a,consumerEntries:[...c.entries()].map(([h,g])=>({file:h,symbols:[...g].sort()}))}}function Qo(e,t){let n=new Map,r=t.flatMap(o=>o.changedSymbols);for(let o of t)for(let s of o.consumerEntries){let a=n.get(s.file);a||(a=new Set,n.set(s.file,a));for(let c of s.symbols)a.add(c)}let i=zP(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:i.length}}}function PP(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function NP(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function EP(e,t){let n=it("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=it("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=it("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,r,i].flatMap(o=>o.split(`
|
|
522
|
-
`)
|
|
523
|
-
`).
|
|
524
|
-
`),...r.
|
|
525
|
-
`)
|
|
526
|
-
`)
|
|
527
|
-
|
|
528
|
-
`)
|
|
567
|
+
LIMIT 1`,t);return n?Q(e,n.relative_path).find(i=>i.symbol===t)??null:null}function fN(e,t,n){let i=Ln(e,t);if(i.length===0)return{removable:!1,blockingFiles:[]};let r=new Set;for(let o of i)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||r.add(o.file);return{removable:r.size===0,blockingFiles:[...r]}}function hf(e,t,n,i){let r=[...n].sort((a,c)=>a.file.localeCompare(c.file)||a.startLine-c.startLine),o=new Set(r.map(a=>a.file)),s=[];for(let a of o){let c=Q(e,a);c.length>0&&c.every(l=>i.contains(a,l.startLine))&&s.push(a)}return{depth:t,entries:r.map(({definition:a,...c})=>c),loc:r.reduce((a,c)=>a+c.loc,0),filesEmptied:s.sort()}}var Vc=class{ranges=new Map;add(t){let n=this.ranges.get(t.file)??[];n.push({start:t.startLine,end:t.endLine}),this.ranges.set(t.file,n)}contains(t,n){let i=this.ranges.get(t);return i?i.some(r=>n>=r.start&&n<=r.end):!1}};import{createHash as j0}from"crypto";import{existsSync as ig}from"fs";import{execFileSync as gN}from"child_process";var ls=2e3,qc=50,hN=64,yN=8,bN=3,SN=2160*60*60,xN=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,CN=3,vN=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,RN=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function Uc(e){let t=re(e,{clearGroups:["whole-project"]});return(n,i)=>{let r=xf(n.config.projectRoot);if(!r)return null;let o=t.has(n)?t.get(n,()=>({head:"",value:null})):null;return o&&o.head===r?o.value:(t.invalidate(n),t.get(n,()=>({head:r,value:i(n.config.projectRoot,r)})).value)}}var kN=Uc("git-commit-history");function sn(e){return kN(e,wN)}function xf(e){try{return on(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function on(e,t){return gN("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function wN(e,t){let n;try{n=on(e,["log","--no-merges","--name-only","-n",String(ls),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...Gc(n,qc)}}function IN(e){return xN.test(e.subject)}function us(e){let t=sn(e);if(!t)return null;let n=new Map;for(let i of t.commits){let r=IN(i);for(let o of i.files){let s=n.get(o)??{changes:0,fixChanges:0,lastChangedAt:0};s.changes+=1,r&&(s.fixChanges+=1),i.timestamp>s.lastChangedAt&&(s.lastChangedAt=i.timestamp),n.set(o,s)}}return n}function Cf(e){let t=sn(e);if(!t||t.commits.length===0)return null;let n=t.commits.map(i=>i.files.length).filter(i=>i>0).sort((i,r)=>i-r);return n.length===0?null:{medianFilesPerCommit:bf(n,.5),p90FilesPerCommit:bf(n,.9),commitsAnalyzed:n.length}}function bf(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var LN=Uc("git-tracked-files");function Wc(e){return LN(e,t=>{try{let n=on(t,["ls-files"]);return new Set(n.split(`
|
|
568
|
+
`).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}})}var DN=Uc("git-file-adds"),Sf="__git__/file-adds";function vf(e){return DN(e,(t,n)=>PN(e,t,n))}function PN(e,t,n){let i=EN(ae(e,"git-file-adds",Sf,n));if(i)return i;let r=TN(t);return r&&ce(e,"git-file-adds",Sf,n,NN(r)),r}function NN(e){return JSON.stringify([...e.entries()])}function EN(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let i of t){if(!Array.isArray(i)||i.length!==2||typeof i[0]!="string")return null;let r=i[1];if(!r||typeof r.commitsAgo!="number"||!Number.isFinite(r.commitsAgo)||typeof r.addedAt!="number"||!Number.isFinite(r.addedAt))return null;n.set(i[0],{commitsAgo:r.commitsAgo,addedAt:r.addedAt})}return n}catch{return null}}function TN(e){let t;try{t=on(e,["log","--no-merges","--diff-filter=A","--name-only","-n",String(ls),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let n=new Map,i=-1;for(let r of t.split("")){if(r.trim()==="")continue;i+=1;let o=r.indexOf(`
|
|
569
|
+
`),s=o>=0?r.slice(0,o):r,[,a]=s.split("\0"),c=Number(a)||0;if(!(o<0))for(let l of r.slice(o+1).split(`
|
|
570
|
+
`)){let u=l.trim();u!==""&&n.set(u,{commitsAgo:i,addedAt:c})}}return n}function Rf(e,t={}){let n=sn(e);return n?zc(n,t):null}function FN(e,t,n={}){let i=sn(e);return i?t.size===0?[]:zc(i,n,t):null}function kf(e,t,n={}){if(t.size===0)return[];let i=xf(e.config.projectRoot);if(!i)return null;let r=n.maxFilesPerCommit??qc;if(t.size>hN)return FN(e,t,n);let o=_N(e.config.projectRoot,i,t,r);return o?zc(o,n,t):null}function zc(e,t,n){let{minTogether:i=4,minConfidence:r=.6,maxFilesPerCommit:o=qc}=t,s=new Map,a=new Map,c=e.newestAnalyzedAt??0;for(let d of e.commits){let m=[...new Set(d.files)].sort();if(m.length>o)continue;e.newestAnalyzedAt===void 0&&d.timestamp>c&&(c=d.timestamp);let p=MN(m),f=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(f)for(let g=0;g<m.length;g++)for(let y=g+1;y<m.length;y++){if(n&&!n.has(m[g])&&!n.has(m[y]))continue;let S=`${m[g]}\0${m[y]}`,R=a.get(S)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};R.together+=1,p?R.broadTogether+=1:R.focusedTogether+=1,d.timestamp>R.lastTogetherAt&&(R.lastTogetherAt=d.timestamp),R.timestamps.push(d.timestamp),R.subjects.push(d.subject),a.set(S,R)}}let l=[],u=c-SN;for(let[d,m]of a){let p=m.together;if(p<i)continue;let[f,g]=d.split("\0"),y=s.get(f)??p,S=s.get(g)??p,R=Math.max(p/y,p/S);if(R<r)continue;let k=m.broadTogether/p,x=m.timestamps.filter(b=>b>=u).length;l.push({fileA:f,fileB:g,together:p,confidence:R,changesA:y,changesB:S,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:k,lastTogetherAt:m.lastTogetherAt,recentTogether:x,commitScope:jN(m.broadTogether,p),recency:x>0?"recent":"stale",subjectContext:BN(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function _N(e,t,n,i){let r;try{r=AN(e)}catch{return null}if(r.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let o;try{o=on(e,["log","--no-merges","--format=%H","-n",String(ls),"--",...[...n].sort()])}catch{return null}let s=new Set(r.map(d=>d.hash)),a=o.split(`
|
|
571
|
+
`).map(d=>d.trim()).filter(d=>d!==""&&s.has(d)),c=$N(e,r,i);if(a.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:c};let l;try{l=on(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...a])}catch{return null}let u=Gc(l,i);return{head:t,...u,newestAnalyzedAt:c}}function AN(e){return on(e,["log","--no-merges","--format=%H%x00%ct","-n",String(ls)]).split(`
|
|
572
|
+
`).map(n=>n.trim()).filter(n=>n!=="").map(n=>{let[i,r]=n.split("\0");return{hash:i??"",timestamp:Number(r)||0}}).filter(n=>n.hash!=="")}function $N(e,t,n){for(let r=0;r<t.length;r+=20){let o=t.slice(r,r+20),s;try{s=on(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...o.map(c=>c.hash)])}catch{return t[0]?.timestamp??0}let a=Gc(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function Gc(e,t){let n=[],i=0;for(let r of e.split("")){if(r.trim()==="")continue;let o=r.indexOf(`
|
|
573
|
+
`),s=o>=0?r.slice(0,o):r,[a,c,l]=s.split("\0");if(!a||!c)continue;let u=o>=0?r.slice(o+1).split(`
|
|
574
|
+
`).map(d=>d.trim()).filter(d=>d!==""):[];if(u.length>t){i+=1;continue}n.push({hash:a,timestamp:Number(c)||0,subject:l??"",files:u})}return{commits:n,skippedBulkCommits:i}}function MN(e){return e.length>=yN?!0:ON(e).size>=bN}function ON(e){let t=new Set;for(let n of e){let i=n.indexOf("/");t.add(i>=0?n.slice(0,i):".")}return t}function jN(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function BN(e){let t=new Set,n=[],i=[];for(let r of e){!i.includes(r)&&i.length<CN&&i.push(r);for(let o of HN(r))t.add(o);for(let o of r.match(vN)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:i,externalIssueLabelStatus:"unavailable"}}function HN(e){let t=new Set,n=RN.exec(e)?.[1]?.toLowerCase();return n&&t.add(VN(n)),/\b(?:feat|feature)\b/i.test(e)&&t.add("feature"),/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i.test(e)&&t.add("fix"),/\b(?:docs?|documentation|guide|readme)\b/i.test(e)&&t.add("docs"),/\brefactor(?:ing|ed)?\b/i.test(e)&&t.add("refactor"),/\btests?\b/i.test(e)&&t.add("test"),/\b(?:release|version|v\d+\.\d+)\b/i.test(e)&&t.add("release"),/\bchore\b/i.test(e)&&t.add("chore"),/\bbuild\b/i.test(e)&&t.add("build"),/\bci\b/i.test(e)&&t.add("ci"),/\bperf(?:ormance)?\b/i.test(e)&&t.add("perf"),[...t]}function VN(e){return e==="feat"?"feature":e}import{existsSync as qN}from"fs";import{join as UN}from"path";function Kc(e){return Jc.test(e)}var Jc=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|CHANGELOG(?:\.[a-z]+)?|.*\.map)$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function Mn(e,t,n={}){let{minTogether:i=4,minConfidence:r=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=sn(e),c=t!==void 0,l=Rf(e,{minTogether:c?Math.min(i,2):i,minConfidence:c?0:r,maxFilesPerCommit:s});if(!a||!l)return{available:!1,commitsAnalyzed:0,findings:[]};let u=pe(e),d=Df(e),m=Yc(e,u,d),p=n.includeLinked===!0||c,f=[];for(let g of l){if(Jc.test(g.fileA)||Jc.test(g.fileB)||!wf(e,g.fileA)||!wf(e,g.fileB)||c&&!g.fileA.includes(t)&&!g.fileB.includes(t)||!c&&(X(g.fileA)==="test"||X(g.fileB)==="test"||WN(g.fileA,g.fileB)))continue;let y=m(g.fileA,g.fileB);if(!p&&y)continue;let S=Qc(g.fileA,g.fileB),R=Xc(g,S,y);if(f.push({...g,structurallyLinked:y,partnerClass:S.partnerClass,partnerClassReasons:S.reasons,...R?{declaredCouplingSuggestion:R}:{}}),f.length>=o)break}return{available:!0,commitsAnalyzed:a.commits.length,findings:f}}function wf(e,t){return qN(UN(e.config.projectRoot,t))}function Qc(e,t){let n=If(e),i=If(t),r=[],o=c=>{r.includes(c)||r.push(c)},s=(c,l)=>n.tags.has(c)&&i.tags.has(l)||n.tags.has(l)&&i.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:r};if(n.tags.has("test")||i.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:r};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:r};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:r};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:r};let a=nE(n.tokens,i.tokens).filter(c=>!eE.has(c));return Lf(e,t)||a.length>=2?(o(Lf(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:r}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:r})}function Xc(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!ZN.has(t.partnerClass))return;let i=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${iE(i)}`,files:i,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function Yc(e,t=pe(e),n=Df(e)){return(i,r)=>zN(t,n,i,r)}function WN(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,i))return!1;let r=e.slice(n+1).split(".")[0],o=t.slice(i+1).split(".")[0];return r!==""&&r===o}function Df(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function zN(e,t,n,i){return e.get(n)?.has(i)===!0||e.get(i)?.has(n)===!0?!0:t.some(r=>r.has(n)&&r.has(i))}var GN=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,JN=/(?:^|\/)(?:\.[a-z0-9-]+rc|config|configs|settings|\.github)(?:\/|$)|(?:^|\/)(?:package\.json|tsconfig(?:\.[^.]+)?\.json|vite\.config\.[cm]?[jt]s|rollup\.config\.[cm]?[jt]s|eslint\.config\.[cm]?[jt]s)$|\.(?:json|ya?ml|toml|ini|env)$/i,KN=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,QN=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,XN=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,YN=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,ZN=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),eE=new Set(["src","lib","app","test","tests","spec","index","main","utils","util","types","type","config","docs","doc"]);function If(e){let t=e.replace(/\\/g,"/"),n=new Set;return GN.test(t)&&n.add("doc"),JN.test(t)&&n.add("config"),KN.test(t)&&n.add("schema"),QN.test(t)&&n.add("script"),XN.test(t)&&n.add("model"),YN.test(t)&&n.add("view"),X(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:tE(t)}}function Lf(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/"),r=n>=0?e.slice(0,n):"",o=i>=0?t.slice(0,i):"";return r!==""&&r===o}function tE(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}function nE(e,t){let n=new Set(t);return[...new Set(e.filter(i=>n.has(i)))].sort()}function iE(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as mt}from"child_process";import{existsSync as rE,readFileSync as oE}from"fs";import{basename as Pf}from"path";function ds(e){let t=new Map;for(let n of e){let i=t.get(n.file);i||(i=[],t.set(n.file,i)),i.push(n)}return t}var Zc="Unable to compute git diff.";function Ti(e,t={}){let n=t.plan??vt(e,t);return n.note?sE(n.note,n.changedFileLines):n.changedFiles.length===0?aE(n.changedFileLines):ps(n.changedFiles,[ms(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function vt(e,t={}){let{base:n="HEAD"}=t;try{let i=cE(e.config.projectRoot,n),r=hE(e,i),o=yE(e,lE(e.config.projectRoot,n));return{changedFileLines:i,changedFiles:r,changedRanges:o,renamedFiles:mE(e.config.projectRoot,n,r),note:i.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Zc}}}function ms(e,t,n,i=[]){let r=new A(e),o=new Set(n),s=ds(i),a=[],c=new Map,l=t.flatMap(f=>r.definitionsForFile(f)).filter(wE).filter(f=>SE(f,s)).sort((f,g)=>f.relativePath.localeCompare(g.relativePath)||f.startLine-g.startLine),u=l.map(f=>f.symbolId),d=vE(e,u),m=RE(e,u,n),p=et(e,l.filter(f=>d.get(f.symbolId)===0));for(let f of l)CE(e,f,o,a,c,p.get(f.symbolId)??new Set,d.get(f.symbolId)??0,m.get(f.symbolId)??new Set);return{changedSymbols:a,consumerEntries:[...c.entries()].map(([f,g])=>({file:f,symbols:[...g].sort()}))}}function ps(e,t){let n=new Map,i=t.flatMap(o=>o.changedSymbols);for(let o of t)for(let s of o.consumerEntries){let a=n.get(s.file);a||(a=new Set,n.set(s.file,a));for(let c of s.symbols)a.add(c)}let r=kE(n);return{changedFiles:[...e],changedSymbols:i,affectedConsumers:r,summary:{totalChangedFiles:e.length,totalChangedSymbols:i.length,totalAffectedFiles:r.length}}}function sE(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function aE(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function cE(e,t){let n=mt("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=mt("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=mt("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,i,r].flatMap(o=>o.split(`
|
|
575
|
+
`)).map(o=>o.trim()).filter(o=>o.length>0))]}function lE(e,t){let n=mt("git",["diff","--unified=0",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=mt("git",["diff","--unified=0","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return Af([...Tf(n),...Tf(i)])}function el(e,t,n){try{return mt("git",["show",`${t}:./${n}`],{encoding:"utf-8",cwd:e,timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return null}}function _r(e,t,n=[]){let i=uE(e,t,n);return r=>(i.has(r)||i.set(r,el(e,t,r)),i.get(r)??null)}function Ar(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(i=>[i.to,i.from]));return[...new Set(t.map(i=>n.get(i)??i))]}function uE(e,t,n){let i=[...new Set(n)],r=new Map;if(i.length===0)return r;try{let o=i.map(a=>`${t}:./${a}
|
|
576
|
+
`).join(""),s=mt("git",["cat-file","--batch"],{cwd:e,input:o,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]});return dE(s,i)}catch{for(let o of i)r.set(o,el(e,t,o));return r}}function dE(e,t){let n=new Map,i=0;for(let r of t){let o=e.indexOf(10,i);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(i,o).toString("utf-8");if(i=o+1,s.endsWith(" missing")){n.set(r,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,c,l]=a,u=Number(l);if(!Number.isFinite(u)||u<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(i+u>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(i,i+u);n.set(r,c==="blob"?d.toString("utf-8"):null),i+=u,e[i]===10&&(i+=1)}return n}function mE(e,t,n){if(n.length===0)return[];let i=new Map,r=new Set;for(let s of fE(e,t))n.includes(s.to)&&(i.set(s.to,s),r.add(s.from));let o=pE(e,t);if(o.length===0)return[...i.values()].sort((s,a)=>s.to.localeCompare(a.to));for(let s of n){if(i.has(s)||!rE(`${e}/${s}`))continue;let a=o.filter(u=>!r.has(u)).filter(u=>Pf(u)===Pf(s));if(a.length===0)continue;let c=oE(`${e}/${s}`,"utf-8"),l=a.map(u=>({from:u,to:s,similarity:gE(el(e,t,u)??"",c)})).sort((u,d)=>d.similarity-u.similarity)[0];l&&l.similarity>=.45&&(i.set(s,l),r.add(l.from))}return[...i.values()].sort((s,a)=>s.to.localeCompare(a.to))}function pE(e,t){let n=mt("git",["diff","--name-only","--diff-filter=D",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=mt("git",["diff","--name-only","--diff-filter=D","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([...Ef(n),...Ef(i)])]}function fE(e,t){let n=mt("git",["diff","--name-status","--find-renames",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=mt("git",["diff","--name-status","--find-renames","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...n.split(`
|
|
577
|
+
`),...i.split(`
|
|
578
|
+
`)].map(r=>r.trim()).filter(r=>r.startsWith("R")).map(r=>r.split(" ")).filter(r=>r.length>=3).map(([r,o,s])=>({from:o,to:s,similarity:Number(r.slice(1))/100}))}function gE(e,t){let n=new Set(Nf(e)),i=new Set(Nf(t));if(n.size===0&&i.size===0)return 1;if(n.size===0||i.size===0)return 0;let r=0;for(let o of n)i.has(o)&&(r+=1);return 2*r/(n.size+i.size)}function Nf(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function Ef(e){return e.split(`
|
|
579
|
+
`).map(t=>t.trim()).filter(t=>t.length>0)}function hE(e,t){let n=_f(e),i=[];for(let r of t){let o=n(r);o&&!e.isIgnored(o)&&i.push(o)}return i}function yE(e,t){let n=_f(e),i=[];for(let r of t){let o=n(r.file);o&&!e.isIgnored(o)&&i.push({...r,file:o})}return Af(i)}function _f(e){let t=e.all(`SELECT relative_path FROM documents
|
|
580
|
+
ORDER BY id`).map(i=>i.relative_path),n=new Map(t.map(i=>[i,i]));return i=>{let r=i.replace(/\\/g,"/"),o=n.get(r);return o||(t.find(s=>s.endsWith(r))??null)}}function Tf(e){let t=[],n=null;for(let i of e.split(`
|
|
581
|
+
`)){if(i.startsWith("+++ ")){n=bE(i.slice(4).trim());continue}if(!n||!i.startsWith("@@ "))continue;let r=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(i);if(!r)continue;let o=Math.max(0,Number(r[1])-1),s=r[2]===void 0?1:Number(r[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function bE(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function Af(e){let t=new Set,n=[];for(let i of e){let r=`${i.file}:${i.startLine}:${i.endLine}`;t.has(r)||(t.add(r),n.push(i))}return n}function SE(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(i=>xE(e.startLine,e.endLine,i.startLine,i.endLine))}function xE(e,t,n,i){return e<=i&&n<=t}function CE(e,t,n,i,r,o,s,a){let c=Math.max(s,o.size);if(!IE(t,c))return;let l=v(t.symbol);i.push({symbol:t.symbol,shortName:l,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:c});for(let u of a)Ff(e,n,r,u,l);for(let u of o)Ff(e,n,r,u,l)}function vE(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT m.symbol_id, COUNT(DISTINCT c.document_id) AS fan_in
|
|
529
582
|
FROM mentions m
|
|
530
583
|
JOIN chunks c ON m.chunk_id = c.id
|
|
531
584
|
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
532
585
|
AND m.role != 1
|
|
533
|
-
GROUP BY m.symbol_id`,...t);return new Map(n.map(
|
|
586
|
+
GROUP BY m.symbol_id`,...t);return new Map(n.map(i=>[i.symbol_id,i.fan_in]))}function RE(e,t,n){if(t.length===0||n.length===0)return new Map;let i=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
|
|
534
587
|
FROM mentions m
|
|
535
588
|
JOIN chunks c ON m.chunk_id = c.id
|
|
536
589
|
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
537
590
|
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
538
591
|
AND m.role != 1
|
|
539
592
|
AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
|
|
540
|
-
${e.pathExclusionsFor("ref_d")}`,...t,...n),
|
|
541
|
-
`).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function
|
|
542
|
-
`).toLowerCase(),n=[],
|
|
543
|
-
${n}`.toLowerCase(),i=Dn(r,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(i.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${i.join(", ")}`]};let o=Dn(r,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function $c(e,t){return{actionTier:yN(e,t.docIntent),docIntent:t.docIntent,docIntentReasons:t.reasons}}function yN(e,t){return t==="historical-note"?"support":e==="co-change"?"signal":"direct"}function bN(e){let t=Yt(e);if(!t)return null;let n=wc(e)??new Set,r=new Map,i=new Map,o=new Set;for(let s of t.commits){let a=[...new Set(s.files)],c=a.filter(u=>Si.test(u)),l=a.filter(u=>!Si.test(u));for(let u of a){o.add(u);let d=r.get(u)??[];d.push(s.timestamp),r.set(u,d)}for(let u of c){let d=i.get(u);d||(d=new Map,i.set(u,d));for(let m of l)d.set(m,(d.get(m)??0)+1)}}return{changeTimes:r,coupling:i,docFiles:[...n].filter(s=>Si.test(s)),everSeenInHistory:o,historyCommitCount:t.commits.length,tracked:n,trackedBySuffix:rf(n)}}function tf(e,t){if(t.size===0)return[];let n=wc(e)??new Set,r=rf(n),i=SN(t,r),o=[];for(let s of n){if(!nf(e,s))continue;let a=sf(e,s);if(!a)continue;let c=xN(a,t,i,n,r);if(c.size===0)continue;let l=[...new Set([...c.values()].flatMap(f=>[...f]))],u=of(e,s,l),d=[...c].map(([f,h])=>({file:f,contexts:ns([...h].flatMap(g=>u.get(g)??[])).slice(0,3)})).filter(f=>f.contexts.length>0),m=[...c.keys()];if(m.length>0){let f=m.sort();o.push({doc:s,cited:f,citations:d,citedClaims:ns(d.flatMap(h=>h.contexts)).slice(0,3)})}}return o}function nf(e,t){return Si.test(t)&&!fN(t)&&Zp(xi(e.config.projectRoot,t))}function rf(e){let t=new Map;for(let n of e){let r=n.split("/");for(let i of[2,3]){if(r.length<i)continue;let o=r.slice(-i).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function SN(e,t){let n=new Set(e);for(let r of e){let i=r.split("/");for(let o of[2,3]){if(i.length<o)continue;let s=i.slice(-o).join("/"),a=t.get(s);a?.length===1&&a[0]===r&&n.add(s)}}return n}function xN(e,t,n,r,i){let o=new Map;for(let s of e){if(!n.has(s))continue;let a;if(r.has(s))a=s;else{let l=i.get(s);l?.length===1&&(a=l[0])}if(!a||!t.has(a))continue;let c=o.get(a)??new Set;c.add(s),o.set(a,c)}return o}function CN(e,t,n,r,i){let o=new Set,s=new Set,a=sf(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=of(e,t,a),l=new Map,u=(d,m)=>{let f=c.get(m);if(!f||f.length===0)return;let h=l.get(d)??[];h.push(...f),l.set(d,ns(h).slice(0,3))};for(let d of a){if(n.has(d)){o.add(d),u(d,d);continue}let m=r.get(d);if(m&&m.length===1){o.add(m[0]),u(m[0],d);continue}m&&m.length>1||i.has(d)&&s.add(d)}return{resolved:o,broken:[...s],citations:[...l].map(([d,m])=>({file:d,contexts:m}))}}function of(e,t,n){let r;try{r=Ac(xi(e.config.projectRoot,t),"utf-8").split(/\r?\n/)}catch{return new Map}let i=new Set(n),o=new Map;for(let s=0;s<r.length;s+=1){let a=r[s]??"";for(let c of a.matchAll(ef)){let l=c[0].replace(/^\.?\//,"");if(!i.has(l))continue;let u=ts(r,s);if(u.length===0)continue;let d=o.get(l)??[];d.push(u),o.set(l,ns(d).slice(0,3))}}return o}function ns(e){let t=[];for(let n of new Set(e))t.some(r=>vN(r,n))||t.push(n);return t}function vN(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=Math.min(n.length,r.length);if(i===0)return!1;if(i<3)return e.includes(t)||t.includes(e);let o=new Set(r),s=n.filter(a=>o.has(a)).length;return s>=3&&s/i>=.6}function sf(e,t){let n;try{n=Ac(xi(e.config.projectRoot,t),"utf-8")}catch{return null}let r=Ye(e,t,n),i=Mt(e,"doc-path-tokens",t,r);if(i!==null)try{return JSON.parse(i)}catch{}let o=[...new Set([...n.matchAll(ef)].map(s=>s[0].replace(/^\.?\//,"")))];return jt(e,"doc-path-tokens",t,r,JSON.stringify(o)),o}import{existsSync as FE,readFileSync as $E,writeFileSync as AE}from"fs";import{isAbsolute as ME,join as jE}from"path";var le={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0,semantic:!1},isolated:{minLoc:3,semantic:!1},similar:{minSimilarity:.6,limit:50,minCallees:4,semantic:!1},extract:{minLoc:15,minCallees:5,limit:50,semantic:!1},wrappers:{maxLoc:15,limit:50,semantic:!1},passthroughs:{maxLoc:15,limit:50,semantic:!1},stale:{minLoc:3,limit:50,semantic:!1},drift:{semantic:!1}};import Ci from"path";function Pn(e){let n=e.replace(/\\/g,"/").split("/").filter(Boolean);return n.length<=1?"(root)":n.length>=3&&["src","lib","app","server","client"].includes(n[0])?`${n[0]}/${n[1]}`:n[0]}function jc(e,t){if(e===t)return"ok";let n=rs(e),r=rs(t);return n&&r?RN(n,r)?"ok":"violation":kN(e,t)}function af(e,t){let n=rs(Pn(e)),r=rs(Pn(t));return!!n&&!!r}function rs(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function RN(e,t){return t==="domain"?!0:e==="domain"?!1:{analysis:new Set(["domain","source","storage","symbols"]),core:new Set(["analysis","domain","resolution","source","storage","symbols"]),"language-parsers":new Set(["domain","resolution","source","storage"]),queries:new Set(["analysis","core","domain","language-parsers","resolution","semantic","source","storage","symbols"]),reindex:new Set(["domain","language-parsers","resolution","runtime","semantic","source","storage","symbols"]),resolution:new Set(["domain","source","storage","symbols"]),runtime:new Set(["domain","queries","reindex","resolution","semantic","source","storage","symbols"]),semantic:new Set(["domain","resolution","storage","symbols"]),source:new Set(["domain","storage"]),storage:new Set(["domain","source"]),symbols:new Set(["analysis","domain","language-parsers","resolution","semantic","source","storage"])}[e]?.has(t)??!1}function kN(e,t){if(t==="shared")return"ok";let n={app:new Set(["core","shared","ui"]),core:new Set(["shared"]),infra:new Set(["core","shared"]),ui:new Set(["core","shared"])};return n[e]?n[e].has(t)?"ok":"violation":null}function Nn(e,t){let{scope:n,minDeviation:r=5}=t??{},i=t?.semantic!==!1,s=new T(e).fileDependencyGraph(n),a=EN(e,n);return DN([...wN(e,s,a,{semantic:i}),...LN(s),...IN(s,r)])}function wN(e,t,n,r){let i=[];for(let[o,s]of t){if(Nt(o))continue;let a=n.get(o)??new Set;for(let c of s)if(!Nt(c)&&!a.has(c)){if(r.semantic&&MN(e,o,c)||jN(e,o,c)||ON(e,o,c)||AN(c)||HN(e,o,c)||BN(c))continue;i.push({file:o,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${o} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."})}}return i}function LN(e){let t=[],n=$N(e);for(let[r,i]of e){if(Nt(r))continue;let o=Pn(r);for(let s of i){if(Nt(s))continue;let a=Pn(s);if(o===a)continue;let c=jc(o,a),l=c?"explicit":"inferred";if((c??n.get(`${o}->${a}`))==="violation"){let d=l==="explicit"?"direct":"signal";t.push({file:r,kind:"layer-violation",description:`Imports from ${a}/ (${s}) \u2014 may cross architectural boundary`,dep:s,detail:`${o}/ should not depend on ${a}/`,actionTier:d,policyBasis:l,evidenceReasons:[`dependency edge exists from ${r} to ${s}`,l==="explicit"?`explicit layer policy rejects ${o}/ -> ${a}/`:`rare cross-layer edge ${o}/ -> ${a}/ is inferred as a violation`],recommendation:l==="explicit"?"Move the dependency behind an allowed layer boundary or document a policy change.":"Review whether this is a real boundary break or an intentional exception before moving code."})}}}return t}function IN(e,t){let n=[];for(let[r,i]of PN(e)){let o=i.filter(a=>!Nt(a));if(o.length<t)continue;let s=NN(e,o);for(let a of o)for(let c of e.get(a)??[])Nt(c)||(s.get(c)??0)===1&&Ci.dirname(c)!==r&&Ci.dirname(c)!==Ci.dirname(r)&&(af(a,c)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${r}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."}))}return n}function DN(e){return{results:e,unusedImports:e.filter(t=>t.kind==="unused-import").length,layerViolations:e.filter(t=>t.kind==="layer-violation").length,patternDeviations:e.filter(t=>t.kind==="pattern-deviation").length}}function PN(e){let t=new Map;for(let n of e.keys()){let r=Ci.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function NN(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Nt(i)||n.set(i,(n.get(i)??0)+1);return n}function EN(e,t){let n=new Map;return TN(e,n,t),FN(e,n),n}function TN(e,t,n){for(let r of _N(e,n))cf(e,t,r.from_file,r.to_file)}function _N(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
|
|
593
|
+
${e.pathExclusionsFor("ref_d")}`,...t,...n),r=new Map;for(let o of i){let s=r.get(o.symbol_id);s||(s=new Set,r.set(o.symbol_id,s)),s.add(o.relative_path)}return r}function Ff(e,t,n,i,r){if(e.isIgnored(i)||t.has(i))return;let o=n.get(i);o||(o=new Set,n.set(i,o)),o.add(r)}function kE(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function wE(e){return!(Ut(e.symbol)||e.parentTypeName!==null&&!le(e.symbol))}function IE(e,t){return le(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}function $f(e){let[t,n]=fs(e,":"),i=t||"unknown",r=(o={})=>{let s=o.actionTier??LE(i);return{sourceAnalyzer:i,actionTier:s,rootCauseKey:o.rootCauseKey??(n||e),label:o.label??`${i} finding`,relatedFiles:o.relatedFiles??[],why:o.why??[],remediation:o.remediation??DE(s,i),file:o.file}};if(!n)return r({rootCauseKey:e,why:["Baseline identity did not include analyzer payload."]});if(["dead","isolated","extract","wrapper","passthrough","stale"].includes(i)){let[o,s]=fs(n,":");return r({file:o,relatedFiles:o?[o]:[],rootCauseKey:s?`${o}:${s}`:n,label:`${i} finding`,why:s?[`Baseline subject: ${s}.`]:[]})}if(i==="cycle"){let o=n.split(">").filter(Boolean);return r({relatedFiles:o,rootCauseKey:n,label:"cycle finding",why:o.length>0?[`Cycle path: ${o.join(" > ")}.`]:[]})}if(i==="similar"){let o=n.split("|").filter(Boolean);return r({relatedFiles:[],rootCauseKey:n,label:"similarity finding",why:o.length>0?[`Similar symbols: ${o.join(" | ")}.`]:[]})}if(i==="drift"){let[o,s]=fs(n,":"),[a,c]=fs(s,":");return r({actionTier:o==="unused-import"?"direct":"signal",file:a,relatedFiles:[...new Set([a,c].filter(Boolean))],rootCauseKey:n,label:`${o||"drift"} finding`,why:[...o?[`Drift kind: ${o}.`]:[],...c?[`Related dependency: ${c}.`]:[]]})}return r({why:["Baseline analyzer prefix is not recognized by this diff-gate version."]})}function LE(e){switch(e){case"dead":case"isolated":case"cycle":case"passthrough":return"direct";case"similar":case"extract":case"wrapper":case"stale":return"signal";default:return"signal"}}function DE(e,t){return e==="direct"?`Fix the new ${t} baseline finding, or knowingly accept it via health --write-baseline.`:`Review the new ${t} baseline signal; fix it if it reflects real debt, or knowingly accept it via health --write-baseline.`}function fs(e,t){let n=e.indexOf(t);return n<0?[e,""]:[e.slice(0,n),e.slice(n+t.length)]}import{existsSync as _E,readFileSync as jf}from"fs";function ys(e,t){let n=PE(e,t)??NE(e,t)??EE(e,t)??TE(e,t);return FE(e,n,t)}function PE(e,t){let n=-1,i=null;for(let r=0;r<=t;r+=1){let o=tl(e[r]??"");o&&(i===null?(i=o,n=r):o===i&&(i=null,n=-1))}if(i===null||n<0)return null;for(let r=t+1;r<e.length;r+=1)if(tl(e[r]??"")===i)return{start:n,end:r+1};return{start:n,end:e.length}}function tl(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function NE(e,t){if(!gs(e[t]??""))return null;let n=t;for(;n>0&&gs(e[n-1]??"");)n-=1;let i=t+1;for(;i<e.length&&gs(e[i]??"");)i+=1;return{start:n,end:i}}function gs(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function EE(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(hs(o)!==null)break;if(nl(o)!==null)return null;n-=1}if(n<0)return null;let i=hs(e[n]??"");if(i===null)return null;let r=n+1;for(;r<e.length;){let o=e[r]??"",s=hs(o);if(s!==null){if(s<=i)break;r+=1;continue}if(nl(o)!==null)break;r+=1}return{start:n,end:r}}function hs(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function TE(e,t){let n=e[t]??"";if(Of(n)||n.trim().length===0)return{start:t,end:t+1};let i=t;for(;i>0&&Mf(e[i-1]??"");)i-=1;let r=t+1;for(;r<e.length&&Mf(e[r]??"");)r+=1;return{start:i,end:r}}function Mf(e){return nl(e)===null}function nl(e){return e.trim().length===0?"blank":Of(e)?"heading":tl(e)?"fence":gs(e)?"table":hs(e)!==null?"list":null}function Of(e){return/^#{1,6}\s+/.test(e.trim())}function FE(e,t,n){let{start:i,end:r}=t;if(r-i>40){let s=Math.floor(20);i=Math.max(i,n-s),r=Math.min(r,i+40),i=Math.max(t.start,r-40)}let o=e.slice(i,r).join(`
|
|
594
|
+
`).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function On(e,t){return t.filter(n=>e.includes(n))}var Fi={classifyCitation:AE,citationContexts:$E,citationKindLabel:OE,citationRemediation:jE,referenceTargets:BE};function AE(e){let t=e.join(`
|
|
595
|
+
`).toLowerCase(),n=[],i=On(t,[".scipquery","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(i.length>0)return n.push(`configuration/example terms near citation: ${i.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let r=On(t,["accepted","intentional","intentionally","retained","historical"]);if(r.length>0)return n.push(`intentional-record terms near citation: ${r.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=On(t,["command","cli","usage","example","run","workflow"]);return o.length>0?(n.push(`guide/reference terms near citation: ${o.join(", ")}`),{citationKind:"guide-reference",actionTier:"signal",reasons:n}):(n.push(e.length>0?"citation appears in prose without config or guide markers":"citation context unavailable"),{citationKind:"behavioral-claim",actionTier:"direct",reasons:n})}function $E(e,t,n){let i;try{i=jf(`${e.config.projectRoot}/${t}`,"utf-8").split(/\r?\n/)}catch{return[]}let r=n.flatMap(ME),o=[];for(let s=0;s<i.length;s+=1){let a=i[s]??"";r.some(c=>a.includes(c))&&o.push(ys(i,s))}return o}function ME(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,i,r)=>n.length>0&&r.indexOf(n)===i)}function OE(e){switch(e){case"behavioral-claim":return"a behavioral doc claim";case"configuration-example":return"a configuration example";case"guide-reference":return"a guide reference";case"intentional-record":return"an intentional record"}}function jE(e,t){switch(e){case"behavioral-claim":return`Re-read ${t} and update the behavioral claim or citation.`;case"configuration-example":return`Verify the configuration example in ${t} still points at the intended file; update only if the example target changed.`;case"guide-reference":return`Verify the guide reference in ${t} still sends readers to the right implementation or command surface.`;case"intentional-record":return`Verify the intentional citation in ${t} is still meant to name this file.`}}function BE(e,t,n){let i=ds(n),r=new Set;for(let o of t)HE(e,o,i.get(o)??[])&&r.add(o);return r}function HE(e,t,n){if(n.length===0)return!1;if(!VE.test(t))return!0;let i=`${e.config.projectRoot}/${t}`;if(!_E(i))return!0;let r=jf(i,"utf-8").split(/\r?\n/),o=qE(r);for(let s of n)for(let a=s.startLine;a<=s.endLine;a+=1)if((r[a]??"").trim()!==""&&!o.has(a))return!0;return!1}var VE=/\.(?:[cm]?[jt]sx?)$/i;function qE(e){let t=new Set,n=!1;for(let i=0;i<e.length;i+=1){let r=e[i].trim();!n&&UE(r)&&(n=!0),n&&(t.add(i),r.endsWith(";")&&(n=!1))}return t}function UE(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}import{existsSync as Bf,readFileSync as rl}from"fs";import{join as Mr}from"path";var $r=/\.(?:md|mdx|rst|txt)$/i;function WE(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var zE=3,GE=/[A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6}\b/g;function ol(e,t={}){let{doc:n,limit:i=20,minCoupling:r=zE}=t,o=QE(e);if(!o)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let s=[];for(let a of o.docFiles){if(n!==void 0&&!a.includes(n)||n===void 0&&!Vf(e,a)||n!==void 0&&!Bf(Mr(e.config.projectRoot,a)))continue;let c=Math.max(0,...o.changeTimes.get(a)??[]),l=JE(e,a),u=new Map,{resolved:d,broken:m,citations:p}=ZE(e,a,o.tracked,o.trackedBySuffix,o.everSeenInHistory),f=new Map(p.map(y=>[y.file,y.contexts]));for(let y of d){if(y===a||$r.test(y))continue;let S=(o.changeTimes.get(y)??[]).filter(R=>R>c).length;S!==0&&u.set(y,{file:y,evidence:"reference",coChanges:0,changesSinceDocUpdate:S,...il("reference",l),citationContexts:f.get(y)})}for(let[y,S]of o.coupling.get(a)??[]){if(S<r||!o.tracked.has(y))continue;let R=(o.changeTimes.get(y)??[]).filter(x=>x>c).length;if(R===0)continue;let k=u.get(y);k?(k.evidence="both",k.coChanges=S,Object.assign(k,il("both",l))):u.set(y,{file:y,evidence:"co-change",coChanges:S,changesSinceDocUpdate:R,...il("co-change",l)})}if(u.size===0&&m.length===0)continue;let g=[...u.values()].sort((y,S)=>S.changesSinceDocUpdate-y.changesSinceDocUpdate);s.push({doc:a,docLastChangedAt:c,staleness:g.reduce((y,S)=>y+S.changesSinceDocUpdate,0)+m.length*10,subjects:g.slice(0,8),brokenReferences:m})}return s.sort((a,c)=>c.staleness-a.staleness),{available:!0,commitsAnalyzed:o.historyCommitCount,docsScanned:o.docFiles.length,findings:s.slice(0,i)}}function JE(e,t){let n;try{n=rl(Mr(e.config.projectRoot,t),"utf8").slice(0,6e3)}catch{return{docIntent:"unknown",reasons:["doc text unavailable"]}}let i=`${t}
|
|
596
|
+
${n}`.toLowerCase(),r=On(i,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(r.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${r.join(", ")}`]};let o=On(i,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function il(e,t){return{actionTier:KE(e,t.docIntent),docIntent:t.docIntent,docIntentReasons:t.reasons}}function KE(e,t){return t==="historical-note"?"support":e==="co-change"?"signal":"direct"}function QE(e){let t=sn(e);if(!t)return null;let n=Wc(e)??new Set,i=new Map,r=new Map,o=new Set;for(let s of t.commits){let a=[...new Set(s.files)],c=a.filter(u=>$r.test(u)),l=a.filter(u=>!$r.test(u));for(let u of a){o.add(u);let d=i.get(u)??[];d.push(s.timestamp),i.set(u,d)}for(let u of c){let d=r.get(u);d||(d=new Map,r.set(u,d));for(let m of l)d.set(m,(d.get(m)??0)+1)}}return{changeTimes:i,coupling:r,docFiles:[...n].filter(s=>$r.test(s)),everSeenInHistory:o,historyCommitCount:t.commits.length,tracked:n,trackedBySuffix:qf(n)}}function Hf(e,t){if(t.size===0)return[];let n=se(),i=0,r=0,o=0,s=0,a=0,c=0;return T("doc-reference.docs-citing-files",()=>{let l=Wc(e)??new Set;i=l.size;let u=qf(l),d=XE(t,u),m=[];for(let p of l){if(!Vf(e,p))continue;n&&(r+=1);let f;try{f=rl(Mr(e.config.projectRoot,p),"utf-8")}catch{n&&(o+=1);continue}if(!tT(f,d)){n&&(s+=1);continue}let g=Uf(e,p,f);if(!g)continue;n&&(a+=1);let y=YE(g.candidates,t,d,l,u);if(y.size===0)continue;let S=[...new Set([...y.values()].flatMap(b=>[...b]))],R=eT(g.contextsByCandidate,S),k=[...y].map(([b,C])=>({file:b,contexts:bs([...C].flatMap(D=>R.get(D)??[])).slice(0,3)})).filter(b=>b.contexts.length>0),x=[...y.keys()];if(x.length>0){n&&(c+=1);let b=x.sort();m.push({doc:p,cited:b,citations:k,citedClaims:bs(k.flatMap(C=>C.contexts)).slice(0,3)})}}return m},()=>({targets:t.size,trackedFiles:i,livingDocs:r,unreadableDocs:o,candidateMisses:s,evidenceDocs:a,citedDocs:c}))}function Vf(e,t){return $r.test(t)&&!WE(t)&&Bf(Mr(e.config.projectRoot,t))}function qf(e){let t=new Map;for(let n of e){let i=n.split("/");for(let r of[2,3]){if(i.length<r)continue;let o=i.slice(-r).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function XE(e,t){let n=new Set(e);for(let i of e){let r=i.split("/");for(let o of[2,3]){if(r.length<o)continue;let s=r.slice(-o).join("/"),a=t.get(s);a?.length===1&&a[0]===i&&n.add(s)}}return n}function YE(e,t,n,i,r){let o=new Map;for(let s of e){if(!n.has(s))continue;let a;if(i.has(s))a=s;else{let l=r.get(s);l?.length===1&&(a=l[0])}if(!a||!t.has(a))continue;let c=o.get(a)??new Set;c.add(s),o.set(a,c)}return o}function ZE(e,t,n,i,r){let o=new Set,s=new Set,a=Uf(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=a.candidates,l=a.contextsByCandidate,u=new Map,d=(m,p)=>{let f=l.get(p);if(!f||f.length===0)return;let g=u.get(m)??[];g.push(...f),u.set(m,bs(g).slice(0,3))};for(let m of c){if(n.has(m)){o.add(m),d(m,m);continue}let p=i.get(m);if(p&&p.length===1){o.add(p[0]),d(p[0],m);continue}p&&p.length>1||r.has(m)&&s.add(m)}return{resolved:o,broken:[...s],citations:[...u].map(([m,p])=>({file:m,contexts:p}))}}function eT(e,t){let n=new Map;for(let i of t){let r=e.get(i);r&&r.length>0&&n.set(i,[...r])}return n}function Uf(e,t,n){let i=n;if(i===void 0)try{i=rl(Mr(e.config.projectRoot,t),"utf-8")}catch{return null}let r=Z(e,t,i),o=ae(e,"doc-path-evidence",t,r);if(o!==null){let a=rT(o);if(a)return a}let s=nT(i);return ce(e,"doc-path-evidence",t,r,iT(s)),s}function tT(e,t){for(let n of t)if(e.includes(n))return!0;return!1}function nT(e){let t=e.split(/\r?\n/),n=new Set,i=new Map;for(let r=0;r<t.length;r+=1){let o=t[r]??"";for(let s of o.matchAll(GE)){let a=s[0].replace(/^\.?\//,"");n.add(a);let c=ys(t,r);if(c.length===0)continue;let l=i.get(a)??[];l.push(c),i.set(a,bs(l).slice(0,3))}}return{candidates:[...n],contextsByCandidate:i}}function iT(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()]};return JSON.stringify(t)}function rT(e){try{let t=JSON.parse(e);if(!pn(t))return null;let n=Me(t.candidates),i=oT(t.contextsByCandidate);return!n||!i?null:{candidates:n,contextsByCandidate:new Map(i)}}catch{return null}}function oT(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string")return null;let i=Me(n[1]);if(!i)return null;t.push([n[0],i])}return t}function bs(e){let t=[];for(let n of new Set(e))t.some(i=>sT(i,n))||t.push(n);return t}function sT(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=Math.min(n.length,i.length);if(r===0)return!1;if(r<3)return e.includes(t)||t.includes(e);let o=new Set(i),s=n.filter(a=>o.has(a)).length;return s>=3&&s/r>=.6}import{existsSync as y0,readFileSync as b0,writeFileSync as S0}from"fs";import{isAbsolute as x0,join as C0}from"path";var be={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0,semantic:!1},isolated:{minLoc:3,semantic:!1},similar:{minSimilarity:.6,limit:50,minCallees:4,semantic:!1},extract:{minLoc:15,minCallees:5,limit:50,semantic:!1},wrappers:{maxLoc:15,limit:50,semantic:!1},passthroughs:{maxLoc:15,limit:50,semantic:!1},stale:{minLoc:3,limit:50,semantic:!1},drift:{semantic:!1}};import Or from"path";function jn(e){let n=e.replace(/\\/g,"/").split("/").filter(Boolean);return n.length<=1?"(root)":n.length>=3&&["src","lib","app","server","client"].includes(n[0])?`${n[0]}/${n[1]}`:n[0]}function sl(e,t){if(e===t)return"ok";let n=Ss(e),i=Ss(t);return n&&i?aT(n,i)?"ok":"violation":cT(e,t)}function Wf(e,t){let n=Ss(jn(e)),i=Ss(jn(t));return!!n&&!!i}function Ss(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function aT(e,t){return t==="domain"?!0:e==="domain"?!1:{analysis:new Set(["domain","source","storage","symbols"]),core:new Set(["analysis","domain","resolution","source","storage","symbols"]),"language-parsers":new Set(["domain","resolution","source","storage"]),queries:new Set(["analysis","core","domain","language-parsers","resolution","semantic","source","storage","symbols"]),reindex:new Set(["domain","language-parsers","resolution","runtime","semantic","source","storage","symbols"]),resolution:new Set(["domain","source","storage","symbols"]),runtime:new Set(["domain","queries","reindex","resolution","semantic","source","storage","symbols"]),semantic:new Set(["domain","resolution","storage","symbols"]),source:new Set(["domain","storage"]),storage:new Set(["domain","source"]),symbols:new Set(["analysis","domain","language-parsers","resolution","semantic","source","storage"])}[e]?.has(t)??!1}function cT(e,t){if(t==="shared")return"ok";let n={app:new Set(["core","shared","ui"]),core:new Set(["shared"]),infra:new Set(["core","shared"]),ui:new Set(["core","shared"])};return n[e]?n[e].has(t)?"ok":"violation":null}function Bn(e,t){let{scope:n,minDeviation:i=5}=t??{},r=t?.semantic!==!1,o=t?.includePatternDeviations!==!1,a=new A(e).fileDependencyGraph(n);return pT([...lT(e,a,{scope:n,semantic:r}),...dT(a),...o?mT(a,i):[]])}function lT(e,t,n){let i=hT(e,n.scope),r=[],o=new Set;for(let[a,c]of t){if($t(a))continue;let l=i.get(a)??new Set;for(let u of c)$t(u)||l.has(u)||uT(e,a,u,n)||(r.push({file:a,dep:u}),o.add(a))}o.size>0&&ST(e,i,{paths:[...o]});let s=[];for(let{file:a,dep:c}of r)(i.get(a)??new Set).has(c)||s.push({file:a,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."});return s}function uT(e,t,n,i){return RT(e,t,n)||kT(e,t,n)||CT(n)||IT(e,t,n)||wT(n)?!0:i.semantic&&vT(e,t,n)}function dT(e){let t=[],n=xT(e);for(let[i,r]of e){if($t(i))continue;let o=jn(i);for(let s of r){if($t(s))continue;let a=jn(s);if(o===a)continue;let c=sl(o,a),l=c?"explicit":"inferred";if((c??n.get(`${o}->${a}`))==="violation"){let d=l==="explicit"?"direct":"signal";t.push({file:i,kind:"layer-violation",description:`Imports from ${a}/ (${s}) \u2014 may cross architectural boundary`,dep:s,detail:`${o}/ should not depend on ${a}/`,actionTier:d,policyBasis:l,evidenceReasons:[`dependency edge exists from ${i} to ${s}`,l==="explicit"?`explicit layer policy rejects ${o}/ -> ${a}/`:`rare cross-layer edge ${o}/ -> ${a}/ is inferred as a violation`],recommendation:l==="explicit"?"Move the dependency behind an allowed layer boundary or document a policy change.":"Review whether this is a real boundary break or an intentional exception before moving code."})}}}return t}function mT(e,t){let n=[];for(let[i,r]of fT(e)){let o=r.filter(a=>!$t(a));if(o.length<t)continue;let s=gT(e,o);for(let a of o)for(let c of e.get(a)??[])$t(c)||(s.get(c)??0)===1&&Or.dirname(c)!==i&&Or.dirname(c)!==Or.dirname(i)&&(Wf(a,c)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${i}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${i}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."}))}return n}function pT(e){return{results:e,unusedImports:e.filter(t=>t.kind==="unused-import").length,layerViolations:e.filter(t=>t.kind==="layer-violation").length,patternDeviations:e.filter(t=>t.kind==="pattern-deviation").length}}function fT(e){let t=new Map;for(let n of e.keys()){let i=Or.dirname(n),r=t.get(i);r||(r=[],t.set(i,r)),r.push(n)}return t}function gT(e,t){let n=new Map;for(let i of t)for(let r of e.get(i)??[])$t(r)||n.set(r,(n.get(r)??0)+1);return n}function hT(e,t){let n=new Map;return yT(e,n,t),n}function yT(e,t,n){for(let i of bT(e,n))zf(e,t,i.from_file,i.to_file)}function bT(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
|
|
544
597
|
FROM mentions m
|
|
545
598
|
JOIN chunks c ON m.chunk_id = c.id
|
|
546
599
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -556,31 +609,31 @@ ${n}`.toLowerCase(),i=Dn(r,["historical note","historical record","history note"
|
|
|
556
609
|
WHERE d1.id != d2.id
|
|
557
610
|
AND m.role != 1
|
|
558
611
|
${e.pathExclusionsFor("d1","d2")}
|
|
559
|
-
${n}`)}function
|
|
560
|
-
`);return
|
|
561
|
-
`),o=Math.max(0,n-2),s=Math.min(
|
|
562
|
-
`);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function
|
|
612
|
+
${n}`)}function ST(e,t,n={}){new A(e).scanSourceReferences({paths:n.paths??B(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},r=>{r.target.relativePath!==r.sourceFile&&(e.isIgnored(r.target.relativePath)||zf(e,t,r.sourceFile,r.target.relativePath))})}function zf(e,t,n,i){if(e.isIgnored(n)||e.isIgnored(i))return;let r=t.get(n);r||(r=new Set,t.set(n,r)),r.add(i)}function xT(e){let t=new Map;for(let[i,r]of e){if($t(i))continue;let o=jn(i);for(let s of r){if($t(s))continue;let a=jn(s);if(o===a||sl(o,a))continue;let c=`${o}->${a}`;t.set(c,(t.get(c)??0)+1)}}let n=new Map;for(let[i,r]of t)n.set(i,r<=2?"violation":"ok");return n}function CT(e){return e.includes("types")||e.endsWith(".d.ts")}function vT(e,t,n){let i=yr(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.isUsed)}function RT(e,t,n){let i=Ie(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.used)}function kT(e,t,n){let i=Ie(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.every(r=>r.isTypeOnly===!0)}function wT(e){return e.endsWith(".vue")}function IT(e,t,n){let i=Ie(e,t).filter(r=>r.sourcePath===n);return i.length===0?!1:i.every(r=>r.kind==="side-effect"||r.kind==="namespace"&&r.usedMembers.length===0&&!r.used)}function $t(e){let t=X(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||LT(Or.basename(e)))}function LT(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}import{basename as Gf,extname as Jf}from"path";function xs(e,t,n,i,r,o){let s=new Set;PT(e,t,n,i)&&s.add(r);for(let a of o)a.value&&DT(s,a.label,a.value);return[...s].slice(0,6)}function DT(e,t,n){let i=NT(n);t.endsWith("name")&&ET(i)&&e.add(`${t} has type-guard boundary shape`);for(let r of i){let o=TT.get(r);o&&e.add(`${t} has ${o} term: ${r}`)}}function PT(e,t,n,i){if(n<=0)return!1;let r=Ke(e,t);if(r.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(r[o]??"").trim();if(s!==""){if(Zi(s)===i)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function NT(e){return e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function ET(e){return e.some(t=>FT.has(t))&&e.some(t=>_T.has(t))}var TT=new Map([["access","access policy"],["accessible","access policy"],["adapter","adapter"],["adapters","adapter"],["allow","access policy"],["allowed","access policy"],["animation","animation calculation"],["api","api surface"],["apply","settings/application"],["audit","side-effect boundary"],["auth","authorization"],["authorize","authorization"],["audio","audio side-effect"],["can","access policy"],["capabilities","capability boundary"],["capability","capability boundary"],["boundary","boundary"],["begin","lifecycle"],["bridge","bridge"],["bridges","bridge"],["cache","state cache"],["chase","gameplay action"],["command","command boundary"],["context","context policy"],["cooldown","temporal state"],["cooldowns","temporal state"],["controller","controller"],["controllers","controller"],["diagnostic","diagnostics"],["diagnostics","diagnostics"],["effect","side-effect boundary"],["effects","side-effect boundary"],["energy","gameplay calculation"],["expired","temporal state"],["facade","facade"],["facades","facade"],["fire","gameplay action"],["gateway","gateway"],["gateways","gateway"],["guard","guard"],["guards","guard"],["haptic","haptic side-effect"],["haptics","haptic side-effect"],["head","sequence boundary"],["history","state history"],["input","input boundary"],["jump","gameplay action"],["keyboard","input boundary"],["log","side-effect boundary"],["logger","side-effect boundary"],["lock","coordination boundary"],["middleware","middleware"],["multiplier","gameplay calculation"],["mute","audio side-effect"],["normalize","normalization"],["normalise","normalization"],["normalizer","normalization"],["oscillate","animation calculation"],["oscillation","animation calculation"],["overlap","collision predicate"],["performance","diagnostics"],["permission","access policy"],["permissions","access policy"],["policy","policy"],["pool","state pool"],["pooled","state pool"],["pools","state pool"],["predict","prediction"],["presenter","presenter"],["presenters","presenter"],["projectile","gameplay entity"],["provider","provider boundary"],["providers","provider boundary"],["public","public surface"],["quality","settings/application"],["rate","calculation"],["register","registry"],["registry","registry"],["relay","relay"],["relays","relay"],["reseed","state lifecycle"],["reset","state lifecycle"],["respond","response boundary"],["response","response boundary"],["resolve","resolution"],["resolver","resolution"],["route","route boundary"],["routes","route boundary"],["run","lifecycle"],["sample","diagnostics"],["score","gameplay calculation"],["scope","scope policy"],["scroll","position state"],["scrolled","position state"],["seed","state lifecycle"],["seeded","state lifecycle"],["segment","segment boundary"],["segments","segment boundary"],["setting","settings/application"],["settings","settings/application"],["spawn","gameplay lifecycle"],["spawning","gameplay lifecycle"],["speed","gameplay calculation"],["surface","public surface"],["tail","sequence boundary"],["tick","temporal state"],["transaction","transaction"],["transactional","transaction"],["transform","transformation"],["transformer","transformation"],["translate","translation"],["translator","translation"],["try","fallible action"],["validate","validation"],["validation","validation"],["validator","validation"],["visual","diagnostics"],["window","settings/application"],["socket","transport boundary"],["websocket","transport boundary"]]),FT=new Set(["can","has","is","should"]),_T=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function Hn(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new A(e);return it({candidates:()=>UT(s,n,i),orderCandidates:ts,scanLimit:o,prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>AT(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:r})}function AT(e,t,n){let i=qT(n);if(i.size!==1||!Sa(e,t.relativePath,t.startLine,t.endLine))return null;let[,r]=[...i.entries()][0],o=$T(e,t,r),s=OT(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:v(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:G(t),forwardsTo:r.symbol,forwardsToShort:v(r.symbol),forwardsToFile:r.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:MT(a,o,s)}}function $T(e,t,n){return xs(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:v(t.symbol)},{label:"callee name",value:v(n.symbol)},{label:"passthrough module",value:Gf(t.relativePath,Jf(t.relativePath))},{label:"callee module",value:Gf(n.file,Jf(n.file))}])}function MT(e,t,n){if(e==="signal"){if(n.length>0)return`Review the public API before inlining; public-facade evidence: ${n.slice(0,2).join("; ")}.`;let i=t.filter(HT);return i.length>0?`Review the public API before inlining; public-surface evidence: ${i.slice(0,2).join("; ")}.`:`Review the boundary before inlining; boundary evidence: ${t.slice(0,2).join("; ")}.`}return"Inline or remove this passthrough unless an external API or runtime registration depends on the forwarding name."}function OT(e,t){return jT(e,t)?Ri(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:fe(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function jT(e,t){let n=Ke(e,t.relativePath);if(n.length===0)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
|
|
613
|
+
`);return WT.test(i)?!0:BT(n,M(t.symbol))}function BT(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${VT(t)}\\b`);return e.some(i=>n.test(i))}function HT(e){return e.includes("public surface")}function VT(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qT(e){let t=e.some(i=>ue(i.symbol))?e.filter(i=>ue(i.symbol)):e,n=new Map;for(let i of t)n.has(i.symbol)||n.set(i.symbol,i);return n}function UT(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:3,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0})}var WT=/^\s*export\s+(?:default\s+)?(?:(?:async\s+)?function\b|(?:const|let|var)\b)/m;function Vn(e,t){let{scope:n,minLoc:i=3,maxLoc:r=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new A(e),u=l.scopedDefinitions(n),d=r0(l,n),m={high:0,medium:1,low:2};return it({candidates:()=>zT(e,l,u,{minLoc:i,maxLoc:r}),orderCandidates:(p,f)=>G(f)-G(p)||p.relativePath.localeCompare(f.relativePath),scanLimit:a,prepare:p=>{let f=KT(p),g=JT(e,l,p,f,{semantic:c}),y=p.filter(S=>{let R=Cs(e,S,g,f);return R.realConsumers.length<=1&&!R.transitivelyReachable&&Kf(S,R.realConsumers.length,d)});return{consumerFileMap:g,singletonBackedClassIds:YT(e,l,u,y,{semantic:c}),candidateIndex:f}},evaluate:(p,f)=>{if(f.singletonBackedClassIds.has(p.symbolId))return null;let g=Cs(e,p,f.consumerFileMap,f.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!Kf(g.definition,g.realConsumers.length,d))return null;let y=QT(e,g);return!s&&y.confidence==="low"?null:y},orderResults:(p,f)=>m[p.confidence]-m[f.confidence]||f.loc-p.loc||p.file.localeCompare(f.file)||p.startLine-f.startLine,limit:o})}function zT(e,t,n,i){return n.filter(r=>r.isTypeLike&&G(r)>=i.minLoc).filter(r=>G(r)<=i.maxLoc).filter(r=>!e.isIgnored(r.relativePath)).filter(r=>X(r.relativePath)!=="test").filter(r=>!fe(e,r.symbol,r.relativePath)).filter(r=>!o0(r.symbol)).filter(r=>!t.hasSuppressionComment(r))}function GT(e,t,n){return nn(e,t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function JT(e,t,n,i,r){let o=GT(t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(l=>{let u=Cs(e,l,o,i);return u.realConsumers.length<=1&&!(u.realConsumers.length>0&&al(l.relativePath))}),a=r.semantic&&s.length>0?Dn(o,et(e,s)):o,c=s.filter(l=>Cs(e,l,a,i).realConsumers.length<=1);return Dn(a,t.sourceFallbackCallerFiles(c))}function KT(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath);i||(i=new Map,t.set(n.relativePath,i));let r=M(n.symbol);r&&i.set(r,n)}return t}function Cs(e,t,n,i){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=as(e,t,o),l=s0(e,t,n,i);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function QT(e,t){let n=Xf(e,t.definition.relativePath,t.definition.startLine),i=al(t.definition.relativePath)?!0:a0(e,t.definition),{confidence:r,reason:o}=c0(t.realConsumers.length,n,i),s=XT(t.realConsumers.length,n,i);return{symbol:t.definition.symbol,shortName:v(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:G(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:i,confidence:r,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function XT(e,t,n){return e===0?{actionTier:"direct",stalenessKind:"unused-abstraction",recommendation:"Delete the abstraction or wire the missing consumer after checking public/package surfaces."}:t==="class"?{actionTier:"signal",stalenessKind:"one-to-one-class-encapsulation",recommendation:"Treat as weak signal: a one-consumer class may be intentional encapsulation, so inline only after reviewing ownership and state boundaries."}:n?{actionTier:"signal",stalenessKind:"single-consumer-abstraction",recommendation:"Review whether this single-consumer abstraction earns its name or should be folded into the owning feature."}:{actionTier:"signal",stalenessKind:"misplaced-single-consumer-type",recommendation:"Review moving or co-locating the type with its only real consumer; keep it here only if this file owns the public contract."}}function YT(e,t,n,i,r){let o=e0(e,ZT(n),i),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=nn(t,s,{semantic:r.semantic}),c=new Set;for(let{singleton:l,classId:u}of o)n0(e,l,a)&&c.add(u);return c}function ZT(e){let t=new Map;for(let n of e){let i=M(n.symbol);i&&t.set(Qf(n.relativePath,i),n)}return t}function e0(e,t,n){let i=[];for(let r of n){let o=t0(e,t,r);o&&i.push({singleton:o,classId:r.symbolId})}return i}function t0(e,t,n){if(Xf(e,n.relativePath,n.startLine)!=="class")return null;let i=M(n.symbol);if(!i)return null;let r=i0(e,n.relativePath,i);return r?t.get(Qf(n.relativePath,r))??null:null}function n0(e,t,n){let i=M(t.symbol),r=n.get(t.symbolId);return!i||!r?!1:[...r].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!_c(e,o,i))}function Qf(e,t){return`${e}\0${t}`}function i0(e,t,n){let i=F(e,t);if(!i)return null;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${r}\\s*\\(`);return i.match(o)?.[1]??null}function r0(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function o0(e){let t=we(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let i=n[n.length-1],r=n[n.length-2];return i?.suffix==="type"&&r?.suffix==="type"}function al(e){let n=(e.split("/").pop()??"").replace(/\.[^.]+$/,"");return!!(n==="types"||n.endsWith("-types")||n==="models"||n==="schema"||n==="common"||n==="protocol"||n==="proto"||n==="dto"||n==="mod"||n==="contracts"||/(^|\/)types(\/|\.)/.test(e)||/(^|\/)models?(\/|\.)/.test(e)||/(^|\/)proto(?:col)?(\/|\.)/.test(e)||/(^|\/)schema(\/|\.)/.test(e)||/(^|\/)contracts?(\/|\.)/.test(e))}function Kf(e,t,n){return!(al(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function s0(e,t,n,i){let r=Ca(e,t.relativePath),o=M(t.symbol);if(!o)return!1;let s=r.get(o);if(!s||s.size===0)return!1;let a=i.get(t.relativePath);if(!a)return!1;for(let c of s){let l=a.get(c);if(!l)continue;let u=n.get(l.symbolId);if(u){for(let d of u)if(d!==t.relativePath&&!e.isIgnored(d))return!0}}return!1}function Xf(e,t,n){let i=F(e,t);if(!i)return"other";let r=i.split(`
|
|
614
|
+
`),o=Math.max(0,n-2),s=Math.min(r.length-1,n+2);for(let a=o;a<=s;a++){let l=(r[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(l))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(l))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(l))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(l))return"enum"}return"other"}function a0(e,t){let n=F(e,t.relativePath);if(!n)return!1;let i=M(t.symbol);if(!i)return!1;let r=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${r}\\b`),s=n.split(`
|
|
615
|
+
`);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function c0(e,t,n){return e===0?{confidence:"high",reason:"unused \u2014 no consumers and defining file has no real usage"}:e===1&&t==="class"?{confidence:"low",reason:"1 consumer + class kind \u2014 likely 1:1 encapsulation, not over-abstraction"}:e===1&&!n?{confidence:"high",reason:"1 consumer + defining file never uses it \u2014 type belongs with its consumer"}:{confidence:"medium",reason:"1 consumer \u2014 single-use abstraction"}}import{basename as _i,extname as vs}from"path";function qn(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new A(e),a=f0(s.fileDependencyGraph(n));return it({candidates:()=>d0(s,n,i),orderCandidates:ts,scanLimit:o,prepare:c=>({callerFileMap:l0(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>u0(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:r})}function l0(e,t,n,i){let r=nn(t,n,{semantic:!1,sourceFallback:!1}),o=[];i.semantic&&T("wrapper.semantic-candidates",()=>{o=n.filter(d=>cl(e,t,d,r).length<=1)},()=>({symbols:n.length,semanticCandidates:o.length}));let s=o.length===0?new Map:nn(t,o,{semantic:!0,sourceFallback:!1}),a=s.size===0?r:Dn(r,s),c=new Map(n.map(d=>[d.symbolId,d])),l=new Map;for(let d of n){let m=cl(e,t,d,a);if(m.length>1||(l.set(d.symbolId,d),m.length!==1))continue;let p=m[0],f=Yf(e,d.symbolId,p);if(!f)continue;let g=Zf(t,e,p,d.symbol,f);g?.isFunctionLike&&c.has(g.symbolId)&&l.set(g.symbolId,c.get(g.symbolId))}let u=[...l.values()];return u.length===0?a:Dn(a,t.sourceFallbackCallerFiles(u))}function u0(e,t,n,i){let r=cl(e,t,n,i.callerFileMap);if(r.length!==1)return null;let o=r[0],s=Yf(e,n.symbolId,o);if(!s)return null;let a=Zf(t,e,o,n.symbol,s);if(a&&di(a.symbol))return null;let{fanIn:c,source:l}=m0(i.callerFileMap,i.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=h0(e,n,o,a);return{symbol:n.symbol,shortName:v(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:G(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?v(a.symbol):_i(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function d0(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:2,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0})}function cl(e,t,n,i){let r=_i(n.relativePath,vs(n.relativePath)),o=[...i.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>_i(s,vs(s))!==r).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return as(e,n,o).realConsumers}function Yf(e,t,n){return e.get(`SELECT c.start_line, c.end_line
|
|
563
616
|
FROM mentions m
|
|
564
617
|
JOIN chunks c ON m.chunk_id = c.id
|
|
565
618
|
JOIN documents d ON c.document_id = d.id
|
|
566
619
|
WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
|
|
567
|
-
LIMIT 1`,t,n)}function
|
|
568
|
-
`),{path:
|
|
620
|
+
LIMIT 1`,t,n)}function Zf(e,t,n,i,r){let o=e.definitionsForFile(n),s=p0(t,n,i,r.start_line,r.end_line);return Qe(o,s)}function m0(e,t,n,i){if(i?.isFunctionLike){let r=[...e.get(i.symbolId)??[]].filter(o=>o!==i.relativePath);if(r.length>0)return{fanIn:r.length,source:"function"}}return{fanIn:g0(t,n),source:"file"}}function p0(e,t,n,i,r){let o=M(n);if(!o)return i;let s=_t(e,t).get(o);if(!s||s.length===0)return i;for(let a of s)if(a>=i&&a<=r)return a;return i}function f0(e){let t=new Map;for(let[n,i]of e){t.has(n)||t.set(n,t.get(n)??0);for(let r of i)t.set(r,(t.get(r)??0)+1)}return t}function g0(e,t){let n=e.get(t)??0;if(n>0)return n;let i=_i(t,vs(t)),r=0;for(let[o,s]of e)o!==t&&_i(o,vs(o))===i&&s>r&&(r=s);return r}function h0(e,t,n,i){return xs(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:v(t.symbol)},{label:"caller name",value:i?.symbol?v(i.symbol):_i(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var v0=75e3,R0=5e3,k0=2500;function w0(e){let t=Ue(e);return t.symbols>=v0||t.documents>=R0?k0:void 0}var I0=".scipquery-baseline.json";function Rs(e,t){return t&&x0(t)?t:C0(e.config.projectRoot,t??I0)}function ll(e,t={}){let{scope:n}=t,i=w0(e),r=[],o=At(e,{scope:n,...be.dead,scanLimit:i});for(let s of o.symbols)Oe(e,s.relativePath)||fe(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&r.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of Nn(e,{scope:n,...be.isolated,scanLimit:i}))Oe(e,s.relativePath)||fe(e,s.symbol,s.relativePath)||r.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of Pn(e,{scope:n}))s.kind==="real"&&r.push(`cycle:${L0(s.path)}`);for(let s of En(e,{scope:n,...be.similar,scanLimit:i}))r.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of $n(e,{scope:n,...be.extract,scanLimit:i}))r.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of qn(e,{scope:n,...be.wrappers,scanLimit:i}))r.push(`wrapper:${s.file}:${s.shortName}`);for(let s of Hn(e,{scope:n,...be.passthroughs,scanLimit:i}))r.push(`passthrough:${s.file}:${s.shortName}`);for(let s of Vn(e,{scope:n,...be.stale,scanLimit:i}))r.push(`stale:${s.file}:${s.shortName}`);for(let s of Bn(e,{scope:n,...be.drift,includePatternDeviations:!1}).results)r.push(`drift:${s.kind}:${s.file}:${s.dep}`);return[...new Set(r)].sort()}function L0(e){if(e.length===0)return"";let t=0;for(let n=1;n<e.length;n++)e[n]<e[t]&&(t=n);return[...e.slice(t),...e.slice(0,t)].join(">")}function ul(e,t={}){let n=ll(e,{scope:t.scope}),i=Rs(e,t.path);return S0(i,JSON.stringify({version:1,findings:n},null,2)+`
|
|
621
|
+
`),{path:i,findingCount:n.length}}function jr(e,t={}){let n=Rs(e,t.path);if(!y0(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let i=JSON.parse(b0(n,"utf-8")),r=new Set(i.findings??[]),o=ll(e,{scope:t.scope}),s=new Set(o);return{baselinePath:n,baselineCount:r.size,current:o,newFindings:o.filter(a=>!r.has(a)),fixedFindings:[...r].filter(a=>!s.has(a))}}var D0=5;function Br(e,t={}){let{base:n="HEAD",minContainment:i=.7,minCallees:r=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:c}=t,l=t.semantic!==!1,u=t.diffPlan??vt(e,{base:n}),d={available:u.note!==Zc,base:n,changedFiles:u.changedFiles,helpersChecked:0,skipped:[],findings:[]};if(!d.available||u.changedFiles.length===0)return d;let m=new A(e),p=new Set(u.changedFiles),f=new Map(u.renamedFiles.map(C=>[C.to,C.from])),g=t.baseContentAt??_r(e.config.projectRoot,n,Ar(u)),y=_0(m,p,f,g);if(y.length===0)return d;let S=y.slice(0,s);y.length>s&&(d.note=`helper scoring capped at ${s} of ${y.length} new symbols`);let R=m.calleeMap(S,{semantic:l}),k=S.map(C=>({def:C,callees:rs((R.get(C.symbolId)??[]).map(D=>D.symbol))})),x,b=()=>(x??=Pr(e,{minCallees:Math.min(3,r),scanLimit:c,semantic:l}),x);for(let{def:C,callees:D}of k){let w=v(C.symbol);if(D.size<r){d.skipped.push({helperShortName:w,helperFile:C.relativePath,reason:`fewer than ${r} meaningful callees \u2014 too small to score`});continue}let j=b(),J=F0(D,j);if(J===0){d.skipped.push({helperShortName:w,helperFile:C.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let Re=A0(e,C.symbolId);if(Re.length===0){d.skipped.push({helperShortName:w,helperFile:C.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let ie=P0({candidateIndex:j,changed:p,helperCallees:D,helperFile:C.relativePath,helperSymbol:C.symbol,minContainment:i,minSiteCoverage:o,migratedFiles:Re});ie.length!==0&&(ie.sort((_e,Ht)=>eg(Ht.migrationScope)-eg(_e.migrationScope)||Ht.containment-_e.containment||Ht.siteCoverage-_e.siteCoverage||_e.file.localeCompare(Ht.file)),d.findings.push({helperSymbol:C.symbol,helperShortName:w,helperFile:C.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:D.size,specificHelperCalleeCount:J,migratedFiles:Re.sort(),leftovers:ie.slice(0,D0)}))}return d.findings.sort((C,D)=>(D.leftovers[0]?.containment??0)-(C.leftovers[0]?.containment??0)||C.helperFile.localeCompare(D.helperFile)),d.findings=d.findings.slice(0,a),d}function P0(e){let t=[],n=N0(e.helperSymbol,e.helperFile,e.migratedFiles),i=new Set;for(let r of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(r)??[])i.add(o);for(let r of i){let o=e.candidateIndex.corpus[r];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=Op(e.helperCallees,o.callees);if(s<e.minContainment)continue;let a=[...e.helperCallees].filter(u=>o.callees.has(u)),c=o.callees.size===0?0:a.length/o.callees.size;if(c<e.minSiteCoverage||!a.some(u=>(e.candidateIndex.docFreq.get(u)??0)<=e.candidateIndex.ubiquityThreshold))continue;let l=E0(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:v(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(v).sort()})}return t}function eg(e){return e==="same-scope"?2:e==="unknown"?1:0}function N0(e,t,n){let i=new Set([...dl(t),...ml(M(e))]);for(let r of n)for(let o of dl(r))i.add(o);return i}function E0(e,t,n){let i=new Set([...dl(n),...ml(M(t))]);if(e.size===0||i.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let r=[...i].filter(o=>e.has(o)).sort();return r.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${r.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var T0=new Set(["app","apps","common","component","components","helper","helpers","index","lib","package","packages","page","pages","route","routes","service","services","shared","spec","src","test","tests","util","utils"]);function dl(e){return ml(e.replace(/\.[^.]+$/,""))}function ml(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!T0.has(t))}function F0(e,t){let n=0;for(let i of e)(t.docFreq.get(i)??0)<=t.ubiquityThreshold&&(n+=1);return n}function _0(e,t,n,i){return e.productionCallableDefinitions({files:[...t],requireFunctionLikeSymbol:!0}).filter(r=>{if(!t.has(r.relativePath))return!1;let o=n.get(r.relativePath)??r.relativePath,s=i(o);return s===null||!new RegExp(`\\b${$0(r.leaf)}\\b`).test(s)})}function A0(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
|
|
569
622
|
FROM mentions m
|
|
570
623
|
JOIN chunks c ON m.chunk_id = c.id
|
|
571
624
|
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
572
625
|
WHERE m.symbol_id = ?
|
|
573
626
|
AND m.role != 1
|
|
574
|
-
${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}function ZE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ki(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=t.files===void 0?null:new Set(t.files),s=new T(e);return ze({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}).filter(a=>eT(a.relativePath)&&(o===null||o.has(a.relativePath))),scanLimit:i,evaluate:a=>{let c=ae(e,a.relativePath)?.callables.find(d=>d.startLine===a.startLine&&d.endLine===a.endLine);if(!c||c.params.length===0||c.params.some(d=>!d.simple)||c.paramsEndLine>=c.endLine)return null;let l=It(e,a.relativePath),u=[];for(let d=c.params.length-1;d>=0;d--){let m=c.params[d];if(m.name===""||m.name.startsWith("_")||tT(l.get(m.name),c.paramsEndLine,c.endLine))break;u.unshift(m.name)}return u.length===0?null:{symbol:a.symbol,shortName:b(a.symbol),file:a.relativePath,startLine:a.startLine,endLine:a.endLine,paramCount:c.paramCount,unusedTrailing:u}},orderResults:(a,c)=>c.unusedTrailing.length-a.unusedTrailing.length||a.file.localeCompare(c.file)||a.startLine-c.startLine,limit:r})}function eT(e){let t=W(e);return t==="typescript"||t==="tsx"||t==="javascript"}function tT(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}var ls=["echo","incomplete-migration","co-change-partner","doc-reference","unused-params","new-dead","baseline"];function wi(e,t={}){let n=t.base??"HEAD",{minTogether:r=6,minConfidence:i=.6,maxEchoChecks:o=Number.POSITIVE_INFINITY,maxHelpers:s=Number.POSITIVE_INFINITY,minSimilarity:a=.8,includeBaseline:c=!1,scanLimit:l}=t,u=t.semantic!==!1,d=new Set(t.skip??[]),m=gt(e,{base:n}),f=xr(e,{base:n,plan:m}),h=f.changedFiles,g=new Set(h),y=new Set(m.changedFileLines),S=yi(e.config.projectRoot,n,bi(m,h)),C=IT(e.config.projectRoot,n,m,S),k={base:n,changedFiles:h,changedSymbols:f.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],rootCauseGroups:[],note:f.summary.note};if(h.length===0)return k;let D=(x,I)=>{if(d.has(x)){k.skipped.push({check:x,reason:"skipped via --skip"});return}I()};return D("echo",()=>cT(e,f.changedSymbols,g,C,o,a,l,u,k)),D("incomplete-migration",()=>yT(e,n,m,s,l,u,S,k)),D("co-change-partner",()=>bT(e,g,r,i,k)),D("doc-reference",()=>RT(e,g,y,m.changedRanges,k)),D("unused-params",()=>kT(e,h,k)),D("new-dead",()=>wT(e,f.changedSymbols,C,k)),c&&D("baseline",()=>NT(e,k)),sT(k,e.config.suppressions??[]),k.rootCauseGroups=rT(k.findings),k}function rT(e){let t=new Map;for(let n of e){let r=n.groupKey??`${n.check}:${n.id}`,i=t.get(r);i||(i={groupKey:r,check:n.check,severity:n.severity,actionTier:n.actionTier,sourceAnalyzer:n.sourceAnalyzer,rootCauseKey:n.rootCauseKey,count:0,findingIds:[],files:new Set,relatedFiles:new Set,message:n.message,remediation:n.remediation},t.set(r,i)),i.count+=1,i.findingIds.push(n.id),i.severity=iT(i.severity,n.severity),i.actionTier=oT(i.actionTier,n.actionTier),n.file&&i.files.add(n.file);for(let o of n.relatedFiles??[])i.relatedFiles.add(o)}return[...t.values()].map(n=>({...n,files:[...n.files].sort(),relatedFiles:[...n.relatedFiles].sort()})).sort((n,r)=>r.count-n.count||cs(r.severity)-cs(n.severity)||n.groupKey.localeCompare(r.groupKey))}function iT(e,t){return cs(t)>cs(e)?t:e}function cs(e){return e==="error"?2:e==="warning"?1:0}function oT(e,t){return e?t&&gf(t)>gf(e)?t:e:t}function gf(e){return e==="direct"?2:e==="signal"?1:0}function sT(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let r of e.findings){let i=t.find(o=>aT(o,r));i?e.suppressed.push({finding:r,suppression:i}):n.push(r)}e.findings=n}function aT(e,t){return!e.reason||e.reason.trim()===""||e.expiresAt&&Date.parse(e.expiresAt)<=Date.now()||e.id&&e.id!==t.id||e.check&&e.check!==t.check||e.file&&e.file!==t.file?!1:!!(e.id||e.check)}function Rr(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function cT(e,t,n,r,i,o,s,a,c){c.checksRun.push("echo");for(let l of t.slice(0,i)){if(r(l))continue;let u=mi(e,l.symbol,{minSimilarity:o,limit:5,scanLimit:s,semantic:a}),d=[];for(let g of u){let y=g.fileA===l.file?g.fileB:g.fileA,S=g.fileA===l.file?g.shortNameB:g.shortNameA,C=g.fileA===l.file?g.symbolB:g.symbolA;n.has(y)||d.push({otherFile:y,otherShort:S,otherSymbol:C,similarity:g.similarity,similarityBasis:g.similarityBasis??"callees",sharedEvidence:g.sharedCallees})}if(d.length===0)continue;let m=d[0],f=Fn("echo",l.symbol,l.file,...d.map(g=>`${g.otherSymbol}|${g.otherFile}`).sort()),h=lT(l,d);Rr(c,{id:f,groupKey:f,actionTier:h,check:"echo",severity:"warning",evidence:"heuristic",confidence:m.similarity,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(d.map(g=>g.otherFile))].sort(),message:fT(l,d),why:gT(l,d),remediation:hT(h,l.shortName,m.otherShort)})}t.length>i&&c.skipped.push({check:"echo",reason:`echo check capped at ${i} of ${t.length} changed symbols`})}function lT(e,t){return t.some(r=>uT(e.symbol,r))?"direct":"signal"}function uT(e,t){if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let n=$(e),r=$(t.otherSymbol);return!n||!r?!1:n===r?!0:pT(t.sharedEvidence)?!1:dT(n,r)}function dT(e,t){let n=hf(e),r=hf(t);if(n.length===0||r.length===0)return!1;let i=new Set(r),o=n.filter(s=>i.has(s)).length;return o>=2&&o/Math.min(n.length,r.length)>=.5}function hf(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}var mT=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function pT(e){return e.length>=3&&e.every(t=>mT.has(t.toLowerCase()))}function fT(e,t){let n=t[0],r=Math.round(n.similarity*100);return t.length===1?`${e.shortName} (${e.file}) is ${r}% similar to established ${n.otherShort} (${n.otherFile})`:`${e.shortName} (${e.file}) resembles ${t.length} established symbol(s); strongest is ${r}% similar to ${n.otherShort} (${n.otherFile})`}function gT(e,t){let n=[`${e.shortName} was changed in this diff.`];for(let r of t.slice(0,3))n.push(`${r.otherShort} is outside this diff and scored ${Math.round(r.similarity*100)}% similar by ${r.similarityBasis} evidence.`),n.push(`Shared evidence: ${r.sharedEvidence.slice(0,5).join(", ")||"(none listed)"}.`);return t.length>3&&n.push(`${t.length-3} additional similar match(es) grouped into this finding.`),n}function hT(e,t,n){return e==="direct"?`Extract or reuse the shared behavior with ${n}, or keep the duplicate with a suppression reason.`:`Review whether ${t} is intentionally parallel to the established implementation(s); extract shared behavior only if the product semantics match.`}function yT(e,t,n,r,i,o,s,a){let c=Ri(e,{base:t,maxHelpers:r,diffPlan:n,scanLimit:i,semantic:o,baseContentAt:s});if(!c.available){a.skipped.push({check:"incomplete-migration",reason:"no git history"});return}a.checksRun.push("incomplete-migration"),c.note&&a.skipped.push({check:"incomplete-migration",reason:c.note});for(let l of c.findings){let u=l.leftovers.map(y=>`${y.shortName} (${y.file}, ${Math.round(y.containment*100)}% helper / ${Math.round(y.siteCoverage*100)}% site, ${y.migrationScope})`).join(", "),d=l.leftovers.map(y=>`${y.shortName}: ${y.migrationScope} (${y.migrationScopeReasons[0]})`).join("; "),m=[...l.migratedFiles,...l.leftovers.map(y=>y.file)],f=l.leftovers.length===0?void 0:Math.max(...l.leftovers.map(y=>Math.min(y.containment,y.siteCoverage))),h=l.leftovers.some(y=>y.migrationScope==="possible-subtype"),g=Fn("incomplete-migration",l.helperSymbol,l.helperFile,m.join("|"));Rr(a,{id:g,check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:f,file:l.helperFile,symbol:l.helperSymbol,relatedFiles:m,message:`new helper ${l.helperShortName} (${l.helperFile}) is wired into ${l.migratedFiles.length} file(s), but ${l.leftovers.length} similar un-migrated site(s) remain: ${u}`,why:[`${l.helperShortName} is new in this diff and already referenced by ${l.migratedFiles.join(", ")}.`,`Helper shape: ${l.helperShape}; ${l.specificHelperCalleeCount}/${l.helperCalleeCount} helper callees are specific enough to score.`,`Unchanged site(s) still contain the helper's callee pattern: ${u}.`,`Migration scope hints: ${d}.`],remediation:h?`Migrate same-scope sites to ${l.helperShortName}; review possible subtype/variant sites before applying the helper.`:`Migrate the remaining sites to ${l.helperShortName}, or confirm they are intentionally different.`})}}function bT(e,t,n,r,i){let o=Ap(e,t,{minTogether:n,minConfidence:0,maxFilesPerCommit:20});if(!o){i.skipped.push({check:"co-change-partner",reason:"no git history"});return}i.checksRun.push("co-change-partner");let s=new Set,a;for(let c of o){let l=t.has(c.fileA),u=t.has(c.fileB);if(l===u)continue;let d=l?c.fileA:c.fileB,m=l?c.fileB:c.fileA,f=l?c.changesA:c.changesB,h=f>0?c.together/f:0;if(h<r||Ic(m)||Ic(d)||!yf(`${e.config.projectRoot}/${m}`))continue;let g=`${d}|${m}`;if(s.has(g))continue;s.add(g);let y=Fn("co-change-partner",d,m,String(c.together)),S=Dc(d,m),C=Pc({fileA:d,fileB:m,together:c.together,confidence:h,commitScope:c.commitScope,recency:c.recency,subjectContext:c.subjectContext},S,(a??=Nc(e))(d,m)),k=[d,m].sort().join("|");i.findings.push({id:y,check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${k}`,confidence:h,file:d,relatedFiles:[m],sourceAnalyzer:"co-change",rootCauseKey:k,partnerClass:S.partnerClass,partnerClassReasons:S.reasons,commitScope:c.commitScope,recency:c.recency,focusedTogether:c.focusedTogether,broadTogether:c.broadTogether,broadCommitRatio:c.broadCommitRatio,lastTogetherAt:c.lastTogetherAt,recentTogether:c.recentTogether,subjectContext:c.subjectContext,...C?{declaredCouplingSuggestion:C}:{},message:`${d} changed, but ${m} did not \u2014 they change together ${c.together}x (${Math.round(h*100)}% of the time)`,why:[`${d} is in this diff and ${m} is not.`,`Git history shows ${c.together} co-change(s), which is ${Math.round(h*100)}% of changes to the edited side.`,`History context: ${ST(c)}.`,`Subject context: ${xT(c.subjectContext)}.`,...CT(c),`Partner class: ${S.partnerClass} (${S.reasons.join("; ")}).`],remediation:C?`Update ${m} alongside this change, declare the coupling "${C.name}", or confirm the coupling no longer holds.`:`Update ${m} alongside this change, or confirm the coupling no longer holds.`})}}function ST(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${vT(e.lastTogetherAt)}`}function xT(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",r=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(i=>`"${i}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${r}; external issue/PR labels ${e.externalIssueLabelStatus}`}function CT(e){let t=[];return e.commitScope==="broad-sweep"&&t.push("Broad-sweep history is weaker than focused co-edits; confirm this is a real coordination contract."),e.recency==="stale"&&t.push("The pair has no co-change in the recent history window; confirm the coupling still holds."),t}function vT(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function RT(e,t,n,r,i){i.checksRun.push("doc-reference");let o=Cr.referenceTargets(e,t,r);if(o.size!==0)for(let s of tf(e,o)){if(n.has(s.doc))continue;let a=s.citedClaims.length>0?s.citedClaims:Cr.citationContexts(e,s.doc,s.cited),c=Cr.classifyCitation(a),l=Fn("doc-reference",s.doc,s.cited.join("|"));Rr(i,{id:l,check:"doc-reference",severity:"warning",evidence:"change-graph",actionTier:c.actionTier,confidence:1,file:s.doc,relatedFiles:s.cited,citationKind:c.citationKind,citationKindReasons:c.reasons,citedClaims:a,message:`${s.doc} cites ${s.cited.join(", ")} as ${Cr.citationKindLabel(c.citationKind)} \u2014 changed in this diff, doc untouched`,why:[`${s.cited.join(", ")} changed in this diff.`,`${s.doc} cites the changed file(s) but was not updated in the same diff.`,...c.reasons.map(u=>`Citation kind evidence: ${u}`)],remediation:Cr.citationRemediation(c.citationKind,s.doc)})}}function kT(e,t,n){n.checksRun.push("unused-params");for(let r of ki(e,{files:t,limit:50})){let i=Fn("unused-params",r.symbol,r.file,r.unusedTrailing.join("|"));Rr(n,{id:i,check:"unused-params",severity:"warning",evidence:"heuristic",confidence:.85,file:r.file,startLine:r.startLine,endLine:r.endLine,symbol:r.symbol,message:`${r.shortName} (${r.file}) has trailing unused parameter(s): ${r.unusedTrailing.join(", ")}`,why:[`${r.shortName} is in a changed file.`,`The trailing parameter(s) ${r.unusedTrailing.join(", ")} are not referenced in the function body.`],remediation:"Drop the unused trailing parameters and their call-site arguments."})}}function wT(e,t,n,r){r.checksRun.push("new-dead");let i=new T(e);for(let o of t){if(n(o)||o.fanIn>0||i.fileKind(o.file)==="test"||De(e,o.file)||ie(e,o.symbol,o.file)||LT(o.symbol))continue;let s=Fn("new-dead",o.symbol,o.file);Rr(r,{id:s,check:"new-dead",severity:"warning",evidence:"graph-fact",confidence:.9,file:o.file,symbol:o.symbol,message:`${o.shortName} (${o.file}) was changed but has zero indexed consumers`,why:[`${o.shortName} is a changed production symbol.`,"The index reports zero consumers for this symbol.","The symbol is not in a detected entry surface or configured live root."],remediation:"Wire it up, or remove it before it becomes permanent dead code."})}}function LT(e){if(ee(e)!=="type")return!1;let t=$(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function IT(e,t,n,r){let i=new Map(n.renamedFiles.map(s=>[s.to,s.from])),o=r??yi(e,t,bi(n));return s=>{let a=i.get(s.file)??s.file,c=$(s.symbol);if(!c)return!1;let l=o(a);return l!==null&&DT(l,c)}}function DT(e,t){return new RegExp(`\\b${PT(t)}\\b`).test(e)}function PT(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function NT(e,t){if(!yf(as(e))){t.skipped.push({check:"baseline",reason:"no .scipquery-baseline.json \u2014 run health --write-baseline to enable"});return}t.checksRun.push("baseline");let n=vi(e);for(let r of n.newFindings){let i=Kp(r),o=Fn("baseline",r);Rr(t,{id:o,groupKey:`baseline:${i.sourceAnalyzer}:${i.rootCauseKey}`,check:"baseline",severity:"error",evidence:"baseline",actionTier:i.actionTier,confidence:1,file:i.file,relatedFiles:i.relatedFiles.length>0?i.relatedFiles:void 0,sourceAnalyzer:i.sourceAnalyzer,rootCauseKey:i.rootCauseKey,message:`new ${i.label} vs committed baseline: ${r}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline.",`Underlying analyzer: ${i.sourceAnalyzer}.`,`Inherited action tier: ${i.actionTier}.`,`Root cause key: ${i.rootCauseKey}.`,...i.why],remediation:i.remediation})}}function Fn(e,...t){return`SQ${nT("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}var ET=.7,bf=.62,Sf=.45;function Uc(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=Fp(e);if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let c=TT(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic}).map(u=>jT(u,s,n)).filter(u=>u!==null);c.sort((u,d)=>(u.kind===d.kind?0:u.kind==="echo"?-1:1)||d.similarity-u.similarity||u.echoFile.localeCompare(d.echoFile)||u.echoSymbol.localeCompare(d.echoSymbol)||u.domain.localeCompare(d.domain));let l=c.slice(0,r).map(OT);return{available:!0,windowCommits:n,findings:l,rootCauseGroups:BT(l)}}function TT(e,t){let n=VT(t.limit),r=[..._T(e,{scope:t.scope,minSimilarity:t.minSimilarity??ET,limit:n,scanLimit:t.scanLimit,semantic:t.semantic})],i=to(e,{scope:t.scope});return i.react&&r.push(...FT(e,{scope:t.scope,minSimilarity:t.minSimilarity??bf,limit:n,scanLimit:t.scanLimit}),...$T(e,{scope:t.scope,minSimilarity:t.minSimilarity??Sf,limit:n,scanLimit:t.scanLimit})),i.vue&&r.push(...AT(e,{scope:t.scope,minSimilarity:t.minSimilarity??bf,limit:n,scanLimit:t.scanLimit}),...MT(e,{scope:t.scope,minSimilarity:t.minSimilarity??Sf,limit:n,scanLimit:t.scanLimit})),r}function _T(e,t){return Pt(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic}).map(n=>({domain:"callable",basis:n.similarityBasis??"callees",symbolA:n.shortNameA,fileA:n.fileA,symbolB:n.shortNameB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:n.sharedCallees,sharedCallees:n.sharedCallees}))}function FT(e,t){return ds(e,t,{query:Cn,domain:"react-component",basis:"jsx-structure",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]]})}function ds(e,t,n){return n.query(e,t).filter(r=>r.fileA!==r.fileB).map(r=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(r),fileA:r.fileA,symbolB:n.symbolB(r),fileB:r.fileB,similarity:r.similarity,sharedEvidence:qT(...n.evidenceBuckets(r)),sharedCallees:[]}))}function $T(e,t){return ds(e,t,{query:vn,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["hook",n.sharedHooks],["react-hook",n.sharedReactHooks],["effect",n.sharedEffects],["state",n.sharedState],["request",n.sharedRequests],["handler",n.sharedHandlers],["action",n.sharedHandlerVerbs]]})}function AT(e,t){return ds(e,t,{query:Rn,domain:"vue-component",basis:"vue-template",symbolA:n=>us(n.fileA),symbolB:n=>us(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function MT(e,t){return ds(e,t,{query:kn,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>us(n.fileA),symbolB:n=>us(n.fileB),evidenceBuckets:n=>[["composable",n.sharedComposables],["store",n.sharedStores],["reactivity",n.sharedReactivity],["lifecycle",n.sharedLifecycle],["request",n.sharedRequests],["function",n.sharedFunctions],["action",n.sharedFunctionVerbs],["binding",n.sharedBindings],["template-event",n.sharedTemplateEvents]]})}function jT(e,t,n){let r=t.get(e.fileA)?.commitsAgo??null,i=t.get(e.fileB)?.commitsAgo??null,o=r!==null&&r<=n,s=i!==null&&i<=n;if(!o&&!s)return null;if(o&&s){let a=(r??0)<=(i??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?r:i)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}return{kind:"echo",domain:e.domain,basis:e.basis,echoSymbol:o?e.symbolA:e.symbolB,echoFile:o?e.fileA:e.fileB,echoAgeCommits:(o?r:i)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function OT(e){let t=xf(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function xf(e){if(e.kind==="echo")return["echo",e.domain,e.basis,e.establishedSymbol].join(":");let t=e.sharedEvidence.slice().sort().join("|"),n=[e.echoSymbol,e.establishedSymbol].sort().join("|");return["twin",e.domain,e.basis,t||n].join(":")}function BT(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??xf(r),o=r.groupKey??`recent-duplicate:${i}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:i,kind:r.kind,domain:r.domain,basis:r.basis,count:0,maxSimilarity:r.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:r.kind==="echo"?r.establishedFile:void 0,establishedSymbol:r.kind==="echo"?r.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:HT(r)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,r.similarity),s.findingIndexes.push(n),s.echoFiles.add(r.echoFile),s.relatedFiles.add(r.echoFile),s.relatedFiles.add(r.establishedFile);for(let a of r.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,r)=>r.count-n.count||r.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(r.groupKey))}function HT(e){return e.kind==="echo"?"Review the established side once, then migrate or delete every echo in this group.":"Pick one owner for the new twins and consolidate the group before the copies diverge."}function VT(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function qT(...e){let t=[],n=new Set;for(let[r,i]of e)for(let o of i){let s=`${r}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function us(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var UT=Y("suppression-inventory",{clearGroups:["whole-project"]});function ms(e){return UT.get(e,()=>WT(e))}function WT(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,uncategorized:0},n=new Map,r=0;for(let i of Ie(e)){let o=F(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=Br(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=GT(a);t[c]+=1}}return{total:r,byCategory:t,byFile:n}}function GT(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as zT}from"fs";import{join as JT}from"path";function Li(e,t,n={}){let r=B(e,t);if(!r)return null;let i=new T(e),o=ZT(XT(e,r.relativePath,r.startLine,r.endLine),KT(e,r.relativePath)),s=r.endLine-r.startLine+1,c=i.calleeMap([r],{additive:!0,semantic:n.semantic}).get(r.symbolId)??[],l=new Set(c.map(u=>u.symbol));return{symbol:r.symbol,shortName:b(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o,cyclomaticEstimate:o+1,calleeCount:l.size,fanIn:QT(e,r.symbolId),fanOut:YT(c,r.relativePath)}}function KT(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function XT(e,t,n,r){try{return zT(JT(e.config.projectRoot,t),"utf-8").split(`
|
|
575
|
-
`).slice(n,
|
|
576
|
-
`)}catch{return""}}function
|
|
627
|
+
${e.pathExclusionsFor("ref_d")}`,t).map(i=>i.relative_path)}function $0(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hr(e,t={}){let{scope:n,limit:i=30,scanLimit:r}=t,o=new A(e);return it({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}).filter(s=>M0(s.relativePath)),scanLimit:r,evaluate:s=>{let a=ye(e,s.relativePath)?.callables.find(u=>u.startLine===s.startLine&&u.endLine===s.endLine);if(!a||a.params.length===0||a.params.some(u=>!u.simple)||a.paramsEndLine>=a.endLine)return null;let c=_t(e,s.relativePath),l=[];for(let u=a.params.length-1;u>=0;u--){let d=a.params[u];if(d.name===""||d.name.startsWith("_")||O0(c.get(d.name),a.paramsEndLine,a.endLine))break;l.unshift(d.name)}return l.length===0?null:{symbol:s.symbol,shortName:v(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:l}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:i})}function M0(e){let t=K(e);return t==="typescript"||t==="tsx"||t==="javascript"}function O0(e,t,n){return e?e.some(i=>i>t&&i<=n):!1}var ws=["echo","incomplete-migration","co-change-partner","doc-reference","unused-params","new-dead","baseline"];function Vr(e,t={}){let n=t.base??"HEAD",{minTogether:i=6,minConfidence:r=.6,maxEchoChecks:o=Number.POSITIVE_INFINITY,maxHelpers:s=Number.POSITIVE_INFINITY,minSimilarity:a=.8,includeBaseline:c=!1,scanLimit:l}=t,u=t.semantic!==!1,d=new Set(t.skip??[]),m=vt(e,{base:n}),p=Ti(e,{base:n,plan:m}),f=p.changedFiles,g=new Set(f),y=new Set(m.changedFileLines),S=new Set([...g,...y]),R=_r(e.config.projectRoot,n,Ar(m,f)),k=uF(e.config.projectRoot,n,m,R),x={base:n,changedFiles:f,changedSymbols:p.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],rootCauseGroups:[],note:p.summary.note};if(f.length===0)return x;let b=(C,D)=>{if(d.has(C)){x.skipped.push({check:C,reason:"skipped via --skip"});return}let w=x.findings.length,j=x.skipped.length,J=x.checksRun.length;T(`diff-gate.check.${C}`,D,()=>({check:C,changedFiles:f.length,changedSymbols:p.changedSymbols.length,findingsAdded:x.findings.length-w,skippedAdded:x.skipped.length-j,checksRunAdded:x.checksRun.length-J}))};return b("echo",()=>W0(e,p.changedSymbols,g,k,o,a,l,u,x)),b("incomplete-migration",()=>eF(e,n,m,s,l,u,R,x)),b("co-change-partner",()=>tF(e,S,i,r,x)),b("doc-reference",()=>sF(e,g,y,m.changedRanges,x)),b("unused-params",()=>aF(e,f,x)),b("new-dead",()=>cF(e,p.changedSymbols,k,x)),c&&b("baseline",()=>pF(e,x)),q0(x,e.config.suppressions??[]),x.rootCauseGroups=B0(x.findings),x}function B0(e){let t=new Map;for(let n of e){let i=n.groupKey??`${n.check}:${n.id}`,r=t.get(i);r||(r={groupKey:i,check:n.check,severity:n.severity,actionTier:n.actionTier,sourceAnalyzer:n.sourceAnalyzer,rootCauseKey:n.rootCauseKey,count:0,findingIds:[],files:new Set,relatedFiles:new Set,message:n.message,remediation:n.remediation},t.set(i,r)),r.count+=1,r.findingIds.push(n.id),r.severity=H0(r.severity,n.severity),r.actionTier=V0(r.actionTier,n.actionTier),n.file&&r.files.add(n.file);for(let o of n.relatedFiles??[])r.relatedFiles.add(o)}return[...t.values()].map(n=>({...n,files:[...n.files].sort(),relatedFiles:[...n.relatedFiles].sort()})).sort((n,i)=>i.count-n.count||ks(i.severity)-ks(n.severity)||n.groupKey.localeCompare(i.groupKey))}function H0(e,t){return ks(t)>ks(e)?t:e}function ks(e){return e==="error"?2:e==="warning"?1:0}function V0(e,t){return e?t&&tg(t)>tg(e)?t:e:t}function tg(e){return e==="direct"?2:e==="signal"?1:0}function q0(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let i of e.findings){let r=t.find(o=>U0(o,i));r?e.suppressed.push({finding:i,suppression:r}):n.push(i)}e.findings=n}function U0(e,t){return!e.reason||e.reason.trim()===""||e.expiresAt&&Date.parse(e.expiresAt)<=Date.now()||e.id&&e.id!==t.id||e.check&&e.check!==t.check||e.file&&e.file!==t.file?!1:!!(e.id||e.check)}function Ai(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function W0(e,t,n,i,r,o,s,a,c){c.checksRun.push("echo");for(let l of t.slice(0,r)){if(!le(l.symbol)||i(l))continue;let u=Dr(e,l.symbol,{minSimilarity:o,limit:5,scanLimit:s,semantic:a,sourceCandidateMode:"target-pruned"}),d=[];for(let g of u){let y=g.fileA===l.file?g.fileB:g.fileA,S=g.fileA===l.file?g.shortNameB:g.shortNameA,R=g.fileA===l.file?g.symbolB:g.symbolA;n.has(y)||d.push({otherFile:y,otherShort:S,otherSymbol:R,similarity:g.similarity,similarityBasis:g.similarityBasis??"callees",sharedEvidence:g.sharedCallees})}if(d.length===0)continue;let m=d[0],p=Un("echo",l.symbol,l.file,...d.map(g=>`${g.otherSymbol}|${g.otherFile}`).sort()),f=z0(l,d);Ai(c,{id:p,groupKey:p,actionTier:f,check:"echo",severity:"warning",evidence:"heuristic",confidence:m.similarity,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(d.map(g=>g.otherFile))].sort(),message:X0(l,d),why:Y0(l,d),remediation:Z0(f,l.shortName,m.otherShort)})}t.length>r&&c.skipped.push({check:"echo",reason:`echo check capped at ${r} of ${t.length} changed symbols`})}function z0(e,t){return t.some(i=>G0(e.symbol,i))?"direct":"signal"}function G0(e,t){if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let n=M(e),i=M(t.otherSymbol);return!n||!i?!1:n===i?!0:Q0(t.sharedEvidence)?!1:J0(n,i)}function J0(e,t){let n=ng(e),i=ng(t);if(n.length===0||i.length===0)return!1;let r=new Set(i),o=n.filter(s=>r.has(s)).length;return o>=2&&o/Math.min(n.length,i.length)>=.5}function ng(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}var K0=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function Q0(e){return e.length>=3&&e.every(t=>K0.has(t.toLowerCase()))}function X0(e,t){let n=t[0],i=Math.round(n.similarity*100);return t.length===1?`${e.shortName} (${e.file}) is ${i}% similar to established ${n.otherShort} (${n.otherFile})`:`${e.shortName} (${e.file}) resembles ${t.length} established symbol(s); strongest is ${i}% similar to ${n.otherShort} (${n.otherFile})`}function Y0(e,t){let n=[`${e.shortName} was changed in this diff.`];for(let i of t.slice(0,3))n.push(`${i.otherShort} is outside this diff and scored ${Math.round(i.similarity*100)}% similar by ${i.similarityBasis} evidence.`),n.push(`Shared evidence: ${i.sharedEvidence.slice(0,5).join(", ")||"(none listed)"}.`);return t.length>3&&n.push(`${t.length-3} additional similar match(es) grouped into this finding.`),n}function Z0(e,t,n){return e==="direct"?`Extract or reuse the shared behavior with ${n}, or keep the duplicate with a suppression reason.`:`Review whether ${t} is intentionally parallel to the established implementation(s); extract shared behavior only if the product semantics match.`}function eF(e,t,n,i,r,o,s,a){let c=Br(e,{base:t,maxHelpers:i,diffPlan:n,scanLimit:r,semantic:o,baseContentAt:s});if(!c.available){a.skipped.push({check:"incomplete-migration",reason:"no git history"});return}a.checksRun.push("incomplete-migration"),c.note&&a.skipped.push({check:"incomplete-migration",reason:c.note});for(let l of c.findings){let u=l.leftovers.map(y=>`${y.shortName} (${y.file}, ${Math.round(y.containment*100)}% helper / ${Math.round(y.siteCoverage*100)}% site, ${y.migrationScope})`).join(", "),d=l.leftovers.map(y=>`${y.shortName}: ${y.migrationScope} (${y.migrationScopeReasons[0]})`).join("; "),m=[...l.migratedFiles,...l.leftovers.map(y=>y.file)],p=l.leftovers.length===0?void 0:Math.max(...l.leftovers.map(y=>Math.min(y.containment,y.siteCoverage))),f=l.leftovers.some(y=>y.migrationScope==="possible-subtype"),g=Un("incomplete-migration",l.helperSymbol,l.helperFile,m.join("|"));Ai(a,{id:g,check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:p,file:l.helperFile,symbol:l.helperSymbol,relatedFiles:m,message:`new helper ${l.helperShortName} (${l.helperFile}) is wired into ${l.migratedFiles.length} file(s), but ${l.leftovers.length} similar un-migrated site(s) remain: ${u}`,why:[`${l.helperShortName} is new in this diff and already referenced by ${l.migratedFiles.join(", ")}.`,`Helper shape: ${l.helperShape}; ${l.specificHelperCalleeCount}/${l.helperCalleeCount} helper callees are specific enough to score.`,`Unchanged site(s) still contain the helper's callee pattern: ${u}.`,`Migration scope hints: ${d}.`],remediation:f?`Migrate same-scope sites to ${l.helperShortName}; review possible subtype/variant sites before applying the helper.`:`Migrate the remaining sites to ${l.helperShortName}, or confirm they are intentionally different.`})}}function tF(e,t,n,i,r){let o=kf(e,t,{minTogether:n,minConfidence:0,maxFilesPerCommit:20});if(!o){r.skipped.push({check:"co-change-partner",reason:"no git history"});return}r.checksRun.push("co-change-partner");let s=new Set,a;for(let c of o){let l=t.has(c.fileA),u=t.has(c.fileB);if(l===u)continue;let d=l?c.fileA:c.fileB,m=l?c.fileB:c.fileA,p=l?c.changesA:c.changesB,f=p>0?c.together/p:0;if(f<i||Kc(m)||Kc(d)||!ig(`${e.config.projectRoot}/${m}`))continue;let g=`${d}|${m}`;if(s.has(g))continue;s.add(g);let y=Un("co-change-partner",d,m,String(c.together)),S=Qc(d,m),R=Xc({fileA:d,fileB:m,together:c.together,confidence:f,commitScope:c.commitScope,recency:c.recency,subjectContext:c.subjectContext},S,(a??=Yc(e))(d,m)),k=[d,m].sort().join("|");r.findings.push({id:y,check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${k}`,confidence:f,file:d,relatedFiles:[m],sourceAnalyzer:"co-change",rootCauseKey:k,partnerClass:S.partnerClass,partnerClassReasons:S.reasons,commitScope:c.commitScope,recency:c.recency,focusedTogether:c.focusedTogether,broadTogether:c.broadTogether,broadCommitRatio:c.broadCommitRatio,lastTogetherAt:c.lastTogetherAt,recentTogether:c.recentTogether,subjectContext:c.subjectContext,...R?{declaredCouplingSuggestion:R}:{},message:`${d} changed, but ${m} did not \u2014 they change together ${c.together}x (${Math.round(f*100)}% of the time)`,why:[`${d} is in this diff and ${m} is not.`,`Git history shows ${c.together} co-change(s), which is ${Math.round(f*100)}% of changes to the edited side.`,`History context: ${nF(c)}.`,`Subject context: ${iF(c.subjectContext)}.`,...rF(c),`Partner class: ${S.partnerClass} (${S.reasons.join("; ")}).`],remediation:R?`Update ${m} alongside this change, declare the coupling "${R.name}", or confirm the coupling no longer holds.`:`Update ${m} alongside this change, or confirm the coupling no longer holds.`})}}function nF(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${oF(e.lastTogetherAt)}`}function iF(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}`}function rF(e){let t=[];return e.commitScope==="broad-sweep"&&t.push("Broad-sweep history is weaker than focused co-edits; confirm this is a real coordination contract."),e.recency==="stale"&&t.push("The pair has no co-change in the recent history window; confirm the coupling still holds."),t}function oF(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function sF(e,t,n,i,r){r.checksRun.push("doc-reference");let o=Fi.referenceTargets(e,t,i);if(o.size!==0)for(let s of Hf(e,o)){if(n.has(s.doc))continue;let a=s.citedClaims.length>0?s.citedClaims:Fi.citationContexts(e,s.doc,s.cited),c=Fi.classifyCitation(a),l=Un("doc-reference",s.doc,s.cited.join("|"));Ai(r,{id:l,check:"doc-reference",severity:"warning",evidence:"change-graph",actionTier:c.actionTier,confidence:1,file:s.doc,relatedFiles:s.cited,citationKind:c.citationKind,citationKindReasons:c.reasons,citedClaims:a,message:`${s.doc} cites ${s.cited.join(", ")} as ${Fi.citationKindLabel(c.citationKind)} \u2014 changed in this diff, doc untouched`,why:[`${s.cited.join(", ")} changed in this diff.`,`${s.doc} cites the changed file(s) but was not updated in the same diff.`,...c.reasons.map(u=>`Citation kind evidence: ${u}`)],remediation:Fi.citationRemediation(c.citationKind,s.doc)})}}function aF(e,t,n){n.checksRun.push("unused-params");for(let i of Hr(e,{files:t,limit:50})){let r=Un("unused-params",i.symbol,i.file,i.unusedTrailing.join("|"));Ai(n,{id:r,check:"unused-params",severity:"warning",evidence:"heuristic",confidence:.85,file:i.file,startLine:i.startLine,endLine:i.endLine,symbol:i.symbol,message:`${i.shortName} (${i.file}) has trailing unused parameter(s): ${i.unusedTrailing.join(", ")}`,why:[`${i.shortName} is in a changed file.`,`The trailing parameter(s) ${i.unusedTrailing.join(", ")} are not referenced in the function body.`],remediation:"Drop the unused trailing parameters and their call-site arguments."})}}function cF(e,t,n,i){i.checksRun.push("new-dead");let r=new A(e);for(let o of t){if(n(o)||o.fanIn>0||r.fileKind(o.file)==="test"||Oe(e,o.file)||fe(e,o.symbol,o.file)||lF(o.symbol))continue;let s=Un("new-dead",o.symbol,o.file);Ai(i,{id:s,check:"new-dead",severity:"warning",evidence:"graph-fact",confidence:.9,file:o.file,symbol:o.symbol,message:`${o.shortName} (${o.file}) was changed but has zero indexed consumers`,why:[`${o.shortName} is a changed production symbol.`,"The index reports zero consumers for this symbol.","The symbol is not in a detected entry surface or configured live root."],remediation:"Wire it up, or remove it before it becomes permanent dead code."})}}function lF(e){if(ee(e)!=="type")return!1;let t=M(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function uF(e,t,n,i){let r=new Map(n.renamedFiles.map(s=>[s.to,s.from])),o=i??_r(e,t,Ar(n));return s=>{let a=r.get(s.file)??s.file,c=M(s.symbol);if(!c)return!1;let l=o(a);return l!==null&&dF(l,c)}}function dF(e,t){return new RegExp(`\\b${mF(t)}\\b`).test(e)}function mF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pF(e,t){if(!ig(Rs(e))){t.skipped.push({check:"baseline",reason:"no .scipquery-baseline.json \u2014 run health --write-baseline to enable"});return}t.checksRun.push("baseline");let n=jr(e);for(let i of n.newFindings){let r=$f(i),o=Un("baseline",i);Ai(t,{id:o,groupKey:`baseline:${r.sourceAnalyzer}:${r.rootCauseKey}`,check:"baseline",severity:"error",evidence:"baseline",actionTier:r.actionTier,confidence:1,file:r.file,relatedFiles:r.relatedFiles.length>0?r.relatedFiles:void 0,sourceAnalyzer:r.sourceAnalyzer,rootCauseKey:r.rootCauseKey,message:`new ${r.label} vs committed baseline: ${i}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline.",`Underlying analyzer: ${r.sourceAnalyzer}.`,`Inherited action tier: ${r.actionTier}.`,`Root cause key: ${r.rootCauseKey}.`,...r.why],remediation:r.remediation})}}function Un(e,...t){return`SQ${j0("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}var fF=.7,rg=.62,og=.45;function pl(e,t={}){let{windowCommits:n=100,limit:i=30,scope:r,scanLimit:o}=t,s=vf(e);if(!s)return{available:!1,windowCommits:n,findings:[]};if(i<=0)return{available:!0,windowCommits:n,findings:[]};let a=CF(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=gF(e,{limit:i,minSimilarity:t.minSimilarity,scanLimit:o,scope:r,semantic:t.semantic,focusFiles:Number.isFinite(i)?void 0:a}).map(d=>vF(d,s,n)).filter(d=>d!==null);l.sort((d,m)=>(d.kind===m.kind?0:d.kind==="echo"?-1:1)||m.similarity-d.similarity||d.echoFile.localeCompare(m.echoFile)||d.echoSymbol.localeCompare(m.echoSymbol)||d.domain.localeCompare(m.domain));let u=l.slice(0,i).map(RF);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:kF(u)}}function gF(e,t){let n=IF(t.limit),i=[...hF(e,{scope:t.scope,minSimilarity:t.minSimilarity??fF,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],r=xo(e,{scope:t.scope});return r.react&&i.push(...yF(e,{scope:t.scope,minSimilarity:t.minSimilarity??rg,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...bF(e,{scope:t.scope,minSimilarity:t.minSimilarity??og,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r.vue&&i.push(...SF(e,{scope:t.scope,minSimilarity:t.minSimilarity??rg,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...xF(e,{scope:t.scope,minSimilarity:t.minSimilarity??og,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i}function hF(e,t){return En(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).map(n=>({domain:"callable",basis:n.similarityBasis??"callees",symbolA:n.shortNameA,fileA:n.fileA,symbolB:n.shortNameB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:n.sharedCallees,sharedCallees:n.sharedCallees}))}function yF(e,t){return Ls(e,t,{query:Tn,domain:"react-component",basis:"jsx-structure",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]]})}function Ls(e,t,n){return n.query(e,t).filter(i=>i.fileA!==i.fileB).map(i=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(i),fileA:i.fileA,symbolB:n.symbolB(i),fileB:i.fileB,similarity:i.similarity,sharedEvidence:LF(...n.evidenceBuckets(i)),sharedCallees:[]}))}function bF(e,t){return Ls(e,t,{query:Fn,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["hook",n.sharedHooks],["react-hook",n.sharedReactHooks],["effect",n.sharedEffects],["state",n.sharedState],["request",n.sharedRequests],["handler",n.sharedHandlers],["action",n.sharedHandlerVerbs]]})}function SF(e,t){return Ls(e,t,{query:_n,domain:"vue-component",basis:"vue-template",symbolA:n=>Is(n.fileA),symbolB:n=>Is(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function xF(e,t){return Ls(e,t,{query:An,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>Is(n.fileA),symbolB:n=>Is(n.fileB),evidenceBuckets:n=>[["composable",n.sharedComposables],["store",n.sharedStores],["reactivity",n.sharedReactivity],["lifecycle",n.sharedLifecycle],["request",n.sharedRequests],["function",n.sharedFunctions],["action",n.sharedFunctionVerbs],["binding",n.sharedBindings],["template-event",n.sharedTemplateEvents]]})}function CF(e,t){let n=new Set;for(let[i,r]of e)r.commitsAgo<=t&&n.add(i);return n}function vF(e,t,n){let i=t.get(e.fileA)?.commitsAgo??null,r=t.get(e.fileB)?.commitsAgo??null,o=i!==null&&i<=n,s=r!==null&&r<=n;if(!o&&!s)return null;if(o&&s){let a=(i??0)<=(r??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?i:r)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?r:i,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}return{kind:"echo",domain:e.domain,basis:e.basis,echoSymbol:o?e.symbolA:e.symbolB,echoFile:o?e.fileA:e.fileB,echoAgeCommits:(o?i:r)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?r:i,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function RF(e){let t=sg(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function sg(e){if(e.kind==="echo")return["echo",e.domain,e.basis,e.establishedSymbol].join(":");let t=e.sharedEvidence.slice().sort().join("|"),n=[e.echoSymbol,e.establishedSymbol].sort().join("|");return["twin",e.domain,e.basis,t||n].join(":")}function kF(e){let t=new Map;for(let[n,i]of e.entries()){let r=i.rootCauseKey??sg(i),o=i.groupKey??`recent-duplicate:${r}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:r,kind:i.kind,domain:i.domain,basis:i.basis,count:0,maxSimilarity:i.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:i.kind==="echo"?i.establishedFile:void 0,establishedSymbol:i.kind==="echo"?i.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:wF(i)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,i.similarity),s.findingIndexes.push(n),s.echoFiles.add(i.echoFile),s.relatedFiles.add(i.echoFile),s.relatedFiles.add(i.establishedFile);for(let a of i.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,i)=>i.count-n.count||i.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(i.groupKey))}function wF(e){return e.kind==="echo"?"Review the established side once, then migrate or delete every echo in this group.":"Pick one owner for the new twins and consolidate the group before the copies diverge."}function IF(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function LF(...e){let t=[],n=new Set;for(let[i,r]of e)for(let o of r){let s=`${i}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function Is(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var DF=re("suppression-inventory",{clearGroups:["whole-project"]});function Ds(e){return DF.get(e,()=>PF(e))}function PF(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,uncategorized:0},n=new Map,i=0;for(let r of $e(e)){let o=F(e,r);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=Zi(s);if(a===null)continue;i+=1,n.set(r,(n.get(r)??0)+1);let c=NF(a);t[c]+=1}}return{total:i,byCategory:t,byFile:n}}function NF(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as EF}from"fs";import{join as TF}from"path";function qr(e,t,n={}){let i=V(e,t);if(!i)return null;let r=new A(e),o=MF(_F(e,i.relativePath,i.startLine,i.endLine),FF(e,i.relativePath)),s=i.endLine-i.startLine+1,c=r.calleeMap([i],{additive:!0,semantic:n.semantic}).get(i.symbolId)??[],l=new Set(c.map(u=>u.symbol));return{symbol:i.symbol,shortName:v(i.symbol),relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,loc:s,branches:o,cyclomaticEstimate:o+1,calleeCount:l.size,fanIn:AF(e,i.symbolId),fanOut:$F(c,i.relativePath)}}function FF(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function _F(e,t,n,i){try{return EF(TF(e.config.projectRoot,t),"utf-8").split(`
|
|
628
|
+
`).slice(n,i+1).join(`
|
|
629
|
+
`)}catch{return""}}function AF(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
|
|
577
630
|
FROM mentions m
|
|
578
631
|
JOIN chunks c ON m.chunk_id = c.id
|
|
579
|
-
WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function YT(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function ZT(e,t){let n=mn(e),r=0,i=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let o of i){let s=n.match(o);s&&(r+=s.length)}if(t==="python"){let o=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="rust"){let o=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="ruby"){let o=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="go"){let o=[/\bselect\b/g,/\bdefer\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}return r}function Ii(e,t,n={}){let r=B(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=Kt(e,r,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?b(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=e_(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:b(r.symbol),relativePath:r.relativePath,definitionSites:i.filter(c=>!e.isIgnored(c.file)),usageSites:o,producers:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:b(c.symbol),file:c.file})),consumers:a.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:c.symbol===c.file?"(top-level)":b(c.symbol),file:c.file}))}}function e_(e,t,n,r){let i=br(je(e,t,{limit:30,semantic:r.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=br(Ue(e,t,{limit:30,semantic:r.semantic})),s=o.length>0?o:br(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function kr(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=B(e,t);return o?r==="backward"?t_(e,o,i,{semantic:n.semantic!==!1}):n_(e,o,{semantic:n.semantic!==!1}):null}function t_(e,t,n,r){let i=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let c=[];for(let l of s){let u=je(e,l,{semantic:r.semantic});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),i.push({symbol:d.symbol,shortName:b(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=sr(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:b(t.symbol),direction:"backward",connectedSymbols:i}}function n_(e,t,n){let r=new Set,i=[],o=new T(e);for(let s of Kt(e,t,{semantic:n.semantic})){if(i.length>=30)break;let a=s.enclosingSymbol??Be(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=sr(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:b(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return i.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:b(t.symbol),direction:"forward",connectedSymbols:i}}function Wc(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=!i_(t),a=s?ri(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?li(e,t,{semantic:o}):null,l=s?Li(e,t,{semantic:o}):null,u=s?Ii(e,t,{semantic:o}):null,d=s?kr(e,t,{direction:"backward",maxDepth:i,semantic:o}):null,m=s?kr(e,t,{direction:"forward",maxDepth:i,semantic:o}):null,f=s?gi(e,t,{maxDepth:r,scope:n.scope}):[],h=hi(e,t,{semantic:o}),g=ii(e,t),y=oi(e,t),S=si(e,t),C=ai(e,t),k={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||d!==null||m!==null||f.length>0,file:h!==null||g.length>0||y.length>0,module:S.files.length>0||S.symbols.length>0||C.length>0},D=[];!k.symbol&&!k.file&&!k.module&&D.push("No symbol, file, or module matched target.");let x=h?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:k,history:r_(e,x),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:d,forwardSlice:m,affected:f,changeSurface:h,deps:g,rdeps:y,system:S,surface:C,warnings:D}}function r_(e,t){let n={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return n;let r=Jo(e);if(!r)return n;let i=In(e,t,{limit:5});return{available:!0,file:t,churn:r.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:i.findings.map(o=>({file:o.fileA===t?o.fileB:o.fileA,together:o.together,confidence:o.confidence,subjectContext:o.subjectContext})),suppressionsInFile:ms(e).byFile.get(t)??0}}function i_(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}function Di(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new T(e);return ze({candidates:()=>s.productionCallableDefinitions({scope:n,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,prepare:a=>({callerMap:s.crossFileCallerMap(a,{semantic:t?.semantic!==!1}),calleeMap:s.calleeMap(a,{semantic:t?.semantic!==!1})}),evaluate:(a,c)=>o_(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function o_(e,t,n){let r=e.endLine-e.startLine+1;if(r<n)return null;let i=t.callerMap.get(e.symbolId)?.size??0,o=t.calleeMap.get(e.symbolId)??[],s=o.filter(l=>l.file!==e.relativePath),a=new Set(s.map(l=>`${l.symbol}|${l.file}`)).size,c=new Set(o.map(l=>`${l.symbol}|${l.file}`)).size;return{symbol:e.symbol,shortName:b(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:a,calleeCount:c,score:Math.round(r/50*(i/5)*Math.max(a/5,1)*100)/100}}function Et(e){return e.scoreCount??e.count}function Rf(e){let t=l_(e),{breakdown:n,pressure:r}=u_(e),i=vf(n,"risk"),o=vf(n,"hygiene");return{score:Math.min(i,o),riskScore:i,hygieneScore:o,scoreBreakdown:n,overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:Et(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Et(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:Et(e.wrappers),passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null,hiddenCouplingScoreCount:e.gitEvidence?.hiddenCoupling.scoreCount??null},axes:s_(e),validation:c_(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function s_(e){return{deletable:{loc:e.dead.loc+e.isolated.loc,symbols:e.dead.count+e.isolated.count},cycles:{count:e.realCycleCount},changeAmplification:e.gitEvidence?.amplification??null,hiddenCoupling:e.gitEvidence?.hiddenCoupling??null,churnWeightedComplexity:a_(e),evidenceQuality:{graphFindings:e.dead.count+e.isolated.count+e.realCycleCount,heuristicFindings:e.similarCount+e.reactComponentDuplicates.count+e.reactHookCandidates.count+e.reactLargeComponentPressure.count+e.vueComponentDuplicates.count+e.vueComposableCandidates.count+e.vueLargeViewPressure.count+e.extractCount+e.wrappers.count+e.passthroughs.count+e.stale.count+e.drift.count,userSuppressed:e.suppressions?.total??0}}}function a_(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let r=n.file?t[n.file]?.changes??0:0;return{...n,changes:r,weighted:ht(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function c_(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[],reactComponents:e.reactComponentDuplicates.files??[],reactHooks:e.reactHookCandidates.files??[],reactLargeComponents:e.reactLargeComponentPressure.files??[],vueComponents:e.vueComponentDuplicates.files??[],vueComposables:e.vueComposableCandidates.files??[],vueLargeViews:e.vueLargeViewPressure.files??[]},r=new Set(Object.values(n).flat()),i=0,o=0,s=0;for(let[u,d]of Object.entries(t))r.has(u)?i+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=r.size>0?ht(i/r.size):0,c=s>0?ht(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let f=0;for(let g of m)f+=t[g]?.fixChanges??0;let h=ht(f/m.size);l[u]={flaggedFiles:m.size,fixDensity:h,lift:c>0?ht(h/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?ht(a/c):null,byCategory:l}}function ht(e){return Math.round(e*100)/100}function kf(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function ps(e,t="existing shared infrastructure discount"){let n=Et(e);return Math.abs(n-e.count)<.01?"":` (${kf(n)} score-weighted after ${t})`}function Pi(e,t){let n=Et(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${kf(n)} score-weighted)`}function l_(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",description:`${e.dead.count} symbols with zero references anywhere \u2014 safe to delete`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.isolated.count>0&&t.push({category:"Isolated symbols",evidence:"graph-fact",description:`${e.isolated.count} symbols completely disconnected from the codebase graph`,effort:"low",impact:"medium",count:e.isolated.count,locRecoverable:e.isolated.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",evidence:"graph-fact",description:`${e.realCycleCount} cycle(s) \u2014 break with dependency inversion or module restructuring`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",description:`${e.similarCount} pairs with real logic overlap (beyond shared imports) \u2014 consolidation candidates`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.reactComponentDuplicates.count>0&&t.push({category:"Duplicated React components",evidence:"heuristic",description:`${e.reactComponentDuplicates.count} React component pair(s) share JSX structure \u2014 extract or reuse the shared UI concept`,effort:"medium",impact:"medium",count:e.reactComponentDuplicates.count,locRecoverable:e.reactComponentDuplicates.loc}),e.reactHookCandidates.count>0&&t.push({category:"Duplicated React hook behavior",evidence:"heuristic",description:`${e.reactHookCandidates.count} React component pair(s) share state/effect/request behavior${ps(e.reactHookCandidates)} \u2014 extract or reuse a hook`,effort:"medium",impact:"medium",count:e.reactHookCandidates.count,locRecoverable:e.reactHookCandidates.loc}),e.reactLargeComponentPressure.count>0&&t.push({category:"Large React components",evidence:"heuristic",description:`${e.reactLargeComponentPressure.count} React component(s) concentrate JSX/behavior pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.reactLargeComponentPressure.count,locRecoverable:0}),e.vueComponentDuplicates.count>0&&t.push({category:"Duplicated Vue components",evidence:"heuristic",description:`${e.vueComponentDuplicates.count} Vue component pair(s) share template structure \u2014 extract or reuse the shared UI concept`,effort:"medium",impact:"medium",count:e.vueComponentDuplicates.count,locRecoverable:e.vueComponentDuplicates.loc}),e.vueComposableCandidates.count>0&&t.push({category:"Duplicated Vue behavior",evidence:"heuristic",description:`${e.vueComposableCandidates.count} Vue component pair(s) share state/effect/request behavior${ps(e.vueComposableCandidates)} \u2014 extract or reuse a composable`,effort:"medium",impact:"medium",count:e.vueComposableCandidates.count,locRecoverable:e.vueComposableCandidates.loc}),e.vueLargeViewPressure.count>0&&t.push({category:"Large Vue views",evidence:"heuristic",description:`${e.vueLargeViewPressure.count} Vue file(s) concentrate template/script/style pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.vueLargeViewPressure.count,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",evidence:"heuristic",description:`${e.extractCount} large functions with isolated callee clusters \u2014 review same-file or feature-local extraction seams`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",evidence:"heuristic",description:`${e.wrappers.count} single-consumer symbols${ps(e.wrappers,"boundary-evidence discount")} \u2014 inline direct wrappers or review boundary signals`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",evidence:"heuristic",description:`${e.passthroughs.count} functions that just forward to one callee \u2014 unnecessary indirection`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let i=[];e.stale.unused>0&&i.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&i.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",description:`${i.join(", ")} \u2014 remove unused abstractions; review single-consumer ownership before moving or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.layerViolations>0&&i.push(`${e.drift.layerViolations} layer violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${i.join(", ")} \u2014 remove direct drift; review signal drift against layer ownership`,effort:e.drift.layerViolations>0?"medium":"low",impact:e.drift.layerViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(e.gitEvidence&&e.gitEvidence.hiddenCoupling.pairCount>0){let i=e.gitEvidence.hiddenCoupling.top[0];t.push({category:"Hidden coupling",evidence:"change-graph",description:`${e.gitEvidence.hiddenCoupling.pairCount} file pair(s) co-change without a structural link`+ps({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(i?` (e.g. ${i.fileA} \u2194 ${i.fileB})`:"")+" \u2014 name the shared concept or enforce the sync",effort:"medium",impact:"high",count:e.gitEvidence.hiddenCoupling.pairCount,locRecoverable:0})}let n={high:3,medium:2,low:1},r={low:3,medium:2,high:1};return t.sort((i,o)=>{let s=n[i.impact]*r[i.effort];return n[o.impact]*r[o.effort]-s}),t}var Cf={"dead-code":"risk",isolated:"risk",cycles:"risk",complexity:"risk","hidden-coupling":"risk","cycles-pressure":"risk","complexity-pressure":"risk","hidden-coupling-pressure":"risk",similar:"hygiene","react-component-duplicates":"hygiene","react-hook-candidates":"hygiene","react-large-component-pressure":"hygiene","vue-component-duplicates":"hygiene","vue-composable-candidates":"hygiene","vue-large-view-pressure":"hygiene",extract:"hygiene",wrappers:"hygiene",passthroughs:"hygiene","stale-abstractions":"hygiene",drift:"hygiene","similar-pressure":"hygiene","react-component-duplicates-pressure":"hygiene","react-hook-candidates-pressure":"hygiene","react-large-component-pressure-pressure":"hygiene","vue-component-duplicates-pressure":"hygiene","vue-composable-candidates-pressure":"hygiene","vue-large-view-pressure-pressure":"hygiene","extract-pressure":"hygiene","wrappers-pressure":"hygiene","passthroughs-pressure":"hygiene","stale-abstractions-pressure":"hygiene","drift-pressure":"hygiene"};function vf(e,t){let n=e.filter(r=>r.kind===t).reduce((r,i)=>r+i.points,0);return Math.max(0,Math.min(100,100-n))}function u_(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(x,I,M)=>{I>0&&r.push({axis:x,points:I,detail:M,kind:Cf[x]??"hygiene"})},s=(x,I,M,L,G,xe,Fe)=>{let Ne=Math.max(L,1);if(M<=Ne)return;let Ks=M/Ne,Xs=Math.min(G,Math.ceil(Math.log2(Ks)*xe));if(Xs<=0)return;let kb=Cf[x]??"hygiene";i.push({axis:x,category:I,kind:kb,count:M,threshold:ht(Ne),ratio:ht(Ks),extraPenalty:Xs}),o(x,Xs,`${M} ${Fe} exceed pressure threshold ${ht(Ne)} (${ht(Ks)}x)`)},a=e.dead.count/n;o("dead-code",Math.min(20,Math.round(a*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let c=e.isolated.count/n;o("isolated",Math.min(10,Math.round(c*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),o("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let l=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(l)),`${e.similarCount} similar function pair(s)`);let u=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(u)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let d=Et(e.reactHookCandidates),m=d/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(m)),Pi(e.reactHookCandidates,"duplicated React behavior pair(s)"));let f=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(f/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let h=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(h)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let g=Et(e.vueComposableCandidates),y=g/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(y)),Pi(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let S=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(S/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let C=Et(e.wrappers);o("wrappers",Math.min(3,C),Pi(e.wrappers,"wrapper candidate(s)"));let k=Et(e.passthroughs);o("passthroughs",Math.min(3,k),Pi(e.passthroughs,"passthrough candidate(s)")),o("stale-abstractions",Math.min(8,e.stale.unused),`${e.stale.unused} unused stale abstraction(s); ${e.stale.singleUse} single-consumer signal(s)`);let D=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(D*50)),`${e.drift.direct} direct drift finding(s); ${e.drift.signal} signal drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence){let x=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(x/10)),Pi({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:x},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let x=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",x,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("react-component-duplicates-pressure","Duplicated React components",e.reactComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated React component pair(s)"),s("react-hook-candidates-pressure","Duplicated React hook behavior",d,Math.max(10,t*.01),8,4,"duplicated React behavior pair(s)"),s("react-large-component-pressure-pressure","Large React components",e.reactLargeComponentPressure.count,Math.max(10,t*.01),4,2,"large React component pressure file(s)"),s("vue-component-duplicates-pressure","Duplicated Vue components",e.vueComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated Vue component pair(s)"),s("vue-composable-candidates-pressure","Duplicated Vue behavior",g,Math.max(10,t*.01),8,4,"duplicated Vue behavior pair(s)"),s("vue-large-view-pressure-pressure","Large Vue views",e.vueLargeViewPressure.count,Math.max(10,t*.01),4,2,"large Vue view pressure file(s)"),s("extract-pressure","Extraction candidates",e.extractCount,Math.max(50,n*.01),4,2,"extraction candidate(s)"),s("wrappers-pressure","Wrapper functions",C,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",k,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:r,pressure:i}}import{getHeapStatistics as d_}from"v8";var m_=64*1024*1024;function Gc(){let e=globalThis.gc;if(!e)return;let t=d_();t.heap_size_limit-t.used_heap_size<m_||e()}var p_=50,f_=75e3,g_=5e3,wf=2500,Lf=50,h_=10,wr=["overview","dead","isolated","cycles","similar","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots","git-evidence","suppressions"],y_={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:x_(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:C_(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:v_(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:R_(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:w_(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:L_(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:I_(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:D_(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:P_(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:N_(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:k_(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:E_(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:T_(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:__(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:A_(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:M_(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:F_(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:$_(e,n)})};function zc(e,t,n={}){return Jc(e,[t],n)[0]}function Jc(e,t,n={}){return b_(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>y_[s](e,n.scope,o,r))})}function b_(e,t,n){let r=$e(e),i=j_(r,t);try{return n(r,i)}finally{Oa(e,{semanticProvider:!0}),Gc()}}function Kc(e){return Rf(S_(e))}function S_(e){let t=be(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:be(e,"dead").dead,isolated:be(e,"isolated").isolated,realCycleCount:be(e,"cycles").realCycleCount,similarCount:be(e,"similar").similarCount,reactComponentDuplicates:be(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:be(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:be(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:be(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:be(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:be(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:be(e,"extract-candidates").extractCount,wrappers:be(e,"wrapper-candidates").wrappers,passthroughs:be(e,"passthrough-candidates").passthroughs,stale:be(e,"stale-abstractions").stale,drift:be(e,"drift").drift,complexity:be(e,"complexity-hotspots").complexity,gitEvidence:If(e,"git-evidence")?.gitEvidence??null,suppressions:If(e,"suppressions")?.suppressions??null}}function If(e,t){return e.find(n=>n.phase===t)}function be(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function x_(e,t,n){return ue(e,n,"dead",()=>{let r=Dt(e,{scope:t,...le.dead,scanLimit:n.candidateScanLimit});return fs(H_(e,r.symbols))})}function C_(e,t,n){return ue(e,n,"isolated",()=>{let r=xn(e,{scope:t,...le.isolated,scanLimit:n.candidateScanLimit});return fs(V_(e,r))})}function v_(e,t,n){return ue(e,n,"cycles",()=>Sn(e,{scope:t}).filter(i=>i.kind==="real").length)}function R_(e,t,n){return ue(e,n,"similar",()=>Pt(e,{scope:t,...le.similar,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function k_(e,t,n){return ue(e,n,"extract-candidates",()=>wn(e,{scope:t,...le.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function w_(e,t,n){return ue(e,n,"react-component-duplicates",()=>{let r=Cn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Xc(r)})}function L_(e,t,n){return ue(e,n,"react-hook-candidates",()=>{let r=vn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Nf(r,U_)})}function I_(e,t,n){return ue(e,n,"react-large-component-pressure",()=>{let r=pi(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return q_(r)})}function D_(e,t,n){return ue(e,n,"vue-component-duplicates",()=>{let r=Rn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Xc(r)})}function P_(e,t,n){return ue(e,n,"vue-composable-candidates",()=>{let r=kn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Nf(r,W_)})}function N_(e,t,n){return ue(e,n,"vue-large-view-pressure",()=>{let r=fi(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return fs(r)})}function E_(e,t,n){return ue(e,n,"wrapper-candidates",()=>{let r=_n(e,{scope:t,...le.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Pf(r,G_)})}function T_(e,t,n){return ue(e,n,"passthrough-candidates",()=>{let r=En(e,{scope:t,...le.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Pf(r,z_)})}function __(e,t,n){return ue(e,n,"stale-abstractions",()=>{let r=Tn(e,{scope:t,...le.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=r.filter(o=>o.consumers===0).length;return{count:r.length,loc:r.reduce((o,s)=>o+s.loc,0),files:[...new Set(r.map(o=>o.file))],unused:i,singleUse:r.length-i}})}function F_(e,t){return ue(e,t,"git-evidence",()=>{let n=Jo(e);if(!n)return null;let r=In(e,void 0,{limit:t.candidateResultLimit}),i={};for(let[o,s]of n)i[o]={changes:s.changes,fixChanges:s.fixChanges};return{amplification:_p(e),hiddenCoupling:{pairCount:r.findings.length,scoreCount:Qc(r.findings.reduce((o,s)=>o+Df(s),0)),top:r.findings.slice(0,5).map(o=>({fileA:o.fileA,fileB:o.fileB,together:o.together,confidence:o.confidence,focusedTogether:o.focusedTogether,broadTogether:o.broadTogether,broadCommitRatio:o.broadCommitRatio,lastTogetherAt:o.lastTogetherAt,recentTogether:o.recentTogether,commitScope:o.commitScope,recency:o.recency,scoreWeight:Df(o),subjectContext:o.subjectContext}))},fileStats:i}})}function $_(e,t){return ue(e,t,"suppressions",()=>{let n=ms(e);return{total:n.total,byCategory:{...n.byCategory}}})}function A_(e,t,n){return ue(e,n,"drift",()=>{let r=Nn(e,{scope:t,...le.drift}),i=r.results.filter(a=>a.kind!=="pattern-deviation"),o=i.filter(a=>a.actionTier==="direct").length,s=i.length-o;return{count:i.length,unusedImports:r.unusedImports,layerViolations:r.layerViolations,direct:o,signal:s}})}function M_(e,t,n){return ue(e,n,"complexity-hotspots",()=>{let r=Di(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:!1});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.filter(i=>i.score>p_).length}})}function j_(e,t){let n=e.symbols>=f_||e.documents>=g_,r=t?Number.POSITIVE_INFINITY:Lf,i=t?Number.POSITIVE_INFINITY:h_;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:r,complexityResultLimit:i,releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:wf,candidateResultLimit:r,complexityResultLimit:i,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${wf} symbols and reported their top ${Lf} findings. Enable full mode for unbounded candidate counts.`]}}function O_(e,t){t.releaseCachesBetweenPhases&&(Oa(e),Gc())}function ue(e,t,n,r){B_(n);try{return r()}finally{O_(e,t)}}function B_(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function H_(e,t){return t.filter(n=>!De(e,n.relativePath)&&!ie(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function V_(e,t){return t.filter(n=>!De(e,n.relativePath)&&!ie(e,n.symbol,n.relativePath))}function fs(e){let t=new Set;for(let n of e){let r=n.relativePath??n.file;r&&t.add(r)}return{count:e.length,loc:e.reduce((n,r)=>n+r.loc,0),files:[...t]}}function Pf(e,t){return{...fs(e),scoreCount:Qc(e.reduce((r,i)=>r+t(i),0))}}function q_(e){let t=new Map;for(let n of e)t.set(n.file,Math.max(t.get(n.file)??0,n.loc));return{count:t.size,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function Xc(e){let t=new Map;for(let n of e)t.set(n.fileA,Math.max(t.get(n.fileA)??0,n.locA)),t.set(n.fileB,Math.max(t.get(n.fileB)??0,n.locB));return{count:e.length,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function Nf(e,t){return{...Xc(e),scoreCount:Qc(e.reduce((r,i)=>r+t(i),0))}}function U_(e){let t=e.sharedHooks.length>0,n=Ef({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:Tf(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function W_(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=Ef({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:Tf(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function Ef(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!Ff.has(_f(t))).length+Math.min(e.functions.length,3)}function Tf(e,t,n){let r=[...e,...t,...n].map(_f);return r.length>0&&r.every(i=>Ff.has(i))}function _f(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function G_(e){return e.actionTier==="signal"?.25:1}function z_(e){return e.actionTier==="signal"?.25:1}function Df(e){return e.commitScope==="broad-sweep"?e.recency==="recent"?.25:0:e.commitScope==="mixed"?e.recency==="recent"?.5:.25:e.recency==="recent"?1:.5}function Qc(e){return Math.round(e*100)/100}var Ff=new Set(["add","apply","cancel","change","clear","close","create","delete","draft","edit","error","filter","form","load","loading","name","open","refresh","remove","reset","save","saving","search","select","selected","submit","toggle","update","value"]);function Yc(e,t,n,r={}){let i=B(e,t),o=B(e,n);if(!i||!o)return null;let s=new Set(je(e,i,{semantic:r.semantic}).map(y=>y.symbol)),a=new Set(je(e,o,{semantic:r.semantic}).map(y=>y.symbol)),c=[];for(let y of s)a.has(y)&&c.push(y);let l=[];for(let y of s)a.has(y)||l.push(y);let u=[];for(let y of a)s.has(y)||u.push(y);let d=new Set([...s,...a]),m=d.size>0?c.length/d.size:0,f;d.size===0?f="Neither function calls other tracked symbols. There is no callee-pattern evidence for consolidation; inspect the source bodies directly.":c.length===0?f="These functions do not share any callees. They are not a callee-based consolidation candidate.":l.length===0&&u.length===0?f="These functions have identical tracked callee sets. They are a strong structural match, but identical callees do not prove interchangeable semantics; inspect signatures, control flow, and return values before consolidating.":l.length===0?f="A's tracked callees are a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic before replacing A with B.":u.length===0?f="B's tracked callees are a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic before replacing B with A.":l.length<=2&&u.length<=2?f=`Create a shared function with the ${c.length} common callees. Pass the ${l.length+u.length} divergent callees as parameters or strategy callbacks.`:f=`Extract the ${c.length} shared callees into a common helper. Each function calls the helper plus its own unique logic (${l.length} callees in A, ${u.length} in B).`;let h=i.endLine-i.startLine+1,g=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:b(i.symbol),file:i.relativePath,loc:h},symbolB:{symbol:o.symbol,shortName:b(o.symbol),file:o.relativePath,loc:g},similarity:m,sharedCallees:c.map(b),uniqueToA:l.map(b),uniqueToB:u.map(b),consolidationStrategy:f}}import{readFileSync as $f}from"fs";import{extname as J_,join as Af}from"path";function Zc(e,t,n={}){let{context:r=0}=n,i=K_(t);if(i)return Q_(e,i.filePath,i.startLine,i.endLine,r);let o=B(e,t);return o?X_(e,o,r):null}function K_(e){let t=e.match(/^(.+\.\w+):(\d+)-(\d+)$/);return t?{filePath:t[1],startLine:parseInt(t[2],10),endLine:parseInt(t[3],10)}:null}function X_(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=Af(e.config.projectRoot,t.relativePath),o;try{o=$f(i,"utf-8")}catch{return null}let s=o.split(`
|
|
632
|
+
WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function $F(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function MF(e,t){let n=Cn(e),i=0,r=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let o of r){let s=n.match(o);s&&(i+=s.length)}if(t==="python"){let o=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="rust"){let o=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="ruby"){let o=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}else if(t==="go"){let o=[/\bselect\b/g,/\bdefer\b/g];for(let s of o){let a=n.match(s);a&&(i+=a.length)}}return i}function Ur(e,t,n={}){let i=V(e,t);if(!i)return null;let r=[{file:i.relativePath,line:i.startLine}],o=en(e,i,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?v(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=OF(e,i,o,{semantic:n.semantic!==!1});return{symbol:i.symbol,shortName:v(i.symbol),relativePath:i.relativePath,definitionSites:r.filter(c=>!e.isIgnored(c.file)),usageSites:o,producers:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:v(c.symbol),file:c.file})),consumers:a.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:c.symbol===c.file?"(top-level)":v(c.symbol),file:c.file}))}}function OF(e,t,n,i){let r=Di(Ge(e,t,{limit:30,semantic:i.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=Di(tt(e,t,{limit:30,semantic:i.semantic})),s=o.length>0?o:Di(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:r,consumers:s}}function $i(e,t,n={}){let{direction:i="backward",maxDepth:r=3}=n,o=V(e,t);return o?i==="backward"?jF(e,o,r,{semantic:n.semantic!==!1}):BF(e,o,{semantic:n.semantic!==!1}):null}function jF(e,t,n,i){let r=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let c=[];for(let l of s){let u=Ge(e,l,{semantic:i.semantic});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),r.push({symbol:d.symbol,shortName:v(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=gi(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:v(t.symbol),direction:"backward",connectedSymbols:r}}function BF(e,t,n){let i=new Set,r=[],o=new A(e);for(let s of en(e,t,{semantic:n.semantic})){if(r.length>=30)break;let a=s.enclosingSymbol??Qe(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=gi(e,a);!c||e.isIgnored(c.relativePath)||i.has(c.symbol)||(i.add(c.symbol),r.push({symbol:c.symbol,shortName:v(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return r.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:v(t.symbol),direction:"forward",connectedSymbols:r}}function fl(e,t,n={}){let i=n.impactDepth??3,r=n.sliceDepth??3,o=n.semantic,s=!VF(t),a=s?xr(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?Ir(e,t,{semantic:o}):null,l=s?qr(e,t,{semantic:o}):null,u=s?Ur(e,t,{semantic:o}):null,d=s?$i(e,t,{direction:"backward",maxDepth:r,semantic:o}):null,m=s?$i(e,t,{direction:"forward",maxDepth:r,semantic:o}):null,p=s?Tr(e,t,{maxDepth:i,scope:n.scope}):[],f=Fr(e,t,{semantic:o}),g=Cr(e,t),y=vr(e,t),S=Rr(e,t),R=kr(e,t),k={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||d!==null||m!==null||p.length>0,file:f!==null||g.length>0||y.length>0,module:S.files.length>0||S.symbols.length>0||R.length>0},x=[];!k.symbol&&!k.file&&!k.module&&x.push("No symbol, file, or module matched target.");let b=f?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:k,history:HF(e,b),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:d,forwardSlice:m,affected:p,changeSurface:f,deps:g,rdeps:y,system:S,surface:R,warnings:x}}function HF(e,t){let n={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return n;let i=us(e);if(!i)return n;let r=Mn(e,t,{limit:5});return{available:!0,file:t,churn:i.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:r.findings.map(o=>({file:o.fileA===t?o.fileB:o.fileA,together:o.together,confidence:o.confidence,subjectContext:o.subjectContext})),suppressionsInFile:Ds(e).byFile.get(t)??0}}function VF(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}function Wr(e,t){let{scope:n,minLoc:i=10,limit:r=30,scanLimit:o}=t??{},s=new A(e);return it({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:i,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,prepare:a=>({callerMap:s.crossFileCallerMap(a,{semantic:t?.semantic!==!1}),calleeMap:s.calleeMap(a,{semantic:t?.semantic!==!1})}),evaluate:(a,c)=>qF(a,c,i),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:r})}function qF(e,t,n){let i=e.endLine-e.startLine+1;if(i<n)return null;let r=t.callerMap.get(e.symbolId)?.size??0,o=t.calleeMap.get(e.symbolId)??[],s=new Set,a=new Set;for(let u of o){let d=`${u.symbol}|${u.file}`;s.add(d),u.file!==e.relativePath&&a.add(d)}let c=a.size,l=s.size;return{symbol:e.symbol,shortName:v(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:i,fanIn:r,fanOut:c,calleeCount:l,score:Math.round(i/50*(r/5)*Math.max(c/5,1)*100)/100}}function Mt(e){return e.scoreCount??e.count}function lg(e){let t=GF(e),{breakdown:n,pressure:i}=JF(e),r=cg(n,"risk"),o=cg(n,"hygiene");return{score:Math.min(r,o),riskScore:r,hygieneScore:o,scoreBreakdown:n,overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:Mt(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Mt(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:Mt(e.wrappers),passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null,hiddenCouplingScoreCount:e.gitEvidence?.hiddenCoupling.scoreCount??null},axes:UF(e),validation:zF(e),suppressions:e.suppressions,actions:t,pressure:i,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function UF(e){return{deletable:{loc:e.dead.loc+e.isolated.loc,symbols:e.dead.count+e.isolated.count},cycles:{count:e.realCycleCount},changeAmplification:e.gitEvidence?.amplification??null,hiddenCoupling:e.gitEvidence?.hiddenCoupling??null,churnWeightedComplexity:WF(e),evidenceQuality:{graphFindings:e.dead.count+e.isolated.count+e.realCycleCount,heuristicFindings:e.similarCount+e.reactComponentDuplicates.count+e.reactHookCandidates.count+e.reactLargeComponentPressure.count+e.vueComponentDuplicates.count+e.vueComposableCandidates.count+e.vueLargeViewPressure.count+e.extractCount+e.wrappers.count+e.passthroughs.count+e.stale.count+e.drift.count,userSuppressed:e.suppressions?.total??0}}}function WF(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let i=n.file?t[n.file]?.changes??0:0;return{...n,changes:i,weighted:Rt(n.score*Math.log2(1+i))}}).sort((n,i)=>i.weighted-n.weighted):null}function zF(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[],reactComponents:e.reactComponentDuplicates.files??[],reactHooks:e.reactHookCandidates.files??[],reactLargeComponents:e.reactLargeComponentPressure.files??[],vueComponents:e.vueComponentDuplicates.files??[],vueComposables:e.vueComposableCandidates.files??[],vueLargeViews:e.vueLargeViewPressure.files??[]},i=new Set(Object.values(n).flat()),r=0,o=0,s=0;for(let[u,d]of Object.entries(t))i.has(u)?r+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=i.size>0?Rt(r/i.size):0,c=s>0?Rt(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let p=0;for(let g of m)p+=t[g]?.fixChanges??0;let f=Rt(p/m.size);l[u]={flaggedFiles:m.size,fixDensity:f,lift:c>0?Rt(f/c):null}}return{flaggedFiles:i.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:i.size>0&&c>0?Rt(a/c):null,byCategory:l}}function Rt(e){return Math.round(e*100)/100}function ug(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Ps(e,t="existing shared infrastructure discount"){let n=Mt(e);return Math.abs(n-e.count)<.01?"":` (${ug(n)} score-weighted after ${t})`}function zr(e,t){let n=Mt(e),i=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?i:`${i} (${ug(n)} score-weighted)`}function GF(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",description:`${e.dead.count} symbols with zero references anywhere \u2014 safe to delete`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.isolated.count>0&&t.push({category:"Isolated symbols",evidence:"graph-fact",description:`${e.isolated.count} symbols completely disconnected from the codebase graph`,effort:"low",impact:"medium",count:e.isolated.count,locRecoverable:e.isolated.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",evidence:"graph-fact",description:`${e.realCycleCount} cycle(s) \u2014 break with dependency inversion or module restructuring`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",description:`${e.similarCount} pairs with real logic overlap (beyond shared imports) \u2014 consolidation candidates`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.reactComponentDuplicates.count>0&&t.push({category:"Duplicated React components",evidence:"heuristic",description:`${e.reactComponentDuplicates.count} React component pair(s) share JSX structure \u2014 extract or reuse the shared UI concept`,effort:"medium",impact:"medium",count:e.reactComponentDuplicates.count,locRecoverable:e.reactComponentDuplicates.loc}),e.reactHookCandidates.count>0&&t.push({category:"Duplicated React hook behavior",evidence:"heuristic",description:`${e.reactHookCandidates.count} React component pair(s) share state/effect/request behavior${Ps(e.reactHookCandidates)} \u2014 extract or reuse a hook`,effort:"medium",impact:"medium",count:e.reactHookCandidates.count,locRecoverable:e.reactHookCandidates.loc}),e.reactLargeComponentPressure.count>0&&t.push({category:"Large React components",evidence:"heuristic",description:`${e.reactLargeComponentPressure.count} React component(s) concentrate JSX/behavior pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.reactLargeComponentPressure.count,locRecoverable:0}),e.vueComponentDuplicates.count>0&&t.push({category:"Duplicated Vue components",evidence:"heuristic",description:`${e.vueComponentDuplicates.count} Vue component pair(s) share template structure \u2014 extract or reuse the shared UI concept`,effort:"medium",impact:"medium",count:e.vueComponentDuplicates.count,locRecoverable:e.vueComponentDuplicates.loc}),e.vueComposableCandidates.count>0&&t.push({category:"Duplicated Vue behavior",evidence:"heuristic",description:`${e.vueComposableCandidates.count} Vue component pair(s) share state/effect/request behavior${Ps(e.vueComposableCandidates)} \u2014 extract or reuse a composable`,effort:"medium",impact:"medium",count:e.vueComposableCandidates.count,locRecoverable:e.vueComposableCandidates.loc}),e.vueLargeViewPressure.count>0&&t.push({category:"Large Vue views",evidence:"heuristic",description:`${e.vueLargeViewPressure.count} Vue file(s) concentrate template/script/style pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.vueLargeViewPressure.count,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",evidence:"heuristic",description:`${e.extractCount} large functions with isolated callee clusters \u2014 review same-file or feature-local extraction seams`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",evidence:"heuristic",description:`${e.wrappers.count} single-consumer symbols${Ps(e.wrappers,"boundary-evidence discount")} \u2014 inline direct wrappers or review boundary signals`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",evidence:"heuristic",description:`${e.passthroughs.count} functions that just forward to one callee \u2014 unnecessary indirection`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let r=[];e.stale.unused>0&&r.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&r.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",description:`${r.join(", ")} \u2014 remove unused abstractions; review single-consumer ownership before moving or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let r=[];e.drift.unusedImports>0&&r.push(`${e.drift.unusedImports} unused imports`),e.drift.layerViolations>0&&r.push(`${e.drift.layerViolations} layer violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${r.join(", ")} \u2014 remove direct drift; review signal drift against layer ownership`,effort:e.drift.layerViolations>0?"medium":"low",impact:e.drift.layerViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(e.gitEvidence&&e.gitEvidence.hiddenCoupling.pairCount>0){let r=e.gitEvidence.hiddenCoupling.top[0];t.push({category:"Hidden coupling",evidence:"change-graph",description:`${e.gitEvidence.hiddenCoupling.pairCount} file pair(s) co-change without a structural link`+Ps({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(r?` (e.g. ${r.fileA} \u2194 ${r.fileB})`:"")+" \u2014 name the shared concept or enforce the sync",effort:"medium",impact:"high",count:e.gitEvidence.hiddenCoupling.pairCount,locRecoverable:0})}let n={high:3,medium:2,low:1},i={low:3,medium:2,high:1};return t.sort((r,o)=>{let s=n[r.impact]*i[r.effort];return n[o.impact]*i[o.effort]-s}),t}var ag={"dead-code":"risk",isolated:"risk",cycles:"risk",complexity:"risk","hidden-coupling":"risk","cycles-pressure":"risk","complexity-pressure":"risk","hidden-coupling-pressure":"risk",similar:"hygiene","react-component-duplicates":"hygiene","react-hook-candidates":"hygiene","react-large-component-pressure":"hygiene","vue-component-duplicates":"hygiene","vue-composable-candidates":"hygiene","vue-large-view-pressure":"hygiene",extract:"hygiene",wrappers:"hygiene",passthroughs:"hygiene","stale-abstractions":"hygiene",drift:"hygiene","similar-pressure":"hygiene","react-component-duplicates-pressure":"hygiene","react-hook-candidates-pressure":"hygiene","react-large-component-pressure-pressure":"hygiene","vue-component-duplicates-pressure":"hygiene","vue-composable-candidates-pressure":"hygiene","vue-large-view-pressure-pressure":"hygiene","extract-pressure":"hygiene","wrappers-pressure":"hygiene","passthroughs-pressure":"hygiene","stale-abstractions-pressure":"hygiene","drift-pressure":"hygiene"};function cg(e,t){let n=e.filter(i=>i.kind===t).reduce((i,r)=>i+r.points,0);return Math.max(0,Math.min(100,100-n))}function JF(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),i=[],r=[],o=(b,C,D)=>{C>0&&i.push({axis:b,points:C,detail:D,kind:ag[b]??"hygiene"})},s=(b,C,D,w,j,J,Re)=>{let ie=Math.max(w,1);if(D<=ie)return;let _e=D/ie,Ht=Math.min(j,Math.ceil(Math.log2(_e)*J));if(Ht<=0)return;let uS=ag[b]??"hygiene";r.push({axis:b,category:C,kind:uS,count:D,threshold:Rt(ie),ratio:Rt(_e),extraPenalty:Ht}),o(b,Ht,`${D} ${Re} exceed pressure threshold ${Rt(ie)} (${Rt(_e)}x)`)},a=e.dead.count/n;o("dead-code",Math.min(20,Math.round(a*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let c=e.isolated.count/n;o("isolated",Math.min(10,Math.round(c*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),o("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let l=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(l)),`${e.similarCount} similar function pair(s)`);let u=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(u)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let d=Mt(e.reactHookCandidates),m=d/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(m)),zr(e.reactHookCandidates,"duplicated React behavior pair(s)"));let p=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(p/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let f=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(f)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let g=Mt(e.vueComposableCandidates),y=g/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(y)),zr(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let S=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(S/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let R=Mt(e.wrappers);o("wrappers",Math.min(3,R),zr(e.wrappers,"wrapper candidate(s)"));let k=Mt(e.passthroughs);o("passthroughs",Math.min(3,k),zr(e.passthroughs,"passthrough candidate(s)")),o("stale-abstractions",Math.min(8,e.stale.unused),`${e.stale.unused} unused stale abstraction(s); ${e.stale.singleUse} single-consumer signal(s)`);let x=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(x*50)),`${e.drift.direct} direct drift finding(s); ${e.drift.signal} signal drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence){let b=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(b/10)),zr({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:b},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let b=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",b,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("react-component-duplicates-pressure","Duplicated React components",e.reactComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated React component pair(s)"),s("react-hook-candidates-pressure","Duplicated React hook behavior",d,Math.max(10,t*.01),8,4,"duplicated React behavior pair(s)"),s("react-large-component-pressure-pressure","Large React components",e.reactLargeComponentPressure.count,Math.max(10,t*.01),4,2,"large React component pressure file(s)"),s("vue-component-duplicates-pressure","Duplicated Vue components",e.vueComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated Vue component pair(s)"),s("vue-composable-candidates-pressure","Duplicated Vue behavior",g,Math.max(10,t*.01),8,4,"duplicated Vue behavior pair(s)"),s("vue-large-view-pressure-pressure","Large Vue views",e.vueLargeViewPressure.count,Math.max(10,t*.01),4,2,"large Vue view pressure file(s)"),s("extract-pressure","Extraction candidates",e.extractCount,Math.max(50,n*.01),4,2,"extraction candidate(s)"),s("wrappers-pressure","Wrapper functions",R,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",k,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:i,pressure:r}}import{getHeapStatistics as KF}from"v8";var QF=64*1024*1024;function gl(){let e=globalThis.gc;if(!e)return;let t=KF();t.heap_size_limit-t.used_heap_size<QF||e()}var XF=50,YF=75e3,ZF=5e3,dg=2500,mg=50,e_=10,Mi=["overview","dead","isolated","cycles","similar","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots","git-evidence","suppressions"],t_={overview:(e,t,n,i)=>({phase:"overview",statsResult:i,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:r_(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:o_(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:s_(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:a_(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:l_(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:u_(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:d_(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:m_(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:p_(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:f_(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:c_(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:g_(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:h_(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:y_(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:x_(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:C_(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:b_(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:S_(e,n)})};function Gr(e,t,n={}){return hl(e,[t],n)[0]}function hl(e,t,n={}){return n_(e,n.full!==!1,(i,r)=>{let o={...r,releaseCachesBetweenPhases:!1};return t.map(s=>t_[s](e,n.scope,o,i))})}function n_(e,t,n){let i=Ue(e),r=v_(i,t);try{return n(i,r)}finally{oc(e,{semanticProvider:!0}),gl()}}function yl(e){return lg(i_(e))}function i_(e){let t=De(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:De(e,"dead").dead,isolated:De(e,"isolated").isolated,realCycleCount:De(e,"cycles").realCycleCount,similarCount:De(e,"similar").similarCount,reactComponentDuplicates:De(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:De(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:De(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:De(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:De(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:De(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:De(e,"extract-candidates").extractCount,wrappers:De(e,"wrapper-candidates").wrappers,passthroughs:De(e,"passthrough-candidates").passthroughs,stale:De(e,"stale-abstractions").stale,drift:De(e,"drift").drift,complexity:De(e,"complexity-hotspots").complexity,gitEvidence:pg(e,"git-evidence")?.gitEvidence??null,suppressions:pg(e,"suppressions")?.suppressions??null}}function pg(e,t){return e.find(n=>n.phase===t)}function De(e,t){let n=e.find(i=>i.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function r_(e,t,n){return Se(e,n,"dead",()=>{let i=At(e,{scope:t,...be.dead,scanLimit:n.candidateScanLimit});return Ns(w_(e,i.symbols))})}function o_(e,t,n){return Se(e,n,"isolated",()=>{let i=Nn(e,{scope:t,...be.isolated,scanLimit:n.candidateScanLimit});return Ns(I_(e,i))})}function s_(e,t,n){return Se(e,n,"cycles",()=>Pn(e,{scope:t}).filter(r=>r.kind==="real").length)}function a_(e,t,n){return Se(e,n,"similar",()=>Ec(e,{scope:t,...be.similar,scanLimit:n.candidateScanLimit}))}function c_(e,t,n){return Se(e,n,"extract-candidates",()=>$n(e,{scope:t,...be.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function l_(e,t,n){return Se(e,n,"react-component-duplicates",()=>{let i=Tn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return bl(i)})}function u_(e,t,n){return Se(e,n,"react-hook-candidates",()=>{let i=Fn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return hg(i,D_)})}function d_(e,t,n){return Se(e,n,"react-large-component-pressure",()=>{let i=Nr(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return L_(i)})}function m_(e,t,n){return Se(e,n,"vue-component-duplicates",()=>{let i=_n(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return bl(i)})}function p_(e,t,n){return Se(e,n,"vue-composable-candidates",()=>{let i=An(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return hg(i,P_)})}function f_(e,t,n){return Se(e,n,"vue-large-view-pressure",()=>{let i=Er(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Ns(i)})}function g_(e,t,n){return Se(e,n,"wrapper-candidates",()=>{let i=qn(e,{scope:t,...be.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return gg(i,N_)})}function h_(e,t,n){return Se(e,n,"passthrough-candidates",()=>{let i=Hn(e,{scope:t,...be.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return gg(i,E_)})}function y_(e,t,n){return Se(e,n,"stale-abstractions",()=>{let i=Vn(e,{scope:t,...be.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),r=i.filter(o=>o.consumers===0).length;return{count:i.length,loc:i.reduce((o,s)=>o+s.loc,0),files:[...new Set(i.map(o=>o.file))],unused:r,singleUse:i.length-r}})}function b_(e,t){return Se(e,t,"git-evidence",()=>{let n=us(e);if(!n)return null;let i=Mn(e,void 0,{limit:t.candidateResultLimit}),r={};for(let[o,s]of n)r[o]={changes:s.changes,fixChanges:s.fixChanges};return{amplification:Cf(e),hiddenCoupling:{pairCount:i.findings.length,scoreCount:Sl(i.findings.reduce((o,s)=>o+fg(s),0)),top:i.findings.slice(0,5).map(o=>({fileA:o.fileA,fileB:o.fileB,together:o.together,confidence:o.confidence,focusedTogether:o.focusedTogether,broadTogether:o.broadTogether,broadCommitRatio:o.broadCommitRatio,lastTogetherAt:o.lastTogetherAt,recentTogether:o.recentTogether,commitScope:o.commitScope,recency:o.recency,scoreWeight:fg(o),subjectContext:o.subjectContext}))},fileStats:r}})}function S_(e,t){return Se(e,t,"suppressions",()=>{let n=Ds(e);return{total:n.total,byCategory:{...n.byCategory}}})}function x_(e,t,n){return Se(e,n,"drift",()=>{let i=Bn(e,{scope:t,...be.drift,includePatternDeviations:!1}),r=i.results.filter(a=>a.kind!=="pattern-deviation"),o=r.filter(a=>a.actionTier==="direct").length,s=r.length-o;return{count:r.length,unusedImports:i.unusedImports,layerViolations:i.layerViolations,direct:o,signal:s}})}function C_(e,t,n){return Se(e,n,"complexity-hotspots",()=>{let i=Wr(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:!1});return{top:i.slice(0,5).map(r=>({symbol:r.shortName,score:r.score,file:r.file})),extremeCount:i.filter(r=>r.score>XF).length}})}function v_(e,t){let n=e.symbols>=YF||e.documents>=ZF,i=t?Number.POSITIVE_INFINITY:mg,r=t?Number.POSITIVE_INFINITY:e_;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:i,complexityResultLimit:r,releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:dg,candidateResultLimit:i,complexityResultLimit:r,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${dg} symbols and reported their top ${mg} findings. Enable full mode for unbounded candidate counts.`]}}function R_(e,t){t.releaseCachesBetweenPhases&&(oc(e),gl())}function Se(e,t,n,i){k_(n);try{return i()}finally{R_(e,t)}}function k_(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function w_(e,t){return t.filter(n=>!Oe(e,n.relativePath)&&!fe(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function I_(e,t){return t.filter(n=>!Oe(e,n.relativePath)&&!fe(e,n.symbol,n.relativePath))}function Ns(e){let t=new Set;for(let n of e){let i=n.relativePath??n.file;i&&t.add(i)}return{count:e.length,loc:e.reduce((n,i)=>n+i.loc,0),files:[...t]}}function gg(e,t){return{...Ns(e),scoreCount:Sl(e.reduce((i,r)=>i+t(r),0))}}function L_(e){let t=new Map;for(let n of e)t.set(n.file,Math.max(t.get(n.file)??0,n.loc));return{count:t.size,loc:[...t.values()].reduce((n,i)=>n+i,0),files:[...t.keys()]}}function bl(e){let t=new Map;for(let n of e)t.set(n.fileA,Math.max(t.get(n.fileA)??0,n.locA)),t.set(n.fileB,Math.max(t.get(n.fileB)??0,n.locB));return{count:e.length,loc:[...t.values()].reduce((n,i)=>n+i,0),files:[...t.keys()]}}function hg(e,t){return{...bl(e),scoreCount:Sl(e.reduce((i,r)=>i+t(r),0))}}function D_(e){let t=e.sharedHooks.length>0,n=yg({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:bg(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function P_(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=yg({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:bg(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function yg(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!xg.has(Sg(t))).length+Math.min(e.functions.length,3)}function bg(e,t,n){let i=[...e,...t,...n].map(Sg);return i.length>0&&i.every(r=>xg.has(r))}function Sg(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function N_(e){return e.actionTier==="signal"?.25:1}function E_(e){return e.actionTier==="signal"?.25:1}function fg(e){return e.commitScope==="broad-sweep"?e.recency==="recent"?.25:0:e.commitScope==="mixed"?e.recency==="recent"?.5:.25:e.recency==="recent"?1:.5}function Sl(e){return Math.round(e*100)/100}var xg=new Set(["add","apply","cancel","change","clear","close","create","delete","draft","edit","error","filter","form","load","loading","name","open","refresh","remove","reset","save","saving","search","select","selected","submit","toggle","update","value"]);function xl(e,t,n,i={}){let r=V(e,t),o=V(e,n);if(!r||!o)return null;let s=new Set(Ge(e,r,{semantic:i.semantic}).map(y=>y.symbol)),a=new Set(Ge(e,o,{semantic:i.semantic}).map(y=>y.symbol)),c=[];for(let y of s)a.has(y)&&c.push(y);let l=[];for(let y of s)a.has(y)||l.push(y);let u=[];for(let y of a)s.has(y)||u.push(y);let d=new Set([...s,...a]),m=d.size>0?c.length/d.size:0,p;d.size===0?p="Neither function calls other tracked symbols. There is no callee-pattern evidence for consolidation; inspect the source bodies directly.":c.length===0?p="These functions do not share any callees. They are not a callee-based consolidation candidate.":l.length===0&&u.length===0?p="These functions have identical tracked callee sets. They are a strong structural match, but identical callees do not prove interchangeable semantics; inspect signatures, control flow, and return values before consolidating.":l.length===0?p="A's tracked callees are a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic before replacing A with B.":u.length===0?p="B's tracked callees are a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic before replacing B with A.":l.length<=2&&u.length<=2?p=`Create a shared function with the ${c.length} common callees. Pass the ${l.length+u.length} divergent callees as parameters or strategy callbacks.`:p=`Extract the ${c.length} shared callees into a common helper. Each function calls the helper plus its own unique logic (${l.length} callees in A, ${u.length} in B).`;let f=r.endLine-r.startLine+1,g=o.endLine-o.startLine+1;return{symbolA:{symbol:r.symbol,shortName:v(r.symbol),file:r.relativePath,loc:f},symbolB:{symbol:o.symbol,shortName:v(o.symbol),file:o.relativePath,loc:g},similarity:m,sharedCallees:c.map(v),uniqueToA:l.map(v),uniqueToB:u.map(v),consolidationStrategy:p}}import{readFileSync as Cg}from"fs";import{extname as T_,join as vg}from"path";function Cl(e,t,n={}){let{context:i=0}=n,r=F_(t);if(r)return A_(e,r.filePath,r.startLine,r.endLine,i);let o=V(e,t);return o?__(e,o,i):null}function F_(e){let t=e.match(/^(.+\.\w+):(\d+)-(\d+)$/);return t?{filePath:t[1],startLine:parseInt(t[2],10),endLine:parseInt(t[3],10)}:null}function __(e,t,n){let i=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),r=vg(e.config.projectRoot,t.relativePath),o;try{o=Cg(r,"utf-8")}catch{return null}let s=o.split(`
|
|
580
633
|
`),a=Math.max(0,t.startLine-n),c=Math.min(s.length-1,t.endLine+n),l=s.slice(a,c+1).join(`
|
|
581
|
-
`);return{symbol:t.symbol,shortName:
|
|
582
|
-
`),u=Math.max(0,n-1-
|
|
583
|
-
`);return{symbol:`${s.relative_path}:${n}-${
|
|
634
|
+
`);return{symbol:t.symbol,shortName:v(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:i?.language??Rg(t.relativePath),source:l}}function A_(e,t,n,i,r){let o=Be(e,t);if(!o)return null;let s=e.get("SELECT relative_path, language FROM documents WHERE relative_path = ?",o);if(!s)return null;let a=vg(e.config.projectRoot,s.relative_path),c;try{c=Cg(a,"utf-8")}catch{return null}let l=c.split(`
|
|
635
|
+
`),u=Math.max(0,n-1-r),d=Math.min(l.length-1,i-1+r),m=l.slice(u,d+1).join(`
|
|
636
|
+
`);return{symbol:`${s.relative_path}:${n}-${i}`,shortName:`${s.relative_path}:${n}-${i}`,relativePath:s.relative_path,startLine:u,endLine:d,language:s.language??Rg(s.relative_path),source:m}}function Rg(e){switch(T_(e).toLowerCase()){case".ts":case".tsx":case".mts":case".cts":return"typescript";case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".py":case".pyi":return"python";case".rs":return"rust";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":return"scala";case".rb":return"ruby";case".php":return"php";case".cs":return"csharp";case".vb":return"vb";case".dart":return"dart";case".c":case".h":return"c";case".cc":case".cpp":case".cxx":case".hpp":case".hh":case".hxx":return"cpp";case".vue":return"vue";default:return null}}function vl(e,t={}){let{scope:n,limit:i}=t,r=new A(e),o=q_([...$_(e,n),...j_(e,r,n)]);return U_(o),i?o.slice(0,i):o}function $_(e,t){let n=[];for(let i of M_(e,t)){if(e.isIgnored(i.barrel_path)||e.isIgnored(i.original_path)||ja(e,i.barrel_path)||F(e,i.barrel_path)&&Ho(e,i.barrel_path).length===0)continue;let r=O_(e,i),o=r?.barrel_consumers??0,s=r?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:i.barrel_path,symbol:i.symbol,shortName:v(i.symbol),originalFile:i.original_path,barrelConsumers:o,directConsumers:s,...wg(e,i.barrel_path)})}return n}function M_(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
|
|
584
637
|
barrel_d.id AS barrel_doc_id,
|
|
585
638
|
barrel_d.relative_path AS barrel_path,
|
|
586
639
|
gs.id AS symbol_id,
|
|
@@ -610,7 +663,7 @@ ${n}`.toLowerCase(),i=Dn(r,["historical note","historical record","history note"
|
|
|
610
663
|
-- Only function-level symbols (ending with ().), not module-level
|
|
611
664
|
AND gs.symbol LIKE '%().'
|
|
612
665
|
${n}
|
|
613
|
-
ORDER BY barrel_d.relative_path, gs.symbol`)}function
|
|
666
|
+
ORDER BY barrel_d.relative_path, gs.symbol`)}function O_(e,t){return e.get(`SELECT
|
|
614
667
|
SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
|
|
615
668
|
SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
|
|
616
669
|
FROM (
|
|
@@ -639,7 +692,7 @@ ${n}`.toLowerCase(),i=Dn(r,["historical note","historical record","history note"
|
|
|
639
692
|
AND consumer_d.id != ?
|
|
640
693
|
${e.pathExclusionsFor("consumer_d")}
|
|
641
694
|
GROUP BY consumer_d.id
|
|
642
|
-
)`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function
|
|
695
|
+
)`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function j_(e,t,n){let i=[];for(let r of B_(e,n))Ig(e,r,r)>0||i.push(...H_(e,t,r));return i}function B_(e,t){return B(e,{scope:t,includeIgnored:!1}).filter(n=>Ho(e,n).length>0||cr(e,n).length>0)}function H_(e,t,n){let i=Ho(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>kg(e,t,n,o.sourcePath)),r=cr(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>kg(e,t,n,o.sourcePath));return[...i,...r]}function kg(e,t,n,i){let r=V_(t,i);return r?[{barrelFile:n,symbol:r.symbol,shortName:v(r.symbol),originalFile:i,barrelConsumers:0,directConsumers:Ig(e,i,n),...wg(e,n)}]:[]}function wg(e,t){return Ri(e,t)?{actionTier:"signal",surfaceEvidence:["barrel file is declared on the package public surface"],recommendation:"Review the package API before removing this re-export; local consumers are zero, but external consumers may import through the public barrel."}:{actionTier:"direct",surfaceEvidence:[],recommendation:"Remove this unused re-export when the barrel is not part of an external API surface."}}function Ig(e,t,n){let i=new Set;for(let r of B(e,{includeIgnored:!1}))if(r!==n)for(let o of Ie(e,r))o.sourcePath===t&&i.add(r);return i.size}function V_(e,t){let n=e.definitionsForFile(t);return n.find(i=>ee(i.symbol)==="method")??n[0]??null}function q_(e){let t=new Set,n=[];for(let i of e){let r=`${i.barrelFile}|${i.symbol}|${i.originalFile}`;t.has(r)||(t.add(r),n.push(i))}return n}function U_(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function kl(e,t={}){let{samples:n=50,scope:i,maxDisagreements:r=5}=t,o=new A(e),s=W_(o.productionCallableDefinitions({scope:i,minLoc:2,requireFunctionLikeSymbol:!0}),n);if(s.length===0||!z_(e,s))return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let a={references:Lg(),callees:Lg()},c=[],l=0,u=Yo(e,s);for(let d of s){let m=Es(d,Ii(e,d).map(y=>y.file)),p=Es(d,(u.get(d.symbolId)??[]).map(y=>y.file));if(m.size===0&&p.size===0)continue;l+=1;let f=Es(d,Ln(e,d).map(y=>y.file)),g=Es(d,(o.calleeMap([d],{semantic:!1}).get(d.symbolId)??[]).map(y=>y.file));Dg(a.references,d,"references",f,m,c),Dg(a.callees,d,"callees",g,p,c)}return c.sort((d,m)=>m.cheapOnly.length+m.oracleOnly.length-(d.cheapOnly.length+d.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?Rl(l/s.length):0,scores:["references","callees"].map(d=>J_(d,a[d])),topDisagreements:c.slice(0,r)}}function Lg(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0}}function W_(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let i=n.length/t,r=[];for(let o=0;o<t;o++)r.push(n[Math.floor(o*i)]);return r}function z_(e,t){let n=t[0];if(!n)return!1;try{return Zt(e,n.relativePath).availability().available}catch{return!1}}function Es(e,t){let n=new Set;for(let i of t)i!==e.relativePath&&n.add(i);return n}function Dg(e,t,n,i,r,o){if(i.size===0&&r.size===0)return;e.comparedSymbols+=1,e.cheapTotal+=i.size,e.oracleTotal+=r.size;let s=[],a=[];for(let c of i)r.has(c)?e.agreed+=1:s.push(c);for(let c of r)i.has(c)||a.push(c);(s.length>0||a.length>0)&&o.push({symbol:v(t.symbol),question:n,cheapOnly:s,oracleOnly:a})}var G_={references:!0,callees:!1};function J_(e,t){let n=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed;return{question:e,comparedSymbols:t.comparedSymbols,precision:G_[e]&&t.cheapTotal>0?Rl(t.agreed/t.cheapTotal):null,recall:Rl(n),unverified:i}}function Rl(e){return Math.round(e*1e3)/1e3}function wl(e,t={}){let{scope:n,minLoc:i=1,limit:r,scanLimit:o}=t,s=t.semantic!==!1,a=Q_(e,K_(e,{scope:n,minLoc:i,scanLimit:o}),{semantic:s}),c=Y_(a);return r?c.slice(0,r):c}function K_(e,t){let n=bt(e,{scope:t.scope}).filter(i=>i.isFunctionLike&&!e.isIgnored(i.relativePath)).filter(i=>G(i)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((i,r)=>G(r)-G(i)||i.relativePath.localeCompare(r.relativePath)),qe(n,t.scanLimit)}function Q_(e,t,n){let i=new Map;for(let r of t){let o=Z_(e,r,n);if(!o)continue;let s=i.get(o)??[];s.push(X_(r)),i.set(o,s)}return i}function X_(e){return{symbol:e.symbol,shortName:v(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:G(e)}}function Y_(e){let t=[];for(let[n,i]of e)i.length>=2&&t.push({signature:n,functions:i});return t.sort((n,i)=>{let r=i.functions.length-n.functions.length;if(r!==0)return r;let o=n.functions.reduce((a,c)=>a+c.loc,0);return i.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function Z_(e,t,n){if(n.semantic){let o=Zm(e,t);if(o)return o}let i=eA(t.documentation),r=i?iA(i):null;return r||rA(tA(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function eA(e){return gn(hn(e))}function tA(e,t,n,i,r){let o=F(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=sA(s,n,i,r);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let d=c;d<=l;d+=1){let m=s[d]?.trim();if(m&&(u=u?`${u} ${m}`:m,nA(u)))return u}if(u&&u.includes("("))return u}return null}function nA(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||sr(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function iA(e){if(!e||!e.trim())return null;let t=e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim(),n=t.indexOf("(");return n===-1||(t=t.slice(n),t=t.replace(/\s+/g,"").toLowerCase(),t.length<3)?null:t}function rA(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),i=n.indexOf("(");if(i===-1)return null;let r=n.slice(0,i),s=new RegExp(`\\b${Pg(t)}\\b`,"i").exec(r);s&&typeof s.index=="number"&&(r=r.slice(0,s.index)),r=r.replace(/\b(public|private|protected|internal|final|static|abstract|sealed|virtual|override|async|suspend|inline|constexpr|consteval|constinit|const|pub|fn|function|def|sub|friend|shared|readonly|new|open|partial|export)\b/gi," ").replace(/\s+/g," ").trim();let a=oA(n.slice(i)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").replace(/\s+/g," ").trim();if(!a.startsWith("("))return null;let c=`${r?`${r} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function oA(e){let t=0,n=0,i=0,r=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c===o&&(o=null);continue}if(c==='"'||c==="'"||c==="`"){o=c;continue}if(c==="(")t+=1;else if(c===")")t=Math.max(0,t-1);else if(c==="[")i+=1;else if(c==="]")i=Math.max(0,i-1);else if(c==="<")r+=1;else if(c===">")r=Math.max(0,r-1);else if(c==="{"){if(t===0&&i===0&&r===0)return e.slice(0,a);n+=1}else if(c==="}")n=Math.max(0,n-1);else if(c==="="&&e[a+1]===">"&&t===0&&n===0&&i===0&&r===0)return e.slice(0,a)}return e}function sA(e,t,n,i){let r=Pg(i),o=new RegExp(`\\b${r}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${r}\\b`,"i"),a=[],c=new Set,l=Math.max(0,Math.min(t,e.length-1)),u=Math.max(l,Math.min(e.length-1,Math.max(n,t+4)));for(let d=l;d<=u;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}return a}function Pg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{existsSync as Ag}from"fs";import{join as IA}from"path";import aA from"better-sqlite3";var cA=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".scipquery-cache","__pycache__",".venv","venv"],Oi=class{db;config;pathFilter;statementCache=new Map;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new aA(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000"),this.db.pragma("query_only = ON"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("cache_size = -64000"),this.db.pragma("mmap_size = 268435456")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
|
|
643
696
|
EXISTS (
|
|
644
697
|
SELECT 1
|
|
645
698
|
FROM defn_enclosing_ranges local_der
|
|
@@ -656,8 +709,8 @@ ${n}`.toLowerCase(),i=Dn(r,["historical note","historical record","history note"
|
|
|
656
709
|
AND local_m.role = 1
|
|
657
710
|
${this.pathExclusionsFor("local_d").trimStart()}
|
|
658
711
|
)
|
|
659
|
-
)`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>
|
|
660
|
-
`)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.
|
|
712
|
+
)`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>cA.flatMap(i=>[`AND ${n}.relative_path NOT LIKE '${i}/%'`,`AND ${n}.relative_path NOT LIKE '%/${i}/%'`])).join(`
|
|
713
|
+
`)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.statement(t).all(...n)}get(t,...n){return this.statement(t).get(...n)}close(){this.statementCache.clear(),this.db.close()}statement(t){let n=this.statementCache.get(t);return n||(n=this.db.prepare(t),this.statementCache.set(t,n)),n}};import lA from"ignore";import{readFileSync as uA,existsSync as Il}from"fs";import{dirname as Ll,isAbsolute as Ng,join as Dl,relative as dA,resolve as mA}from"path";function an(e){let t=lA(),n=!1,i=pA(e);for(let r of i)try{let o=uA(r,"utf-8");t.add(o),n=!0}catch{}return n||t.add(fA),{isIgnored:r=>Eg(t,e,r),filter:r=>r.filter(o=>!Eg(t,e,o))}}function pA(e){let t=[],n=Dl(e,".gitignore");Il(n)&&t.push(n);let i=Ll(e),r=0;for(;i!==Ll(i)&&r<5;){let o=Dl(i,".gitignore");if(Il(o)&&t.push(o),Il(Dl(i,".git")))break;i=Ll(i),r++}return t}var fA=`
|
|
661
714
|
# Dependencies
|
|
662
715
|
node_modules/
|
|
663
716
|
vendor/
|
|
@@ -714,30 +767,30 @@ Thumbs.db
|
|
|
714
767
|
|
|
715
768
|
# Type definitions (often noise in queries)
|
|
716
769
|
*.d.ts
|
|
717
|
-
`;function
|
|
718
|
-
`),n}function
|
|
719
|
-
`),{path:n,suppressionCount:
|
|
720
|
-
`)}function
|
|
721
|
-
${m}`:""}`));return}try{t(JSON.parse(Buffer.concat(o).toString("utf8")))}catch(
|
|
770
|
+
`;function Eg(e,t,n){let i=gA(t,n);if(!i)return!1;try{return e.ignores(i)}catch{return!1}}function gA(e,t){if(!t||t===".")return null;if(!Ng(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=Ng(t)?t:mA(e,t),i=dA(e,n).replaceAll("\\","/");return!i||i==="."||i.startsWith("..")?null:i}import{readFileSync as hA,writeFileSync as Tg,existsSync as Jr,mkdirSync as yA}from"fs";import{isAbsolute as bA,join as kt,relative as SA,resolve as Nl}from"path";import{createHash as xA}from"crypto";import{homedir as CA}from"os";var Kr=".scipquery.json",vA={enabled:!1,debounceMs:3e4,cooldownMs:6e4,gitPollMs:2e3,autoRefresh:!0,ignore:[]},RA=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"];function je(e){let t=kt(e,Kr);if(!Jr(t))return{};try{let n=hA(t,"utf-8");return JSON.parse(n)}catch(n){let i=n instanceof Error?n.message:String(n);throw n instanceof SyntaxError?new Error(`invalid ${Kr} at ${t}: ${i}`,{cause:n}):new Error(`unable to read ${Kr} at ${t}: ${i}`,{cause:n})}}function ji(e,t={}){let n=[],i=new Set(RA);for(let[s,a]of(e.languages??[]).entries())i.has(a)||n.push({level:"error",path:`languages[${s}]`,message:`Unsupported language: ${a}`});e.indexerConcurrency!==void 0&&(!Number.isInteger(e.indexerConcurrency)||e.indexerConcurrency<=0)&&n.push({level:"error",path:"indexerConcurrency",message:"Must be a positive integer."}),e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&n.push({level:"error",path:"watch.debounceMs",message:"Must be greater than 0."}),e.watch?.cooldownMs!==void 0&&e.watch.cooldownMs<=0&&n.push({level:"error",path:"watch.cooldownMs",message:"Must be greater than 0."}),e.watch?.gitPollMs!==void 0&&e.watch.gitPollMs<=0&&n.push({level:"error",path:"watch.gitPollMs",message:"Must be greater than 0."}),e.watch?.autoRefresh!==void 0&&typeof e.watch.autoRefresh!="boolean"&&n.push({level:"error",path:"watch.autoRefresh",message:"Must be a boolean."});let r=e.indexer?.typescript;if(r?.projectMode!==void 0&&r.projectMode!=="single"&&r.projectMode!=="workspace"&&n.push({level:"error",path:"indexer.typescript.projectMode",message:'Must be "single" or "workspace".'}),r?.projects!==void 0)if(!Array.isArray(r.projects))n.push({level:"error",path:"indexer.typescript.projects",message:"Must be an array."});else for(let[s,a]of r.projects.entries()){let c=`indexer.typescript.projects[${s}]`;if(typeof a!="string"||a.trim()==="")n.push({level:"error",path:c,message:"Project path must be a non-empty string."});else if(t.projectRoot){let l=Nl(t.projectRoot,a),u=SA(t.projectRoot,l);u.startsWith("..")||bA(u)?n.push({level:"error",path:c,message:"Project path must stay inside the project root."}):Jr(l)||n.push({level:"warning",path:c,message:`TypeScript project path does not exist: ${a}`})}}if(r?.projectMode==="workspace"&&r.pnpmWorkspaces===!0&&n.push({level:"warning",path:"indexer.typescript.pnpmWorkspaces",message:'Ignored when projectMode is "workspace"; explicit TypeScript projects are indexed directly.'}),e.locality!==void 0)if(!wA(e.locality))n.push({level:"error",path:"locality",message:"Must be an object."});else{let s=e.locality.architecturalBoundarySegments;if(s!==void 0)if(!Array.isArray(s))n.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});else for(let[a,c]of s.entries()){let l=`locality.architecturalBoundarySegments[${a}]`;typeof c!="string"||c.trim()===""?n.push({level:"error",path:l,message:"Boundary segment must be a non-empty string."}):(c.includes("/")||c.includes("\\"))&&n.push({level:"error",path:l,message:"Boundary segment must be a single folder name, not a path."})}}if(e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings))n.push({level:"error",path:"declaredCouplings",message:"Must be an array."});else for(let[s,a]of(e.declaredCouplings??[]).entries()){let c=`declaredCouplings[${s}]`;if((!a.name||a.name.trim()==="")&&n.push({level:"error",path:`${c}.name`,message:"Declared coupling name is required."}),!Array.isArray(a.files)||a.files.length<2)n.push({level:"error",path:`${c}.files`,message:"Declared coupling needs at least two files."});else for(let[l,u]of a.files.entries())!u||u.trim()===""?n.push({level:"error",path:`${c}.files[${l}]`,message:"Declared coupling file path is required."}):t.projectRoot&&!Jr(kt(t.projectRoot,u))&&n.push({level:"warning",path:`${c}.files[${l}]`,message:`Declared coupling file does not exist: ${u}`});a.reason!==void 0&&a.reason.trim()===""&&n.push({level:"error",path:`${c}.reason`,message:"Declared coupling reason cannot be blank."})}let o=t.now??new Date;for(let[s,a]of(e.suppressions??[]).entries()){let c=`suppressions[${s}]`;if((!a.reason||a.reason.trim()==="")&&n.push({level:"error",path:`${c}.reason`,message:"Suppression reason is required."}),!a.id&&!a.check&&n.push({level:"error",path:c,message:"Suppression must include id or check."}),a.file!==void 0&&(a.file.trim()===""?n.push({level:"error",path:`${c}.file`,message:"Suppression file path cannot be blank."}):t.projectRoot&&!Jr(kt(t.projectRoot,a.file))&&n.push({level:"warning",path:`${c}.file`,message:`Suppression file does not exist: ${a.file}`})),a.expiresAt){let l=Date.parse(a.expiresAt);Number.isNaN(l)?n.push({level:"error",path:`${c}.expiresAt`,message:"Must be an ISO date string."}):l<=o.getTime()&&n.push({level:"warning",path:`${c}.expiresAt`,message:"Suppression has expired."})}}return n}function Bi(e){return{...vA,...e.watch}}function kA(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return Pl(n);if(t?.dbPath)return Pl(Nl(e,t.dbPath));let r=process.env.XDG_CACHE_HOME||kt(CA(),".cache"),o=xA("sha256").update(Nl(e)).digest("hex").slice(0,12),s=kt(r,"scip-query","projects",o);return Pl(s)}function wt(e,t){let n=kA(e,t);return{cacheDir:n,dbPath:kt(n,"index.db"),indexPath:kt(n,"index.scip"),metaPath:kt(n,"meta.json")}}function Fg(e,t){let n=kt(e,Kr);return Jr(n)||Tg(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4,gitPollMs:2e3,autoRefresh:!0}},null,2)+`
|
|
771
|
+
`),n}function _g(e,t){let n=kt(e,Kr),i=je(e),r={...i,suppressions:[...i.suppressions??[],t]},o=ji(r,{projectRoot:e}).filter(s=>s.level==="error");if(o.length>0){let s=o.map(a=>`${a.path}: ${a.message}`).join("; ");throw new Error(`invalid suppression: ${s}`)}return Tg(n,JSON.stringify(r,null,2)+`
|
|
772
|
+
`),{path:n,suppressionCount:r.suppressions?.length??0}}function Pl(e){return yA(e,{recursive:!0}),e}function wA(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xe(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function Hi(e=xe()){let t=je(e),n=wt(e,t),i=process.env.SCIP_QUERY_INDEX_DB??(Ag(n.dbPath)?n.dbPath:IA(e,"index.db"));return{projectRoot:e,config:t,paths:n,dbPath:i}}function Vi(e){return Hi(e).dbPath}function LA(){let{projectRoot:e,config:t,paths:n,dbPath:i}=Hi();Ag(i)||(console.error("error: No index.db found. Run: scip-query reindex"),process.exit(1));let r={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:e,entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality},o=an(e);return new Oi(r,o)}function rt(e){let t=LA();try{return e(t)}finally{t.close()}}function El(e,t){return t.concat([e])}function Wn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function $g(e){switch(e.state){case"idle":return"Watching (idle)";case"waiting":{let t=Math.round((e.reindexAt-Date.now())/1e3);return`${e.changedFiles} file(s) changed, reindexing in ${t}s...`}case"indexing":return`Reindexing... (${Math.round((Date.now()-e.startedAt)/1e3)}s)`;case"cooldown":return`Cooldown (${Math.round((e.until-Date.now())/1e3)}s)${e.dirty?" \u2014 changes pending":""}`;default:return DA(e)}}function DA(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}import{spawnSync as S6}from"child_process";function Mg(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function Je(e){return e+1}function Ee(e,t){return`${Je(e)}-${Je(t)}`}function Pe(e,t,n){return`${e}:${Ee(t,n)}`}function Ts(e,t=180){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var N={empty(e){console.log(e)},list(e,t){for(let n of e)console.log(t(n))},groupedByFile(e,t,n=i=>i.relativePath){let i="";for(let r of e){let o=n(r);o!==i&&(i&&console.log(""),console.log(o),i=o),console.log(t(r))}},sectionedReport(e){let t=!0;for(let n of e)if(!(n.skipIfEmpty&&n.rows.length===0)){t||console.log(""),t=!1,n.title!==void 0&&console.log(`\u2550\u2550\u2550 ${n.title} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(n.explanation);for(let i of n.rows)console.log(i)}},table(e,t,n){console.log(` ${e.join(" ")}`);let i=n??e.map(r=>r.length);console.log(` ${i.map(r=>"\u2500".repeat(r)).join(" ")}`);for(let r of t)console.log(r)}};var TA=NA(import.meta.url),{version:Fs}=qA(),Qr="__health-phase",_s="__diff-impact-batch",FA=10,_A=4,AA=8,$A=75e3,MA=5e3,Og=2500,OA=4,jA=12,BA=10*1024*1024,jg=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),Bg=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),HA=new Set([...Bg,"suppressions"]),VA=new Set(["similar","extract-candidates"]);function qA(){for(let e of["../package.json","../../package.json"])try{return TA(e)}catch{}return{version:"0.0.0"}}function qi(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
|
|
773
|
+
`)}function UA(e){let t=Ue(e);return t.symbols>=$A||t.documents>=MA}function As(e,t,n,i={}){return UA(e)?n?(i.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0}):(i.quiet||console.error(`Large index detected; ${t} will scan the highest-priority ${Og} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:Og,semantic:!1}):{semantic:!0}}async function $s(e){let{applicability:t,overview:n}=rt(a=>({applicability:WA(a,e),overview:Gr(a,"overview",e)})),i=new Map;i.set("overview",n);let r=Mi.filter(a=>a==="overview"?!1:zA(a,t)?!0:(i.set(a,JA(a)),!1)),o=GA(r);return(await Hg(o,XA(o.length),a=>KA(a,e))).flat().forEach(a=>i.set(a.phase,a)),yl(Mi.map(a=>i.get(a)))}function WA(e,t){return xo(e,{scope:t.scope})}function zA(e,t){return jg.has(e)?t.react:Bg.has(e)?t.vue:!0}function GA(e){let t=[jg,HA,VA],n=new Set,i=[];for(let r of e){if(n.has(r))continue;let o=t.find(a=>a.has(r));if(!o){n.add(r),i.push([r]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),i.push(s)}return i}function JA(e){switch(e){case"react-component-duplicates":return{phase:e,reactComponentDuplicates:{count:0,loc:0,files:[]}};case"react-hook-candidates":return{phase:e,reactHookCandidates:{count:0,loc:0,files:[]}};case"react-large-component-pressure":return{phase:e,reactLargeComponentPressure:{count:0,loc:0,files:[]}};case"vue-component-duplicates":return{phase:e,vueComponentDuplicates:{count:0,loc:0,files:[]}};case"vue-composable-candidates":return{phase:e,vueComposableCandidates:{count:0,loc:0,files:[]}};case"vue-large-view-pressure":return{phase:e,vueLargeViewPressure:{count:0,loc:0,files:[]}};default:throw new Error(`Health phase "${e}" cannot be synthesized.`)}}function KA(e,t){if(e.length===1)return QA(e[0],t).then(o=>[o]);let n=e.join(","),i=process.argv[1]??Fl(import.meta.url),r=[n];return t.scope&&r.push("--scope",t.scope),t.full&&r.push("--full"),_l({cliPath:i,command:Qr,args:r,label:`Health phases "${n}"`})}function QA(e,t){let n=process.argv[1]??Fl(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),_l({cliPath:n,command:Qr,args:i,label:`Health phase "${e}"`})}function _l(e){return new Promise((t,n)=>{let i=e.maxBuffer??BA,r=PA(process.execPath,[...process.execArgv,e.cliPath,e.command,...e.args??[]],{cwd:process.cwd(),env:e.env??process.env,stdio:["ignore","pipe","pipe"]}),o=[],s=[],a=0,c=0,l=!1,u=d=>{l||(l=!0,r.kill(),n(d))};r.stdout.on("data",d=>{if(a+=d.length,a>i){u(new Error(`${e.label} exceeded stdout buffer limit (${i} bytes).`));return}o.push(d)}),r.stderr.on("data",d=>{if(c+=d.length,c>i){u(new Error(`${e.label} exceeded stderr buffer limit (${i} bytes).`));return}s.push(d)}),r.on("error",u),r.on("close",d=>{if(l)return;l=!0;let m=Buffer.concat(s).toString("utf8").trim();if(d!==0){n(new Error(`${e.label} failed${m?`:
|
|
774
|
+
${m}`:""}`));return}try{t(JSON.parse(Buffer.concat(o).toString("utf8")))}catch(p){n(new Error(`${e.label} returned invalid JSON: ${p instanceof Error?p.message:p}`))}})})}async function Hg(e,t,n){let i=new Array(e.length),r=0;async function o(){for(;r<e.length;){let s=r++;i[s]=await n(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),i}var XA=Ug({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:OA,defaultMaximum:jA});function Vg(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
|
|
722
775
|
Codebase Health Score: ${e.score}/100`),console.log(` Risk: ${e.riskScore}/100 (validated predictors: graph facts + change graph)`),console.log(` Hygiene: ${e.hygieneScore}/100 (tidiness candidates)
|
|
723
|
-
`),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${
|
|
724
|
-
`),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let
|
|
725
|
-
Prioritized Actions (highest impact + lowest effort first):`);for(let
|
|
726
|
-
Top Complexity Hotspots:`);for(let
|
|
727
|
-
Score Breakdown (100 minus the following):`);for(let
|
|
728
|
-
No issues found. Codebase is clean.`)}function
|
|
729
|
-
Maintenance Pressure:`);for(let t of e.pressure)console.log(` ${t.category}: ${t.count} / ${t.threshold} threshold (${t.ratio}x, -${t.extraPenalty} ${t.kind})`)}}function
|
|
730
|
-
Axes:`),console.log(` Deletable: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let
|
|
731
|
-
Affected consumer files:`),
|
|
732
|
-
`),console.log("Or download manually:"))
|
|
776
|
+
`),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${Wn(e.overview.indexSizeBytes)}
|
|
777
|
+
`),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let i of e.warnings)console.log(` ${i}`);console.log("")}console.log(" Findings:");let n=e.findings;if(n.deadSymbols>0&&console.log(` Dead code: ${n.deadSymbols} symbols (${n.deadLoc} LOC)`),n.isolatedSymbols>0&&console.log(` Isolated symbols: ${n.isolatedSymbols} (${n.isolatedLoc} LOC)`),n.cycles>0&&console.log(` Circular deps: ${n.cycles}`),n.similarPairs>0&&console.log(` Similar pairs: ${n.similarPairs}`),n.reactComponentDuplicatePairs>0&&console.log(` React components: ${n.reactComponentDuplicatePairs} duplicate pair(s)`),n.reactHookCandidatePairs>0&&console.log(` React hook reuse: ${Tl(n.reactHookCandidatePairs,n.reactHookCandidateScoreCount)} candidate pair(s)`),n.reactLargeComponentPressureFiles>0&&console.log(` React large comps: ${n.reactLargeComponentPressureFiles} component(s)`),n.vueComponentDuplicatePairs>0&&console.log(` Vue components: ${n.vueComponentDuplicatePairs} duplicate pair(s)`),n.vueComposableCandidatePairs>0&&console.log(` Vue composables: ${Tl(n.vueComposableCandidatePairs,n.vueComposableCandidateScoreCount)} candidate pair(s)`),n.vueLargeViewPressureFiles>0&&console.log(` Vue large views: ${n.vueLargeViewPressureFiles} file(s)`),n.extractionCandidates>0&&console.log(` Extract candidates: ${n.extractionCandidates}`),n.wrappers>0&&console.log(` Wrapper functions: ${Tl(n.wrappers,n.wrapperScoreCount)}`),n.passthroughs>0&&console.log(` Passthroughs: ${n.passthroughs}`),n.staleTypes>0&&console.log(` Stale abstractions: ${n.staleTypes}`),n.driftedFiles>0&&console.log(` Pattern drift: ${n.driftedFiles} files`),n.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${n.complexityHotspotCount}`),e.actions.length>0){console.log(`
|
|
778
|
+
Prioritized Actions (highest impact + lowest effort first):`);for(let i=0;i<e.actions.length;i++){let r=e.actions[i],o=r.locRecoverable>0?` (~${r.locRecoverable} LOC recoverable)`:"";console.log(` ${i+1}. [${r.effort} effort / ${r.impact} impact] ${r.description}${o}`)}}if(e.topComplexity.length>0){console.log(`
|
|
779
|
+
Top Complexity Hotspots:`);for(let i of e.topComplexity)console.log(` ${i.score.toFixed(1).padStart(6)} ${i.symbol}`)}if(e$(e),ZA(e),e.scoreBreakdown.length>0){console.log(`
|
|
780
|
+
Score Breakdown (100 minus the following):`);for(let i of e.scoreBreakdown)console.log(` -${String(i.points).padStart(2)} ${i.axis}: ${i.detail}`)}e.actions.length===0&&console.log(`
|
|
781
|
+
No issues found. Codebase is clean.`)}function Tl(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${YA(t)} score-weighted)`}function YA(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function ZA(e){if(e.pressure.length!==0){console.log(`
|
|
782
|
+
Maintenance Pressure:`);for(let t of e.pressure)console.log(` ${t.category}: ${t.count} / ${t.threshold} threshold (${t.ratio}x, -${t.extraPenalty} ${t.kind})`)}}function e$(e){let t=e.axes;if(console.log(`
|
|
783
|
+
Axes:`),console.log(` Deletable: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let i=t.changeAmplification;console.log(` Change amplification: ${i.medianFilesPerCommit} files/commit median, ${i.p90FilesPerCommit} p90 (${i.commitsAnalyzed} commits)`)}if(t.hiddenCoupling&&t.hiddenCoupling.pairCount>0){console.log(` Hidden coupling: ${t.hiddenCoupling.pairCount} co-changing pair(s) without a dependency edge`);for(let i of t.hiddenCoupling.top.slice(0,3))console.log(` ${i.fileA} <-> ${i.fileB} (${i.together}x together, ${Math.round(i.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let i=t.churnWeightedComplexity[0];i.weighted>0&&console.log(` Churn x complexity: hottest is ${i.symbol} (${i.changes} changes, weighted ${i.weighted})`)}let n=t.evidenceQuality;if(console.log(` Evidence quality: ${n.graphFindings} graph-fact finding(s), ${n.heuristicFindings} heuristic finding(s), ${n.userSuppressed} user-suppressed`),e.validation&&e.validation.flaggedFiles>0){let i=e.validation,r=i.ratio===null?"n/a":`${i.ratio}x`;console.log(` Validation: flagged files fix-density ${i.flaggedFixDensity} vs baseline ${i.baselineFixDensity} (${r})`)}}async function qg(e){let t=rt(r=>{let o=vt(r,{base:e.base});return o.note?{kind:"complete",result:Ti(r,{base:e.base})}:o.changedFiles.length===0?{kind:"complete",result:Ti(r,{base:e.base})}:{kind:"batched",plan:o}});if(t.kind==="complete")return t.result;let n=Mg(t.plan.changedFiles,FA),i=await Hg(n,t$(n.length),r=>r$(r,e));return ps(t.plan.changedFiles,i)}var t$=Ug({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:_A,defaultMaximum:AA});function Ug(e){return(t,n=process.env,i=EA)=>n$(t,n,i,e)}function n$(e,t,n,i){let r=t[i.envKey],o=i$(n,i),s=r?parseInt(r,10):o;return!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e)}function i$(e,t){let n=e(),i=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,i))}function r$(e,t){let n=process.argv[1]??Fl(import.meta.url),i=[];return t.base&&i.push("--base",t.base),_l({cliPath:n,command:_s,args:i,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function Wg(e){console.log(`Changed files: ${e.summary.totalChangedFiles}`),console.log(`Changed symbols: ${e.summary.totalChangedSymbols}`),console.log(`Affected consumer files: ${e.summary.totalAffectedFiles}`),e.summary.note&&console.log(`Note: ${e.summary.note}`),console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),N.list(e.changedSymbols,t=>` ${t.file} ${t.shortName} (fan-in: ${t.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
|
|
784
|
+
Affected consumer files:`),N.list(e.affectedConsumers,t=>` ${t.file} (${t.consumedSymbols} symbol(s))`))}var Xr=El,L=(e=>parseInt(e,10)),Yr=(e=>{let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}),ft=parseFloat,Ms=parseInt;function h(e,t,n,...i){return i.length>0?{flags:e,description:t,parser:n,defaultValue:i[0]}:{flags:e,description:t,parser:n}}function Al(){return h("--json","Output as JSON for programmatic consumption")}function $(e=[]){return e.some(t=>t.flags==="--json")?e:[...e,Al()]}function P(e,t=[]){return{category:e,examples:t}}import{execFileSync as Qj}from"child_process";import{existsSync as ao,mkdirSync as Xj,readFileSync as Yj,writeFileSync as Sy}from"fs";import{homedir as Zj}from"os";import{dirname as eB,join as Gi}from"path";import{execFileSync as VO}from"child_process";import{closeSync as qO,copyFileSync as UO,existsSync as Gs,mkdirSync as nu,mkdtempSync as WO,openSync as zO,readFileSync as Js,renameSync as to,rmSync as no,writeFileSync as zh}from"fs";import{basename as zs,dirname as gt,extname as GO,join as Lt}from"path";import{execFileSync as zg}from"child_process";import{existsSync as Jg,readFileSync as c$}from"fs";import{platform as Zr,arch as Kg}from"os";import{dirname as Gg,join as Os}from"path";import{fileURLToPath as l$}from"url";import{execFileSync as o$}from"child_process";import{platform as s$}from"os";var a$=s$()==="win32";function It(e){let t=a$?"where":"which";try{return o$(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var Qg="v0.8.1",$l="https://github.com/scip-code/scip",u$={win32:{x64:Os("vendor","scip","win32-x64","scip.exe"),arm64:Os("vendor","scip","win32-arm64","scip.exe")}};function d$(){let e=Gg(l$(import.meta.url));for(;;){let t=Os(e,"package.json");if(Jg(t))try{if(JSON.parse(c$(t,"utf-8")).name==="scip-query")return e}catch{}let n=Gg(e);if(n===e)return null;e=n}}function Xg(){let e=u$[Zr()]?.[Kg()];if(!e)return null;let t=d$();if(!t)return null;let n=Os(t,e);return Jg(n)?n:null}function js(){return It("scip")?"scip":Xg()}function eo(){return js()!==null}function m$(){let e=Zr(),t=Kg(),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:`${$l}/releases/download/${Qg}/${o}`,filename:o}}function Ml(){let e=m$();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Zr()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
|
|
785
|
+
`),console.log("Or download manually:")):Zr()==="win32"?(console.log("Windows installs should include a managed scip.exe in the scip-query package."),console.log("Reinstall scip-query, or build the managed binary from source with:"),console.log(` npm run build:scip-windows
|
|
733
786
|
`),console.log("Upstream release page:")):console.log("Download from:"),console.log(e?` ${e.url}
|
|
734
|
-
`:` ${
|
|
735
|
-
`),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function
|
|
736
|
-
VALUES (?, ?, NULL, ?)`),c=
|
|
737
|
-
`).filter(
|
|
738
|
-
`)){if(!
|
|
739
|
-
`).filter(Boolean)}catch{return null}}function
|
|
740
|
-
`)[0]}`,a=e.label===e.language?s:`${e.label}: ${s}`;return n(`Skipping ${e.label}: ${s}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,skipped:{language:e.language,reason:a}}}finally{
|
|
787
|
+
`:` ${$l}/releases/tag/${Qg}
|
|
788
|
+
`),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function Yg(e){let t=Xg();if(t)return e(`Using bundled scip CLI at ${t}`),!0;if(Zr()==="darwin"&&It("brew")){e("Installing scip CLI via Homebrew...");try{if(zg("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),It("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(n){let i=n instanceof Error?n.message:String(n);e(`Homebrew install failed: ${i}`)}}if(It("go")){e("Installing scip CLI via go install...");try{if(zg("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),It("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(n){let i=n instanceof Error?n.message:String(n);e(`go install failed: ${i}`)}}return e("Could not auto-install scip CLI."),e(`Install manually from: ${$l}/releases`),!1}import p$ from"better-sqlite3";import{execFileSync as f$}from"child_process";import{existsSync as g$,readdirSync as h$,readFileSync as y$}from"fs";import{extname as Bs,join as Zg}from"path";function cn(e){let t=new Set((e.extensions??id).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!g$(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=an(e.projectRoot),i=b$(e.projectRoot,t).filter(o=>!n.isIgnored(o)),r=new p$(e.dbPath);try{let o=x$(r,i),s=r.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
|
|
789
|
+
VALUES (?, ?, NULL, ?)`),c=r.transaction(u=>{let d=0;for(let m of u){if(o.has(m))continue;let p=y$(Zg(e.projectRoot,m),"utf-8"),f=s.run(C$(m),m,p);d+=Number(f.changes)}return d})(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 b$(e,t){let n=S$(e,t);if(n)return n;let i=[],r=o=>{let s=o?Zg(e,o):e,a;try{a=h$(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Ra.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){r(l);continue}t.has(Bs(c.name).toLowerCase())&&i.push(l)}};return r(""),i.sort()}function S$(e,t){try{return f$("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
|
|
790
|
+
`).filter(i=>i&&t.has(Bs(i).toLowerCase())).sort()}catch{return null}}function x$(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 C$(e){return Bs(e).toLowerCase()===".vue"?"vue":Bs(e).replace(/^\./,"").toLowerCase()||"source"}import{execFileSync as v$}from"child_process";import{existsSync as R$,readdirSync as th}from"fs";import{extname as nh,join as ih}from"path";var k$=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),w$=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function Ot(e){let t=[],n=I$(e),i=N$(e);for(let r of w$){if(L$(e,r.files)){t.push(r.language);continue}if(D$(n,r.globs)){t.push(r.language);continue}T$(i,r.extensions)&&t.push(r.language)}return t.includes("typescript")&&eh(t,"javascript"),t.includes("cpp")&&!i.has(".c")&&eh(t,"c"),t}function I$(e){try{return th(e)}catch{return[]}}function L$(e,t){return t?.length?t.some(n=>R$(ih(e,n))):!1}function D$(e,t){return t?.length?e.some(n=>t.some(i=>P$(n,i))):!1}function P$(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,i]=t.split("*");return e.startsWith(n??"")&&e.endsWith(i??"")}function N$(e){let t=E$(e);if(t)return t;let n=new Set,i=[e];for(;i.length>0;){let r=i.pop();if(!r)continue;let o;try{o=th(r,{withFileTypes:!0})}catch{continue}for(let s of o){if(s.name.startsWith(".")&&!s.name.endsWith("proj")&&!s.name.endsWith("sln")&&s.isDirectory())continue;let a=ih(r,s.name);if(s.isDirectory()){k$.has(s.name)||i.push(a);continue}let c=nh(s.name).toLowerCase();c&&n.add(c)}}return n}function E$(e){try{let t=v$("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let i of t.split(`
|
|
791
|
+
`)){if(!i)continue;let r=nh(i).toLowerCase();r&&n.add(r)}return n}catch{return null}}function T$(e,t){return t?.length?t.some(n=>e.has(n)):!1}function eh(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as rh,readdirSync as F$}from"fs";import{join as Ol}from"path";var _$={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:"rust",indexerBinary:"rust-analyzer",checkCommand:"rust-analyzer --version",indexArgs:({outputPath:e})=>({binary:"rust-analyzer",args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:"https://github.com/rust-lang/rust-analyzer"},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"},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",oh(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",oh(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=Ol(e,"vendor","bin","scip-php"),i=Ol(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",rh(i)?i:rh(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function zn(e){return _$[e]}function oh(e,t){let n;try{n=F$(e)}catch{return null}for(let i of t)for(let r of n)if(r.endsWith(i))return Ol(e,r);return null}import{readFileSync as A$,writeFileSync as $$}from"fs";import{create as jl}from"@bufbuild/protobuf";import{deserializeSCIP as M$,serializeSCIP as O$,DocumentSchema as j$,IndexSchema as B$,SymbolInformationSchema as H$}from"@c4312/scip";function V$(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=q$(e),n=U$(e.flatMap(r=>r.documents??[])),i=sh(e.flatMap(r=>r.externalSymbols??[]));return jl(B$,{metadata:t,documents:n,externalSymbols:i})}function Bl(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(r=>M$(A$(r))),i=V$(n);return $$(t,Buffer.from(O$(i))),{documentCount:i.documents.length,externalSymbolCount:i.externalSymbols.length,inputCount:e.length}}function q$(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let i of e.slice(1)){let r=i.metadata?.projectRoot;if(n&&r&&r!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${r}`)}return t}function U$(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath);if(!i){t.set(n.relativePath,n);continue}t.set(n.relativePath,jl(j$,{language:i.language||n.language,relativePath:i.relativePath||n.relativePath,occurrences:W$([...i.occurrences,...n.occurrences]),symbols:sh([...i.symbols,...n.symbols]),text:G$(i.text,n.text),positionEncoding:i.positionEncoding||n.positionEncoding}))}return[...t.values()]}function W$(e){let t=new Set,n=[];for(let i of e){let r=JSON.stringify(i);t.has(r)||(t.add(r),n.push(i))}return n}function sh(e){let t=new Map;for(let n of e){let i=t.get(n.symbol);if(!i){t.set(n.symbol,n);continue}t.set(n.symbol,jl(H$,{symbol:i.symbol,documentation:J$([...i.documentation,...n.documentation]),relationships:z$([...i.relationships,...n.relationships]),kind:i.kind||n.kind,displayName:i.displayName||n.displayName,enclosingSymbol:i.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:i.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function z$(e){let t=new Set,n=[];for(let i of e){let r=[i.symbol,i.isReference?"1":"0",i.isImplementation?"1":"0",i.isTypeDefinition?"1":"0",i.isDefinition?"1":"0"].join("|");t.has(r)||(t.add(r),n.push(i))}return n}function G$(e,t){return e?t?e.length>=t.length?e:t:e:t}function J$(e){return[...new Set(e)]}import{execFileSync as K$}from"child_process";import{createHash as Q$}from"crypto";import{readdirSync as X$,readFileSync as Y$}from"fs";import{join as ch}from"path";function ah(e){return(eM(e)??tM(e)).filter(t=>t&&!lh(t)).sort()}function Gn(e,t={}){return(t.language?ah(e).filter(i=>Z$(i,t.language,t.markerFiles)):ah(e)).map(i=>{let r=ch(e,i);try{let o=Y$(r);return{path:i,size:o.byteLength,hash:Q$("sha256").update(o).digest("hex")}}catch{return{path:i,size:-1,hash:"unreadable"}}})}function Z$(e,t,n){let i=e.split("/").at(-1)??e;if(n?.includes(e)||n?.includes(i)||iM.has(i))return!0;let r=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return(rM[t]??[]).includes(r)}function eM(e){try{return K$("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
|
|
792
|
+
`).filter(Boolean)}catch{return null}}function tM(e){let t=[],n=[""];for(;n.length>0;){let i=n.pop(),r=i?ch(e,i):e,o;try{o=X$(r,{withFileTypes:!0})}catch{continue}for(let s of o){let a=i?`${i}/${s.name}`:s.name;if(s.isDirectory()){lh(a)||n.push(a);continue}t.push(a)}}return t}function lh(e){return e.split("/").some(n=>nM.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var nM=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]),iM=new Set(["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lockb","tsconfig.json","tsconfig.base.json","pyproject.toml","setup.py","setup.cfg","Cargo.toml","Cargo.lock","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","build.sbt","compile_commands.json","CMakeLists.txt","Makefile","Gemfile","Gemfile.lock","composer.json","composer.lock","pubspec.yaml","pubspec.lock"]),rM={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".mjs",".cjs"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"]};import{readFileSync as oM,writeFileSync as sM}from"fs";import{create as uh}from"@bufbuild/protobuf";import{deserializeSCIP as aM,DocumentSchema as cM,IndexSchema as lM,serializeSCIP as uM,SymbolRole as dM}from"@c4312/scip";function dh(e){let t;try{t=aM(oM(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=mM(t);return n.removedDefinitionOccurrences>0&&sM(e,Buffer.from(uM(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function mM(e){let t=new Set;for(let o of e.documents)for(let s of o.symbols)s.symbol&&t.add(s.symbol);for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,i=0,r=[];for(let o of e.documents){let s=o.occurrences.filter(a=>(a.symbolRoles&dM.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){r.push(o);continue}i+=1,r.push(uh(cM,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:uh(lM,{metadata:e.metadata,documents:r,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:i}}import{existsSync as pM,readFileSync as fM,readdirSync as gM,statSync as hM}from"fs";import Ce from"path";var yM=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function mh(e,t=[]){let n=Ce.resolve(e),i=bM(n),r=t.flatMap(c=>SM(n,c)),o=CM([...i,...r]),s=vM(n,o)?[n,...o]:o,a=s.length>0?s:[n];return[...new Set(a.map(c=>kM(n,c)))].sort((c,l)=>c.localeCompare(l))}function bM(e){let t=[],n=[e];for(;n.length>0;){let i=n.pop(),r;try{r=gM(i,{withFileTypes:!0})}catch{continue}for(let o of r){let s=Ce.join(i,o.name);if(o.isDirectory()){!yM.has(o.name)&&!o.name.startsWith(".")&&n.push(s);continue}o.isFile()&&xM(s)&&t.push(Ce.dirname(s))}}return t}function SM(e,t){let n=t.trim();if(!n)return[];let i=Ce.resolve(e,n);if(!IM(e,i))return[];try{let r=hM(i);if(r.isDirectory())return[i];if(r.isFile()&&ph(Ce.basename(i)))return[Ce.dirname(i)]}catch{return[]}return[]}function xM(e){if(!ph(Ce.basename(e)))return!1;let t=fh(e);return t?Ce.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function ph(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function CM(e){let t=[...new Set(e.map(n=>Ce.resolve(n)))].sort((n,i)=>n.localeCompare(i));return t.length<=1?t:t.filter(n=>!t.some(i=>i!==n&&wM(n,i)))}function vM(e,t){if(t.length===0||t.some(i=>Ce.resolve(i)===e))return!1;let n=Ce.join(e,"tsconfig.json");return pM(n)&&RM(n)}function RM(e){let n=fh(e)?.include;return Array.isArray(n)?n.some(i=>typeof i=="string"&&i.trim()!==""&&!i.startsWith("!")&&(i.includes("/")||i.includes("**")||!Ce.extname(i))):!1}function fh(e){try{let t=JSON.parse(fM(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function kM(e,t){let n=Ce.relative(e,t);return n?n.split(Ce.sep).join("/"):"."}function wM(e,t){let n=Ce.relative(e,t);return!!n&&!n.startsWith("..")&&!Ce.isAbsolute(n)}function IM(e,t){let n=Ce.relative(e,t);return!n.startsWith("..")&&!Ce.isAbsolute(n)}import{execFile as LM}from"child_process";import{existsSync as Hs,renameSync as Vl,rmSync as ql}from"fs";import{cpus as DM}from"os";import{join as gh}from"path";function PM(e,t,n){if(!e.defaultOutputPath)return;let i=gh(t,e.defaultOutputPath);n!==i&&Hs(i)&&Vl(i,n)}function NM(e,t,n){if(!e.defaultOutputPath)return null;let i=gh(t,e.defaultOutputPath);if(i===n)return null;let r=`${n}.default-output-backup`;return ql(r,{force:!0}),Hs(i)?(Vl(i,r),{defaultOutputPath:i,backupPath:r}):{defaultOutputPath:i,backupPath:null}}function EM(e){e&&(ql(e.defaultOutputPath,{force:!0}),e.backupPath&&Hs(e.backupPath)&&Vl(e.backupPath,e.defaultOutputPath))}function TM(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,DM().length));return Math.max(1,Math.min(e,Math.floor(i)))}async function hh(e,t,n,i){let r=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=TM(o.length,i),c=await _M(o,a,l=>Hl(l,t,n));if(a>1){let l=new Map;for(let u of c.filter(d=>d.skipped)){let d=o.find(m=>m.id===u.id);d&&(n(`Retrying ${d.label} indexer serially after parallel failure...`),l.set(d.id,await Hl(d,t,n)))}s.push(...c.map(u=>l.get(u.id)??u))}else s.push(...c);for(let l of r)s.push(await Hl(l,t,n));return s.sort((l,u)=>e.findIndex(d=>d.id===l.id)-e.findIndex(d=>d.id===u.id))}async function Hl(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),ql(e.scipPath,{force:!0});let i=NM(e.config,t,e.scipPath);try{await FM(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),PM(e.config,t,e.scipPath)}catch(r){let o=r instanceof Error?r.message:String(r),s=`${e.resolvedBinary} indexer failed: ${o.split(`
|
|
793
|
+
`)[0]}`,a=e.label===e.language?s:`${e.label}: ${s}`;return n(`Skipping ${e.label}: ${s}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,skipped:{language:e.language,reason:a}}}finally{EM(i)}if(!Hs(e.scipPath)){let r=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,o=e.label===e.language?r:`${e.label}: ${r}`;return n(`Skipping ${e.label}: ${r}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,skipped:{language:e.language,reason:o}}}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath}}function FM(e,t,n){return new Promise((i,r)=>{LM(e,[...t],n,o=>{o?r(o):i()})})}async function _M(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 Wl}from"child_process";import{existsSync as Ul,readFileSync as AM}from"fs";import{createRequire as $M}from"module";import{platform as MM}from"os";import{dirname as yh,join as Vs}from"path";var OM=$M(import.meta.url);function zl(e){return[e.indexerBinary,...e.binaryAliases??[]]}function qs(e){let t=zl(e);return t.length===1?t[0]:t.join(" or ")}function Ui(e){for(let t of zl(e))if(It(t))return t;return BM(e)}function bh(e){return Ui(e)!==null||jM(e)}function jM(e){return Sh(e)!==null}function BM(e){let t=Sh(e);if(!t)return null;let i=JSON.parse(AM(t,"utf8")).bin;if(!i)return null;if(typeof i=="string")return Vs(yh(t),i);for(let r of zl(e)){let o=i[r];if(o)return Vs(yh(t),o)}return null}function Sh(e){if(!e.bundledNpmPackage)return null;try{return OM.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function Gl(e,t){for(let n of e.projectLocalBinaries??[]){let i=Vs(t,n);if(Ul(i))return i}return null}function HM(e,t){return Gl(e,t)??Ui(e)}function xh(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Jl(n,t))return t;let i=Ch(n,t);return i?{...t,DOTNET_ROOT:i}:t}function Us(e,t){let n=qs(e),i=t?HM(e,t):Ui(e);if(!i)return{language:e.language,binaryLabel:n,installed:!1,runnable:!1,resolvedBinary:null,installUrl:e.installUrl};if(e.indexerBinary!=="scip-dotnet")return{language:e.language,binaryLabel:n,installed:!0,runnable:!0,resolvedBinary:i};let r=VM(i);return{language:e.language,binaryLabel:n,installed:!0,runnable:r.runnable,resolvedBinary:i,installUrl:e.installUrl,note:r.note}}function Ws(e,t){let n=e.installMethods,i=qs(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(It(r.prerequisite)){t(`Installing ${i} via ${r.label}...`);try{Wl(r.binary,r.args,{stdio:"inherit",timeout:3e5,env:process.env});let o=Ui(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}function VM(e){if(Jl(e,process.env))return{runnable:!0};let t=Ch(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=vh(process.env);return{runnable:!1,note:n.length>0?`.NET 9 runtime still unavailable after checking ${n.join(", ")}`:"binary is present, but scip-dotnet still needs a .NET 9 runtime"}}function Ch(e,t){for(let n of vh(t))if(Jl(e,{...t,DOTNET_ROOT:n}))return n;return null}function vh(e){let t=[],n=e.DOTNET_ROOT;if(n&&Ul(n)&&t.push(n),MM()==="darwin"&&It("brew"))try{let i=Wl("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),r=Vs(i,"libexec");Ul(r)&&!t.includes(r)&&t.push(r)}catch{}return t}function Jl(e,t){try{return Wl(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import vO from"better-sqlite3";import{existsSync as RO,readFileSync as kO,writeFileSync as wO}from"fs";import{dirname as IO,join as LO,resolve as DO}from"path";import{readFileSync as qM,rmSync as UM,statSync as WM,mkdtempSync as zM}from"fs";import{cpus as GM,tmpdir as JM}from"os";import{join as Kl}from"path";import{Worker as KM}from"worker_threads";function Rh(e){return e.length>=8&&wh(e.length)>1}function kh(e){let t=wh(e.vueFiles.length),n=XM(e.vueFiles),i=ZM(n,t),r=new URL("./augment-vue-worker.js",import.meta.url),o=zM(Kl(JM(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=QM(),l=Date.now();try{for(let d=0;d<i.length;d++)new KM(r,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:i[d],resultPath:Kl(o,`${d}.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 u=i.map((d,m)=>{let p=JSON.parse(qM(Kl(o,`${m}.json`),"utf-8"));if(!p.ok)throw new Error(`Vue reference worker failed: ${p.error}`);return p.result});return{occurrences:u.flatMap(d=>d.occurrences),skippedReferences:u.reduce((d,m)=>d+m.skippedReferences,0)}}finally{UM(o,{recursive:!0,force:!0})}}function wh(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:Math.min(8,Math.max(1,GM().length-1));return Math.max(1,Math.min(e,n))}function QM(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function XM(e){let t=YM(),n=[];for(let i of e){let r=Ih(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 YM(){return Number.POSITIVE_INFINITY}function ZM(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),i=e.map(r=>({task:r,weight:eO(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 eO(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Ih(e.fileName)-e.startOffset)}function Ih(e){try{return WM(e).size}catch{return 1}}import{createRequire as tO}from"module";import{existsSync as nO,readFileSync as Xl}from"fs";import{dirname as Lh,extname as iO,join as Dh,relative as rO,resolve as oO}from"path";import{pathToFileURL as sO}from"url";function aO(e){e.transaction(()=>{e.prepare(`
|
|
741
794
|
DELETE FROM mentions
|
|
742
795
|
WHERE chunk_id IN (
|
|
743
796
|
SELECT c.id
|
|
@@ -752,12 +805,12 @@ Affected consumer files:`),P.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
|
|
|
752
805
|
FROM documents
|
|
753
806
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
754
807
|
)
|
|
755
|
-
`).run()})()}function
|
|
808
|
+
`).run()})()}function Ph(e,t){return e.prepare(`
|
|
756
809
|
SELECT relative_path AS relativePath
|
|
757
810
|
FROM documents
|
|
758
811
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
759
812
|
ORDER BY relative_path
|
|
760
|
-
`).all().map(
|
|
813
|
+
`).all().map(i=>oO(t,i.relativePath))}function Nh(e,t){let{vueCore:n,ts:i,volarTs:r}=cO(e),{parsed:o,vueOptions:s}=lO(n,i,t),a=Lh(t),c=n.createVueLanguagePlugin(i,o.options,s,p=>p),l=uO(n,i,c),u=dO(a,o),{languageServiceHost:d}=r.createLanguageServiceHost(i,i.sys,l,p=>p,u),m=i.createLanguageService(d);return{ts:i,language:l,languageService:m,fileNames:o.fileNames,configDir:a}}function cO(e){let t=tO(sO(Dh(e,"package.json")).href);return{vueCore:Ql(t,"@vue/language-core",e),ts:Ql(t,"typescript",e),volarTs:Ql(t,"@volar/typescript",e)}}function lO(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,Lh(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function uO(e,t,n){let i={},r=e.createLanguage([n],new Map,o=>{if(!nO(o))return;let s=Xl(o,"utf-8");i.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??yO(o))});return i.current=r,r}function dO(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Ql(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 Eh(e,t,n){let i=mO(e);return r=>{let o=Jn(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.containingByLine.get(a.line);return l!==void 0?l:pO(c.starts,a.line,2)}}function mO(e){let t=e.prepare(`
|
|
761
814
|
SELECT
|
|
762
815
|
d.relative_path AS relativePath,
|
|
763
816
|
der.start_line AS startLine,
|
|
@@ -766,23 +819,23 @@ Affected consumer files:`),P.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
|
|
|
766
819
|
FROM defn_enclosing_ranges der
|
|
767
820
|
JOIN documents d ON d.id = der.document_id
|
|
768
821
|
ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
|
|
769
|
-
`).all(),n=new Map;for(let
|
|
822
|
+
`).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});for(let o=i.startLine;o<=i.endLine;o++)r.containingByLine.set(o,i.symbolId)}for(let i of n.values())i.starts.sort((r,o)=>r.line-o.line);return n}function pO(e,t,n){let i=0,r=e.length-1;for(;i<=r;){let s=Math.floor((i+r)/2);e[s].line<t?i=s+1:r=s-1}let o=null;for(let s of[r,i]){let a=e[s];if(!a)continue;let c=Math.abs(a.line-t);c>n||(!o||c<o.distance)&&(o={distance:c,symbolId:a.symbolId})}return o?.symbolId??null}function Th(e,t,n){let i=xO(t),r=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
|
|
770
823
|
INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
|
|
771
824
|
VALUES (?, ?, ?, ?)
|
|
772
|
-
`),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let u=
|
|
825
|
+
`),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let u=Jn(t,l),d=Hh(i.name,i.version,u);o.run(d,"default",7,`Vue component|${u}`);let m=CO(r,i,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Fh(e,t,n,i,r){return e.transaction(()=>(aO(e),fO(e,t,n,i),gO(e,r)))()}function fO(e,t,n,i){let r=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
|
|
773
826
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
774
827
|
VALUES (?, ?, ?, ?, X'00')
|
|
775
828
|
`),s=e.prepare(`
|
|
776
829
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
777
830
|
VALUES (?, ?, 1)
|
|
778
|
-
`);for(let a of n){let c=
|
|
831
|
+
`);for(let a of n){let c=i.get(a);if(!c)continue;let l=Jn(t,a),u=r.get(l);if(!u)continue;let d=o.run(u.id,-1,0,0);s.run(Number(d.lastInsertRowid),c)}}function _h(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(Yl(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(r)?n.get(e.fileName):null}return t(e)}function Ah(e){let t=new Set,n=[];for(let i of e){let r=$h(i);t.has(r)||(t.add(r),n.push(i))}return n}function $h(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function gO(e,t){let n=SO(e,[...new Set(t.map(c=>c.sourceFile))]),i=e.prepare(`
|
|
779
832
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
780
833
|
VALUES (?, ?, ?, ?, X'00')
|
|
781
|
-
`),
|
|
834
|
+
`),r=e.prepare(`
|
|
782
835
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
783
836
|
VALUES (?, ?, 0)
|
|
784
|
-
`),o=new Set,s=0,a=0;for(let c of t){let l
|
|
785
|
-
`)}function
|
|
837
|
+
`),o=new Set,s=0,a=0;for(let c of t){let l=$h(c);if(o.has(l))continue;o.add(l);let u=n.get(c.sourceFile);if(!u)continue;let d=i.run(u,a++,c.sourceLine,c.sourceLine),m=r.run(Number(d.lastInsertRowid),c.symbolId);s+=Number(m.changes)}return s}function*Mh(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 Oh(e,t){for(let[n]of e.toGeneratedLocation(t,i=>!!i.navigation))return n;return null}function Yl(e,t){let n=e;for(let[i]of n.toSourceLocation(t,r=>!!r.navigation))return i;return null}function hO(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 jh(e,t){return Jn(e,t).startsWith("node_modules/")}function Jn(e,t){return rO(e,t).replaceAll("\\","/")}function yO(e){switch(iO(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 Bh(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Xl(t,"utf-8"),i={text:n,lineStarts:bO(n)};return e.set(t,i),i}catch{return e.set(t,null),null}},positionAt:hO}}function bO(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function SO(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 xO(e){try{let t=JSON.parse(Xl(Dh(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 CO(e,t,n,i){let r=Jn(n,i),o=Hh(t.name,t.version,r);return e.get(o)?.id??null}function Hh(e,t,n){let i=n.split("/").map(r=>`\`${r.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${i}/default.`}function Zl(e){cn({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=DO(e.projectRoot,e.tsconfig);if(!RO(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new vO(e.dbPath);try{let i=Ph(n,e.projectRoot),r=LO(IO(e.dbPath),"augment-vue-meta.json"),o=Vh(n,e.projectRoot,e.tsconfig),s=PO(r,o,e.onStatus);if(s)return s;let a=NO({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:i,onStatus:e.onStatus});return FO(r,Vh(n,e.projectRoot,e.tsconfig),a),a}finally{n.close()}}function PO(e,t,n){let i=TO(e,t);return i&&n?.(`Vue references unchanged; reused ${i.resolvedReferences} cached resolved references.`),i}function NO(e){let t=Th(e.db,e.projectRoot,e.vueFiles),n=EO(e,t),i=Ah(n.occurrences),r=Fh(e.db,e.projectRoot,e.vueFiles,t,i),o={vueFiles:e.vueFiles.length,resolvedReferences:i.length,insertedMentions:r,skippedReferences:n.skippedReferences,syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function EO(e,t){if(Rh(e.vueFiles))return kh({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=_O({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return AO({...n,vueFiles:n.context.fileNames.filter(i=>i.endsWith(".vue"))})}function TO(e,t){try{let n=JSON.parse(kO(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function FO(e,t,n){wO(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
|
|
838
|
+
`)}function Vh(e,t,n){let i=e.prepare(`
|
|
786
839
|
SELECT
|
|
787
840
|
(SELECT COUNT(*) FROM documents) AS documents,
|
|
788
841
|
(SELECT COUNT(*) FROM global_symbols) AS symbols,
|
|
@@ -791,40 +844,40 @@ Affected consumer files:`),P.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
|
|
|
791
844
|
(SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
|
|
792
845
|
(SELECT MAX(id) FROM chunks) AS maxChunkId,
|
|
793
846
|
(SELECT MAX(id) FROM global_symbols) AS maxSymbolId
|
|
794
|
-
`).get();return{version:2,tsconfig:n,files:
|
|
795
|
-
Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!
|
|
796
|
-
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
847
|
+
`).get();return{version:2,tsconfig:n,files:Gn(t),db:i}}function _O(e){let t=Bh();return{projectRoot:e.projectRoot,context:Nh(e.projectRoot,e.configPath),symbolLookup:Eh(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function AO(e){let t=[],n=0,i=e.tasks??e.vueFiles.map(r=>({fileName:r,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let r of i){let o=$O(e,r);t.push(...o.occurrences),n+=o.skippedReferences}return{occurrences:t,skippedReferences:n}}function $O(e,t){let n=e.context.language.scripts.get(t.fileName),i=n?.generated?.languagePlugin.typescript?.getServiceScript(n.generated.root)?.code;if(!n||!i)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let r=e.sourceReader.get(t.fileName);if(!r)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let o=e.context.language.maps.get(i,n),s=Jn(e.projectRoot,t.fileName),a=[...Mh(r.text)],c={tokens:a.filter(l=>l.start>=t.startOffset&&l.start<t.endOffset),tokenByStart:new Map(a.map(l=>[l.start,l])),tokenTextCounts:jO(a),processedStarts:new Set};return MO({...e,fileName:t.fileName,sourceInfo:r,sourceFile:s,map:o,tokenContext:c})}function MO(e){let t=[],n=0;for(let i of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(i.start))continue;let r=Oh(e.map,i.start);if(r===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,r+1)??[]).find(c=>!jh(e.projectRoot,c.fileName));if(!s){n++;continue}let a=_h(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}qh(t,e.sourceReader,e.sourceInfo,e.sourceFile,i,a),e.tokenContext.processedStarts.add(i.start),OO(t,e,i,r,a)}return{occurrences:t,skippedReferences:n}}function OO(e,t,n,i,r){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let o of BO(t.context.languageService,t.fileName,i+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(o))continue;let s=t.tokenContext.tokenByStart.get(o);s&&(qh(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,r),t.tokenContext.processedStarts.add(o))}}function qh(e,t,n,i,r,o){let s=t.positionAt(n,r.start);e.push({sourceFile:i,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+r.text.length,symbolId:o})}function jO(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function BO(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 u=HO(i,l.textSpan.start,o,r.text);u!==null&&a.push(u)}return a}function HO(e,t,n,i){let r=n.get(t);if(r?.text===i)return r.start;let o=Yl(e,t);if(o===null)return null;let s=n.get(o);return s?.text===i?s.start:null}async function ln(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:i=console.log,skipAutoInstall:r=!1}=e,o=JO(e),s=Date.now();nu(gt(o.outputScip),{recursive:!0}),nu(gt(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=yj(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects}),l=await lj(Lt(gt(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:i}),u=null;try{let d=KO({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:i});if(d)return d;nj(r,i);let m=QO(o);return u=m.runDir,await XO({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:m,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:r,onStatus:i})}catch(d){throw ey(o.metaPath,ru({trigger:e.trigger,result:"failed",start:s,error:d instanceof Error?d.message:String(d)})),d}finally{u&&no(u,{recursive:!0,force:!0}),l()}}function JO(e){let t=e.outputScip??Lt(e.projectRoot,"index.scip"),n=e.outputDb??Lt(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:Lt(gt(n),"meta.json")}}function KO(e){if(e.opts.skipIfUnchanged===!1||!Gs(e.paths.outputScip)||!Gs(e.paths.outputDb)||!bj(e.paths.metaPath,e.fingerprint))return null;cn({projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let t=Date.now()-e.start,n=ru({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return ey(e.paths.metaPath,n),e.onStatus(`Index unchanged; reused existing SQLite index in ${(t/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:t,reused:!0,skipped:[],lastRefresh:n}}function QO(e){let t=WO(Lt(gt(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:Lt(t,zs(e.outputScip)),tempOutputDb:Lt(t,zs(e.outputDb)),tempMetaPath:Lt(t,zs(e.metaPath))}}async function XO(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:i,reusedLanguages:r}=await YO(e,t);r.length>0&&e.onStatus(`Reused ${r.length} cached language shard(s): ${r.join(", ")}`);let o=ZO(e,t,n,i),s=o.durationMs;return e.onStatus(`Done in ${(s/1e3).toFixed(1)}s`),{languages:n.map(a=>a.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:s,reused:!1,skipped:i,lastRefresh:o}}async function YO(e,t){let n=ej(e),i=new Set(n.map(l=>l.language));for(let l of i)e.onStatus(`Reusing cached ${l} SCIP shard (language inputs unchanged).`);let{preparedRuns:r,skippedLanguages:o}=ij({languages:e.languages.filter(l=>!i.has(l)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,onStatus:e.onStatus}),s=await hh(r,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:a}=oj(s,o),c=[...n,...a];return sj(c,o,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:c,skippedLanguages:o,reusedLanguages:[...i]}}function ZO(e,t,n,i){tj(e.paths.outputDb,n),aj(n,e.tempPaths.tempOutputScip,e.onStatus),cj(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),cn({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus});let r=ru({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(o=>o.language),skipped:[...i]});return Zh(e.tempPaths.tempMetaPath,{version:3,status:i.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,languageFingerprints:Kh(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects}),requestedLanguages:e.languages,indexedLanguages:n.map(o=>o.language),skipped:[...i],lastRefresh:r}),hj({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath}),r}function ej(e){let t;try{t=JSON.parse(Js(e.paths.metaPath,"utf-8"))}catch{return[]}if(t.version!==3||!t.languageFingerprints)return[];let n=[],i=Kh(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects});for(let r of e.languages){let o=Yh(e.paths.outputDb,r);Gs(o)&&Wi(t.languageFingerprints[r])===Wi(i[r])&&n.push({language:r,scipPath:o})}return n}function tj(e,t){for(let n of t){let i=Yh(e,n.language);nu(gt(i),{recursive:!0}),n.scipPath!==i&&UO(n.scipPath,i)}}function nj(e,t){if(!js()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
848
|
+
Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!Yg(t))throw new Error(`The scip CLI is required but could not be installed.
|
|
849
|
+
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function ij(e){let t=[],n=[],i=e.languages.map((r,o)=>({language:r,scipPath:e.languages.length>1?Jh(e.tempOutputScip,r,o):e.tempOutputScip}));for(let{language:r,scipPath:o}of i){let s=rj({...e,language:r,scipPath:o});for(let a of s)"skipped"in a?Gh(n,a.skipped):t.push(a.prepared)}return{preparedRuns:t,skippedLanguages:n}}function rj(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[eu({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=mh(e.projectRoot,e.typescriptProjects);return t.length===0?[eu({...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)=>eu({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Jh(e.tempOutputScip,"typescript-project",i),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function eu(e){let t=zn(e.language),n=qs(t),i=Gl(t,e.projectRoot);if(!i&&!bh(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...`),!Ws(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??Ui(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});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:xh(t,e.env,r)}}}function oj(e,t){let n=new Map;for(let r of e)if(r.skipped)Gh(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)Bl(r.scipPaths,r.outputScipPath),i.push({language:r.language,scipPath:r.outputScipPath});else{let o=r.scipPaths[0];o!==r.outputScipPath&&to(o,r.outputScipPath),i.push({language:r.language,scipPath:r.outputScipPath})}return{indexedOutputs:i}}function Gh(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 sj(e,t,n,i,r){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
|
|
797
850
|
`);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
|
|
798
|
-
`+o)}if(t.length!==0&&(
|
|
851
|
+
`+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.
|
|
799
852
|
`+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
|
|
800
|
-
`))}function
|
|
801
|
-
`),()=>{try{
|
|
802
|
-
`),
|
|
803
|
-
`).map(o=>o.slice(3).trim()).filter(o=>o!==""));return[...new Set(t.batches.flatMap(o=>o.entries.map(s=>s.file)))].filter(o=>
|
|
804
|
-
`),
|
|
805
|
-
`),o=new Set;for(let s of t){let a=
|
|
806
|
-
`)}function
|
|
807
|
-
${
|
|
808
|
-
`).map(s=>s.trim()).filter(s=>/\berror\b/i.test(s));return
|
|
809
|
-
`)}function
|
|
810
|
-
`);
|
|
811
|
-
`);
|
|
853
|
+
`))}function aj(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),Bl(e.map(i=>i.scipPath),t)):e[0].scipPath!==t&&to(e[0].scipPath,t)}function cj(e,t,n,i){if(i("Converting to SQLite..."),!Gs(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let r=dh(e);r.removedDefinitionOccurrences>0&&i(`Sanitized ${r.removedDefinitionOccurrences} invalid definition occurrences across ${r.touchedDocuments} documents before SQLite conversion.`);let o=js();if(!o)throw new Error("scip CLI is not available");VO(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Failed to convert SCIP index to SQLite: ${o}`,{cause:r})}}function Jh(e,t,n){let i=GO(e)||".scip",r=zs(e,i);return Lt(gt(e),`${r}.${n+1}.${t}${i}`)}async function lj(e,t){for(let n=0;n<2;n++){let i=uj(e,t);if(i)return i;let r=dj(e);if(r&&mj(t.trigger,r)){t.onStatus(`Manual reindex preempting watcher refresh started at ${r.startedAt}.`),await fj(r.pid),no(e,{force:!0});continue}if(r&&!iu(r.pid)){no(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${gt(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${gt(e)}.`)}function uj(e,t){let n;try{n=zO(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 zh(n,JSON.stringify(i)+`
|
|
854
|
+
`),()=>{try{qO(n)}finally{no(e,{force:!0})}}}function dj(e){try{let t=JSON.parse(Js(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:gt(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function mj(e,t){return e?.kind==="manual-cli"&&pj(t?.trigger)}function pj(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function fj(e){Uh(e,"SIGTERM"),!await Wh(e,2e3)&&(Uh(e,"SIGKILL"),await Wh(e,1e3))}function Uh(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function Wh(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!iu(e))return!0;await gj(50)}return!iu(e)}function iu(e){try{return process.kill(e,0),!0}catch{return!1}}function gj(e){return new Promise(t=>setTimeout(t,e))}function hj(e){tu(e.tempOutputScip,e.outputScip),tu(e.tempOutputDb,e.outputDb),tu(e.tempMetaPath,e.metaPath)}function tu(e,t){no(`${t}.tmp-replace`,{force:!0}),to(e,`${t}.tmp-replace`),to(`${t}.tmp-replace`,t)}function yj(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:Xh(n),typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Qh(n.typescriptProjects),files:Gn(e)}}function Kh(e,t,n){return Object.fromEntries(t.map(i=>{let r=zn(i).markerFiles,o=i==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Qh(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]};return[i,{version:2,languages:[i],pnpmWorkspaces:i==="typescript"&&Xh(n),...o,files:Gn(e,{language:i,markerFiles:r})}]}))}function Qh(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function Xh(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Yh(e,t){return Lt(gt(e),"language-indexes",`${t}.scip`)}function bj(e,t){try{let n=JSON.parse(Js(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&Wi(n.fingerprint)===Wi(t)&&Wi([...n.indexedLanguages??[]].sort())===Wi(t.languages)}catch{return!1}}function Zh(e,t){let n=`${e}.tmp-${process.pid}-${Date.now()}`;zh(n,`${JSON.stringify(t,null,2)}
|
|
855
|
+
`),to(n,e)}function ey(e,t){try{let n=JSON.parse(Js(e,"utf-8"));if(n.version!==2&&n.version!==3)return;Zh(e,{...n,lastRefresh:t})}catch{}}function ru(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 Wi(e){return JSON.stringify(e)}import{existsSync as ty,readFileSync as Sj}from"fs";function Kn(e,t,n){let i=new Date().toISOString();if(!ty(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!ty(n.metaPath))return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let r=JSON.parse(Sj(n.metaPath,"utf-8")),o=t.languages??Ot(e),s=xj(e,o,t),a=Array.isArray(r.indexedLanguages)?[...r.indexedLanguages].sort():[],c=(r.version===2||r.version===3)&&r.status==="complete"&&JSON.stringify(r.fingerprint)===JSON.stringify(s)&&JSON.stringify(a)===JSON.stringify(s.languages);return{state:c?"fresh":"stale",checkedAt:i,metaPath:n.metaPath,updatedAt:r.updatedAt,lastRefresh:r.lastRefresh,reason:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:c?void 0:"Run: scip-query reindex"}}catch(r){return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${r instanceof Error?r.message:String(r)}`,remedy:"Run: scip-query reindex"}}}function xj(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:n.indexer?.typescript?.projectMode!=="workspace"&&n.indexer?.typescript?.pnpmWorkspaces===!0,typescriptProjectMode:n.indexer?.typescript?.projectMode??"single",typescriptProjects:Cj(n.indexer?.typescript?.projects),files:Gn(e)}}function Cj(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}import{execFileSync as Hj}from"child_process";import{createRequire as vj}from"module";var Rj=vj(import.meta.url);function ny(e,t=[]){let n=kj(),i=Ja(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 kj(){try{return Rj.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as zi,spawnSync as sy}from"child_process";import{existsSync as jt,mkdtempSync as ay,readFileSync as wj,readdirSync as Ij,rmSync as cy,symlinkSync as Lj,writeFileSync as Dj}from"fs";import{tmpdir as ly}from"os";import{join as ot}from"path";var Pj=3e5,Nj=12;function ou(e,t,n={}){let i=su(e);if(i.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],batches:[]};let r=Ej(t,i),o=n.timeoutMs??Pj,s=_j(e,t),a=ay(ot(ly(),"scip-cleanup-verify-")),c=[],l=new Set;try{zi("git",["-C",e,"worktree","add","--detach","--force",a,"HEAD"],{stdio:"ignore"}),Aj(e,a);for(let u of i)for(let d of oy(u,a,o).errorKeys)l.add(d);for(let u of t.batches){dy(a,u);let d=[];for(let m of i){let p=oy(m,a,o);d.push(...p.rawErrors.filter(f=>!l.has(uy(f))))}if(d.length===0)c.push({depth:u.depth,status:"verified"});else{c.push({depth:u.depth,status:"failed",errors:d.slice(0,Nj)});break}}}finally{try{zi("git",["-C",e,"worktree","remove","--force",a],{stdio:"ignore"})}catch{cy(a,{recursive:!0,force:!0})}}return{checkers:i.map(u=>u.label),uncoveredFiles:r,baselineErrors:l.size,dirtyOverlap:s,batches:c}}function Ej(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 uy(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var iy=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"];function su(e){let t=[];if(jt(ot(e,"tsconfig.json"))){let n=ot(e,"node_modules",".bin","tsc");t.push(jt(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:iy}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:iy})}if(jt(ot(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"]}),["pyproject.toml","setup.py","requirements.txt"].some(n=>jt(ot(e,n)))){let n=Tj();n&&t.push(n)}for(let n of Fj(e))t.push({label:`cargo check --quiet --manifest-path ${n}`,binary:"cargo",args:["check","--quiet","--manifest-path",n],coversExtensions:[".rs"],env:{...process.env,CARGO_TARGET_DIR:ot(e,n,"..","target")}});return t}function Tj(){return ry("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--select","E9,F821,F822","."],coversExtensions:[".py"]}:ry("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"]}:null}function ry(e){try{return sy(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}function Fj(e){let t=[];if(jt(ot(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=Ij(e)}catch{return t}for(let i of n)i==="node_modules"||i.startsWith(".")||jt(ot(e,i,"Cargo.toml"))&&t.push(`${i}/Cargo.toml`);return t}function _j(e,t){let n;try{n=zi("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}let i=new Set(n.split(`
|
|
856
|
+
`).map(o=>o.slice(3).trim()).filter(o=>o!==""));return[...new Set(t.batches.flatMap(o=>o.entries.map(s=>s.file)))].filter(o=>i.has(o)).sort()}function Aj(e,t){for(let n of["node_modules"]){let i=ot(e,n),r=ot(t,n);if(jt(i)&&!jt(r))try{Lj(i,r,"junction")}catch{}}}function dy(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=ot(e,i);jt(o)&&Dj(o,$j(wj(o,"utf-8"),r,{rust:i.endsWith(".rs")}))}}function au(e,t){for(let n of t)dy(e,n)}function my(e,t){let n=ay(ot(ly(),"scip-cleanup-patch-"));try{return zi("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),au(n,t),zi("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{zi("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{cy(n,{recursive:!0,force:!0})}}}function cu(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 lu(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 compiler-verified.`);return i}function $j(e,t,n={}){let i=e.split(`
|
|
857
|
+
`),r=(n.rust===!0?Mj(e):Cn(e)).split(`
|
|
858
|
+
`),o=new Set;for(let s of t){let a=Oj(i,s.start),c=Bj(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(`
|
|
859
|
+
`)}function Mj(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 Oj(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 jj=200;function Bj(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>jj)break}return n}function oy(e,t,n){let i=sy(e.binary,e.args,{cwd:t,encoding:"utf-8",timeout:n,env:e.env??process.env,maxBuffer:33554432});if(i.status===0)return{ok:!0,rawErrors:[],errorKeys:new Set};let o=`${i.stdout??""}
|
|
860
|
+
${i.stderr??""}`.split(`
|
|
861
|
+
`).map(s=>s.trim()).filter(s=>/\berror\b/i.test(s));return i.error&&o.length===0&&o.push(String(i.error)),{ok:!1,rawErrors:o,errorKeys:new Set(o.map(uy))}}var py={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"]},Vj={typescript:{status:"available",reason:"AST/source fallback covers TypeScript imports, references, and source-backed evidence."},javascript:{status:"available",reason:"AST/source fallback covers JavaScript, JSX, and Vue script evidence."},java:{status:"available",reason:"AST-dispatched source fallback covers Java imports."},scala:{status:"available",reason:"AST-dispatched source fallback covers Scala imports."},kotlin:{status:"available",reason:"AST-dispatched source fallback covers Kotlin imports."},rust:{status:"available",reason:"AST/source fallback covers Rust imports and exports."},python:{status:"available",reason:"AST/source fallback covers Python imports."},ruby:{status:"available",reason:"AST/source fallback covers Ruby imports."},go:{status:"unavailable",reason:"No Go source-fallback adapter is registered; Go relies on SCIP graph facts."},cpp:{status:"available",reason:"AST/source fallback covers C++ includes."},c:{status:"available",reason:"AST/source fallback covers C includes."},csharp:{status:"available",reason:"AST-dispatched source fallback covers C# imports."},vb:{status:"available",reason:"AST-dispatched source fallback covers Visual Basic imports."},dart:{status:"partial",reason:"Dart source fallback is regex-only for imports and exports."},php:{status:"available",reason:"AST/source fallback covers PHP imports."}};function Dt(e,t){let n=t.languages??Ot(e),i=n.map(s=>{let a=Us(zn(s),e);return{...a,language:s,resolvedBinary:a.resolvedBinary??void 0}}),r=n.includes("typescript")?{language:"typescript",...ny(e,t.semantic?.typescript?.tsconfigs)}:void 0,o=su(e).map(s=>({label:s.label,coversExtensions:s.coversExtensions}));return{languages:n,indexers:i,semantic:r,checkers:o,gitAvailable:zj(e)}}function Qn(e){let t=e.indexers.filter(r=>r.runnable).length,n=e.languages.length===0||t===0?"unavailable":t===e.indexers.length?"available":"partial",i=e.semantic?e.semantic.available?"available":"partial":"unavailable";return{languages:e.languages,matrix:e.languages.map(r=>qj(e,r)),capabilities:[{id:"indexing",label:"SCIP indexing",status:n,evidence:"graph-fact",reason:n==="available"?"All detected/configured language indexers are runnable.":`${t}/${e.indexers.length} detected/configured language indexers are runnable.`},{id:"semantic-typescript",label:"TypeScript semantic provider",status:i,evidence:"semantic",reason:e.semantic?e.semantic.available?"ts-morph can load the configured TypeScript project.":e.semantic.reason??"TypeScript semantic checks will fall back to SCIP/source evidence.":"TypeScript is not detected/configured for this project."},{id:"heuristic-detectors",label:"Heuristic cleanup detectors",status:n==="unavailable"?"unavailable":"available",evidence:"heuristic",reason:n==="unavailable"?"Heuristic detectors need an indexed code graph.":"Similarity, migration, wrapper, stale-abstraction, and doc-drift detectors can run over the index."},{id:"cleanup-verification",label:"Compiler cleanup verification",status:e.checkers.length>0?"available":"unavailable",evidence:"compiler",reason:e.checkers.length>0?e.checkers.map(r=>r.label).join(", "):"No project checker was detected for cleanup-plan --verify."},{id:"diff-gate",label:"Git diff gate",status:e.gitAvailable&&n!=="unavailable"?"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 qj(e,t){let n=e.indexers.find(a=>a.language===t),i=n?.runnable?"available":"unavailable",r=Vj[t],o=t==="typescript"?Uj(e):{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:`No semantic provider is registered for ${t}; commands use graph and source evidence instead.`},s=Wj(e,t);return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:i,evidence:"graph-fact",reason:n?.runnable?`${n.binaryLabel} is runnable${n.resolvedBinary?` at ${n.resolvedBinary}`:""}.`:n?.note??`${t} indexing is not runnable in this project.`},sourceFacts:{id:"source-facts",label:"Source fallback",status:i==="unavailable"?"unavailable":r.status,evidence:"heuristic",reason:i==="unavailable"?"Source fallback needs indexed documents before it can attach evidence.":r.reason},semantic:o,detectors:{id:"detectors",label:"Cleanup detectors",status:i==="unavailable"?"unavailable":"available",evidence:"heuristic",reason:i==="unavailable"?"Cleanup detectors need an indexed graph for this language.":"Graph-backed cleanup detectors can analyze this language; source and semantic precision depends on the rows above."},cleanupVerification:{id:"cleanup-verification",label:"Cleanup verification",status:s.length>0?"available":"unavailable",evidence:"compiler",reason:s.length>0?s.map(a=>a.label).join(", "):`No detected checker covers ${py[t].join(", ")} files.`}}}function Uj(e){return e.semantic?{id:"semantic",label:"Semantic provider",status:e.semantic.available?"available":"partial",evidence:"semantic",reason:e.semantic.available?"ts-morph can load the configured TypeScript project.":e.semantic.reason??"TypeScript semantic checks fall back to SCIP/source evidence."}:{id:"semantic",label:"Semantic provider",status:"unavailable",evidence:"semantic",reason:"TypeScript is not detected/configured for this project."}}function Wj(e,t){let n=new Set(py[t]);return e.checkers.filter(i=>i.coversExtensions.some(r=>n.has(r)))}function zj(e){try{return Hj("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{chmodSync as Gj,existsSync as Ks,readFileSync as Qs,writeFileSync as hy}from"fs";import{join as ro}from"path";var io="<!-- scip-query:agent-setup:begin -->",uu="<!-- scip-query:agent-setup:end -->",fy="# scip-query:agent-setup";function oo(){if(process.stdin.isTTY)return"";try{return Qs(0,"utf-8")}catch{return""}}function Xs(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function so(e){let t=e.rootCauseGroups?.length??e.findings.length,n=[`scip-query diff-gate found ${e.findings.length} issue(s) in ${t} root-cause group(s) in this diff \u2014 fix or knowingly accept them before finishing:`],i=e.rootCauseGroups?.filter(r=>r.count>1)??[];for(let r of i)n.push(`- group [${r.check}] ${r.count} finding(s): ${r.message}`),n.push(` -> ${r.remediation}`);for(let r of e.findings)n.push(`- [${r.check}] ${r.message}`),n.push(` -> ${r.remediation}`);return n.join(`
|
|
862
|
+
`)}function Ys(e,t={}){let n={written:[],unchanged:[],skipped:[]};return Jj(e,n),t.gitHook&&Kj(e,n),n}function Jj(e,t){let n=[io,"## scip-query","","This repo is indexed by scip-query (compiler-resolved code intelligence).","","- Unsure how to explore, plan, verify, or clean up here: invoke the `scip-query` skill \u2014 it routes to the right specialist skill.","- For non-trivial implementation requests: plan first (`concrete-plan` skill, anchored by `scip-query plan-context <target>`), then implement.","- After the change, run the check matching what you did: extracted a helper -> `scip-query incomplete-migration`; new helper -> `scip-query recent-duplicates`; new params -> `scip-query unused-params`; new wrapper -> `scip-query wrapper-candidates`; schema/config change -> `scip-query co-change <file>`; deleted code -> `scip-query cleanup-plan --verify`.","- Before declaring the work done: `scip-query reindex && scip-query diff-gate` \u2014 fix findings or state why each is accepted.",uu].join(`
|
|
863
|
+
`);gy(e,"AGENTS.md",n,t);let i=Ks(ro(e,"CLAUDE.md"))?Qs(ro(e,"CLAUDE.md"),"utf-8"):"";if(i.includes("@AGENTS.md")&&!i.includes(io)){t.unchanged.push("CLAUDE.md");return}let r=[io,"@AGENTS.md",uu].join(`
|
|
864
|
+
`);gy(e,"CLAUDE.md",r,t)}function gy(e,t,n,i){let r=ro(e,t),o=Ks(r)?Qs(r,"utf-8"):"",s;if(o.includes(io)){let a=new RegExp(`${io}[\\s\\S]*?${uu}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
|
|
812
865
|
|
|
813
866
|
`)}${n}
|
|
814
867
|
`:`${n}
|
|
815
|
-
`;s===o?
|
|
816
|
-
`);if(
|
|
817
|
-
`),e.result[
|
|
818
|
-
`),e.result.removed.push(e.label)}function
|
|
868
|
+
`;s===o?i.unchanged.push(t):(hy(r,s),i.written.push(t))}function Kj(e,t){let n=ro(e,".git","hooks");if(!Ks(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let i=ro(n,"pre-commit"),r=["#!/bin/sh",fy,"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(`
|
|
869
|
+
`);if(Ks(i)){let o=Qs(i,"utf-8");if(o.includes(fy)){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}}hy(i,r),Gj(i,493),t.written.push(".git/hooks/pre-commit")}var xy="SCIP_QUERY_SKIP_HOOK_INSTALL",du="SCIP_QUERY_STOP_HOOK_MODE",tB="scip-query hook-",nB="scip-query diff-gate --hook";function Zs(e,t={}){let n=Cy(),i=t.env??process.env;return rB(i)?(n.skipped.push({target:"project agent hooks",reason:`${xy}=1`}),n):(yy({provider:"codex",rootDir:Gi(e,".codex"),configPath:Gi(e,".codex","hooks.json"),label:".codex/hooks.json",createRoot:!0,result:n}),yy({provider:"claude",rootDir:Gi(e,".claude"),configPath:Gi(e,".claude","settings.json"),label:".claude/settings.json",createRoot:!0,result:n}),t.removeLegacyUserHooks!==!1&&iB({homeDir:t.homeDir,result:n}),n)}function iB(e={}){let t=e.result??Cy(),n=e.homeDir??Zj();return by({configPath:Gi(n,".codex","hooks.json"),label:"Codex/hooks.json",result:t}),by({configPath:Gi(n,".claude","settings.json"),label:"Claude/settings.json",result:t}),t}function Cy(){return{installed:[],updated:[],unchanged:[],removed:[],skipped:[]}}function rB(e=process.env){let t=e[xy];return t==="1"||t?.toLowerCase()==="true"||t?.toLowerCase()==="yes"}function oB(e=process.env){let t=e[du]?.toLowerCase();return t==="block"||t==="blocking"||t==="1"||t==="true"||t==="yes"?"block":t==="feedback"||t==="continue"?"feedback":"warn"}function yy(e){if(!e.createRoot&&!ao(e.rootDir))return;let t=vy(e.configPath,e.label,e.result);if(!t)return;let n=sB(t,e.provider);if(JSON.stringify(n)===JSON.stringify(t)){e.result.unchanged.push(e.label);return}let i=ao(e.configPath);Xj(eB(e.configPath),{recursive:!0}),Sy(e.configPath,`${JSON.stringify(n,null,2)}
|
|
870
|
+
`),e.result[i?"updated":"installed"].push(e.label)}function by(e){if(!ao(e.configPath))return;let t=vy(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","Stop"]){let a=Array.isArray(n[s])?n[s]:[],c=Ry(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,Sy(e.configPath,`${JSON.stringify(o,null,2)}
|
|
871
|
+
`),e.result.removed.push(e.label)}function vy(e,t,n){if(!ao(e))return{};try{let i=JSON.parse(Yj(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 sB(e,t){let n=e.hooks&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{},i={...e,hooks:{...n}};for(let r of["SessionStart","UserPromptSubmit","Stop"]){let o=Array.isArray(n[r])?n[r]:[];i.hooks[r]=[...Ry(o),cB(t,r)]}return i}function Ry(e){return e.map(t=>({...t,hooks:Array.isArray(t.hooks)?t.hooks.filter(n=>!aB(n)):[]})).filter(t=>t.hooks.length>0)}function aB(e){if(!e||typeof e!="object")return!1;let t=e.command;return typeof t=="string"&&(t.startsWith(tB)||t===nB)}function cB(e,t){return t==="SessionStart"?{matcher:"startup|resume|clear|compact",hooks:[{type:"command",command:"scip-query hook-context",timeout:60,statusMessage:"Refreshing scip-query context"}]}:t==="UserPromptSubmit"?{hooks:[{type:"command",command:"scip-query hook-context",timeout:60,statusMessage:"Checking scip-query freshness"}]}:{hooks:[{type:"command",command:"scip-query hook-stop",timeout:30,statusMessage:"Running scip-query diff gate"}]}}async function ky(){let e=await dB(oo());e&&console.log(JSON.stringify(e))}function wy(){let e=oo();if(Xs(e))return;let t=Iy(e),n=Ly(t);!n||!ao(n.paths.dbPath)||yB(n,i=>{let r=Vr(i,{minTogether:6,skip:[]});r.findings.length!==0&&console.log(JSON.stringify(lB(r,oB())))})}function lB(e,t="warn"){let n=so(e),i=uB(e);return t==="block"?{decision:"block",reason:n}:t==="feedback"?{hookSpecificOutput:{hookEventName:"Stop",additionalContext:`${i}
|
|
819
872
|
|
|
820
|
-
This is non-error Stop hook feedback. Fix true findings, or explain why a finding is intentionally accepted before finishing.`}}:{systemMessage:`${
|
|
873
|
+
This is non-error Stop hook feedback. Fix true findings, or explain why a finding is intentionally accepted before finishing.`}}:{systemMessage:`${i}
|
|
821
874
|
|
|
822
|
-
Stop hook allowed this turn to finish. Review these findings when relevant. Set ${
|
|
823
|
-
`);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}async function
|
|
824
|
-
`)}function
|
|
825
|
-
`)}function
|
|
826
|
-
`,t),t}catch(
|
|
827
|
-
`)}`}function eO(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 tO(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 nO(e){return e.indexerRemediation.length===0?["All detected indexers were already runnable."]:e.indexerRemediation.map(t=>{let n=t.after.runnable?"READY":"BLOCKED",r=t.attempted?"install attempted":"no automatic install attempted";return`- ${n} ${t.language}: ${t.binaryLabel} (${r})`})}function rO(e){return e.health.score===null?`unavailable (${e.health.unavailableReason??"not checked"})`:`${e.health.score} (risk ${e.health.riskScore}, hygiene ${e.health.hygieneScore})`}function iO(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function Wh(e,t,n){if(Kj(Yj(e),{recursive:!0}),(Jj(e)?Xj(e,"utf-8"):null)===t){n.unchanged.push(e);return}Qj(e,t),n.written.push(e)}async function Qh(e={}){let t=[],{projectRoot:n,config:r,paths:i,dbPath:o}=Pr(),s=Ai();X(t,{id:"scip-cli",label:"scip CLI",status:s?"ok":"warn",message:s?"scip CLI is available.":"scip CLI is not available; reindex may attempt install."});let a=js({quiet:!0});X(t,{id:"skills",label:"Agent skills",status:a.skipped.length>0?"warn":"ok",message:`${a.installed.length} installed, ${a.alreadyLinked.length} already linked, ${a.skipped.length} skipped.`,details:a.skipped.map(L=>`Skipped ${L}`)});let c=Ir(r,{projectRoot:n}),l=c.filter(L=>L.level==="error");X(t,{id:"config",label:"Project config",status:l.length>0?"failed":c.length>0?"warn":"ok",message:c.length===0?"Config OK.":`${c.length} diagnostic(s), ${l.length} error(s).`,details:c.map(L=>`${L.level.toUpperCase()} ${L.path}: ${L.message}`)});let u=Dr(r);X(t,{id:"watch-refresh",label:"Watch refresh policy",status:u.autoRefresh===!1?"skipped":"ok",message:u.autoRefresh===!1?"Project hooks report freshness but do not auto-refresh stale indexes.":`Project hooks auto-refresh stale indexes; live watch defaults are ${u.debounceMs}ms debounce, ${u.cooldownMs}ms cooldown, and ${u.gitPollMs}ms Git polling.`});let d=Ct(n,r);X(t,{id:"readiness",label:"Indexer readiness",status:d.languages.length===0?"failed":d.indexers.some(L=>!L.runnable)?"warn":"ok",message:d.languages.length===0?"No supported project languages detected.":`Detected languages: ${d.languages.join(", ")}`,details:d.indexers.map(L=>`${L.runnable?"OK":L.installed?"WARN":"MISSING"} ${L.language}: ${L.binaryLabel}${L.note?` - ${L.note}`:""}`)});let m=fO(n,d,t),f=Ct(n,r),h=null;if(f.languages.length===0||l.length>0)X(t,{id:"reindex",label:"Index refresh",status:"skipped",message:f.languages.length===0?"Skipped because no supported languages were detected.":"Skipped because config validation has errors."});else{let L=[];try{h=await tn({projectRoot:n,languages:f.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:r.indexerConcurrency,trigger:{kind:"setup",detail:"scip-query setup"},onStatus:G=>L.push(G)}),X(t,{id:"reindex",label:"Index refresh",status:h.skipped.length>0?"warn":"ok",message:`${h.reused?"Reused":"Indexed"} ${h.languages.join(", ")} in ${(h.durationMs/1e3).toFixed(1)}s.`,details:[...L,...h.skipped.map(G=>`Skipped ${G.language}: ${G.reason}`)]})}catch(G){X(t,{id:"reindex",label:"Index refresh",status:"failed",message:Bs(G),details:L})}}let g=Ct(n,r),y=Bn(g),S=On(n,r,i);X(t,{id:"capabilities",label:"Capability matrix",status:SO(y),message:xO(y)});let C=await hO(i.dbPath,t),k=null;try{k=Ms(n),X(t,{id:"project-hooks",label:"Project agent hooks",status:k.skipped.length>0?"warn":"ok",message:`${k.installed.length} installed, ${k.updated.length} updated, ${k.unchanged.length} already configured, ${k.removed.length} legacy user hook config(s) cleaned up, ${k.skipped.length} skipped.`,details:[...k.removed.map(L=>`Removed legacy user-level ${L}`),...k.skipped.map(L=>`Skipped ${L.target}: ${L.reason}`)]})}catch(L){X(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:Bs(L)})}let D=null;try{D=As(n,{gitHook:e.gitHook}),X(t,{id:"agent-guidance",label:"Project agent guidance",status:D.skipped.length>0?"warn":"ok",message:`${D.written.length} written, ${D.unchanged.length} already wired, ${D.skipped.length} skipped.`,details:D.skipped.map(L=>`Skipped ${L.target}: ${L.reason}`)})}catch(L){X(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:Bs(L)})}let x=sO({reindexResult:h,readiness:g,capabilities:y,freshness:S,health:C,hooksResult:k,agentResult:D,steps:t});X(t,{id:"smoke-tests",label:"Setup smoke tests",status:aO(x),message:cO(x),details:x.map(L=>`${L.command}: ${L.status} - ${L.evidence}`)});let I={projectRoot:n,dbPath:o,configuredDbPath:i.dbPath,scipCliInstalled:s,languages:g.languages,steps:t,skills:a,initialReadiness:d,indexerRemediation:m,readiness:g,capabilities:y,freshness:S,reindex:h,health:C,smokeTests:x,healthDossier:null,hooks:k,setupAgent:D,filesWritten:D?.written??[],verdict:Xh(t,g)},M=Gh(I);return I.healthDossier=M,I.filesWritten=[...I.filesWritten,...M.written],X(t,{id:"health-dossier",label:"Health dossier",status:M.status==="failed"?"failed":"ok",message:M.status==="failed"?M.error:`${M.written.length} written, ${M.unchanged.length} unchanged.`,details:[M.markdownPath,M.jsonPath]}),I.verdict=Xh(t,g),I}function Yh(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${CO(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("Setup steps:");for(let t of e.steps)console.log(` ${t.status.toUpperCase()} ${t.label}${t.message?` - ${t.message}`:""}`);console.log(""),console.log("Smoke tests:");for(let t of e.smokeTests)console.log(` ${t.status.toUpperCase()} ${t.command} - ${t.evidence}`);if(e.indexerRemediation.length>0){console.log(""),console.log("Indexer remediation:");for(let t of e.indexerRemediation){let n=t.after.runnable?"ready":"blocked",r=t.attempted?"attempted install":"manual action required";console.log(` - ${t.language}: ${n} (${r})`),t.recovery&&console.log(` ${t.recovery}`)}}}function sO(e){let t=e.steps.find(o=>o.id==="reindex"),n=e.steps.find(o=>o.id==="project-hooks"),r=e.steps.find(o=>o.id==="agent-guidance"),i=e.steps.find(o=>o.id==="watch-refresh");return[{id:"reindex",command:"scip-query reindex",status:e.reindexResult?"pass":t?.status==="failed"?"fail":"unavailable",evidence:e.reindexResult?`${e.reindexResult.languages.join(", ")} indexed${e.reindexResult.reused?" from cache":""}.`:t?.message??"No reindex result was produced."},{id:"status",command:"scip-query status",status:e.freshness.state==="missing"?"fail":"pass",evidence:`Index freshness is ${e.freshness.state}: ${e.freshness.reason}`},{id:"config-validate",command:"scip-query config-validate",status:lO(e.steps),evidence:uO(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?dO(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:zh(e.readiness,e.freshness),evidence:Jh(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:zh(e.readiness,e.freshness),evidence:Jh(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:mO(e.capabilities),evidence:pO(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:`printf %s '{"hook_event_name":"SessionStart"}' | scip-query hook-context`,status:i?.status==="ok"?"pass":"unavailable",evidence:i?.message??"Watch refresh policy was not evaluated."},{id:"setup-agent",command:"scip-query setup-agent",status:e.agentResult?"pass":r?.status==="failed"?"fail":"unavailable",evidence:e.agentResult?`${e.agentResult.written.length} written, ${e.agentResult.unchanged.length} already wired, ${e.agentResult.skipped.length} skipped.`:r?.message??"Project agent guidance was not written."}]}function aO(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function cO(e){let t=e.filter(i=>i.status==="pass").length,n=e.filter(i=>i.status==="unavailable").length,r=e.filter(i=>i.status==="fail").length;return`${t} passed, ${n} unavailable, ${r} failed.`}function lO(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function uO(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function dO(e){let t=e.matrix.filter(n=>[n.indexing,n.sourceFacts,n.semantic,n.cleanupVerification].some(r=>r.status==="unavailable")).length;return`${e.matrix.length} language row(s), ${t} with unavailable capability cells.`}function zh(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function Jh(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 mO(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function pO(e){if(e.matrix.length===0)return"No detected languages produced capability rows.";let t=e.matrix.filter(i=>i.cleanupVerification.status==="available").length,n=e.matrix.filter(i=>i.cleanupVerification.status==="partial").length,r=e.matrix.filter(i=>i.cleanupVerification.status==="unavailable").length;return`${t} available, ${n} partial, ${r} unavailable cleanup-verification row(s).`}function fO(e,t,n){let r=[];if(t.languages.length===0)return X(n,{id:"indexer-remediation",label:"Indexer remediation",status:"skipped",message:"Skipped because no supported languages were detected."}),r;for(let s of t.indexers){if(s.runnable)continue;let a=An(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,u=!1;l?u=Ps(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 d=gO(Ds(a,e));r.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:u,before:s,after:d,messages:c,recovery:d.runnable?void 0:d.note??d.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(r.length===0)return X(n,{id:"indexer-remediation",label:"Indexer remediation",status:"ok",message:"All detected indexers are runnable."}),r;let i=r.filter(s=>!s.after.runnable),o=r.filter(s=>s.attempted);return X(n,{id:"indexer-remediation",label:"Indexer remediation",status:i.length>0?"warn":"ok",message:i.length===0?`${o.length} install attempt(s); all detected indexers are runnable.`:`${o.length} install attempt(s); ${i.length} indexer(s) still blocked.`,details:r.flatMap(s=>[`${s.language}: ${s.after.runnable?"ready":"blocked"}`,...s.messages])}),r}function gO(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function hO(e,t){if(!oO(e)){let n="Skipped because no SQLite index database exists yet.";return X(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Kh(n)}try{let n=await xs({full:!0,json:!0});return X(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),yO(n)}catch(n){let r=Bs(n);return X(t,{id:"health",label:"Health audit",status:"failed",message:r}),Kh(r)}}function yO(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(bO),warnings:e.warnings??[]}}function bO(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-health-audit to confirm this signal; use scip-health-improve when the user wants confirmed issues fixed autonomously."}}function Kh(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function Xh(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 SO(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 xO(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 CO(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function X(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function Bs(e){return e instanceof Error?e.message:String(e)}import{existsSync as vO,mkdirSync as RO,writeFileSync as kO}from"fs";import{dirname as wO,join as LO}from"path";function Zh(e,t={}){let n=LO(e,".github","workflows","scip-query.yml"),r=IO();return vO(n)&&!t.force?{path:n,written:!1,skipped:!0,content:r,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(RO(wO(n),{recursive:!0}),kO(n,r)),{path:n,written:!t.dryRun,skipped:!1,content:r})}function IO(){return`name: scip-query
|
|
875
|
+
Stop hook allowed this turn to finish. Review these findings when relevant. Set ${du}=feedback to ask the agent to continue without a hook error, or ${du}=block to enforce the gate.`}}function uB(e){return so(e).replace(" \u2014 fix or knowingly accept them before finishing:"," \u2014 review these findings when relevant:")}async function dB(e){let t=Iy(e),n=gB(t);if(n!=="SessionStart"&&n!=="UserPromptSubmit")return;let i=Ly(t);if(!i)return;let r=await mB(i),o=n==="SessionStart"?pB(i.projectRoot,i.config,i.paths):fB(String(t.prompt??"")),s=[r,o].filter(a=>!!a?.trim()).join(`
|
|
876
|
+
`);if(s.trim())return{hookSpecificOutput:{hookEventName:n,additionalContext:s}}}async function mB(e){if(Bi(e.config).autoRefresh===!1)return;let n=Kn(e.projectRoot,e.config,e.paths);if(n.state!=="fresh")try{let i=await ln({projectRoot:e.projectRoot,languages:e.config.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,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:e.config.indexerConcurrency,trigger:{kind:"manual-cli",detail:"agent hook auto-refresh"},onStatus:()=>{}});return`scip-query auto-refresh: ${i.reused?"reused":"indexed"} ${i.languages.join(", ")} because the index was ${n.state}.`}catch(i){let r=i instanceof Error?i.message:String(i);return`scip-query auto-refresh skipped: index is ${n.state}, but refresh failed: ${r}`}}function pB(e,t,n){let i=Kn(e,t,n),r=Dt(e,t),s=Qn(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.","For non-trivial edits, plan with concrete-plan anchored by `scip-query plan-context <target>`, then verify with scip-verify."].filter(c=>c!==void 0).join(`
|
|
877
|
+
`)}function fB(e){let t=e.toLowerCase(),n=[];return Xn(t,["debug","bug","regression","failing","fails","error","wrong"])&&n.push("Debug or bug request: use scip-debug. For issue-quality triage, use scip-triage-issue."),Xn(t,["explain","how does","walk me through","trace","understand"])&&n.push("Exploration request: use scip-explore before answering behavioral questions."),Xn(t,["diagram","visualize","visualise","flow map","architecture map"])&&n.push("Diagram request: use scip-diagram and back every node and edge with scip-query evidence."),Xn(t,["implement","build","change","refactor","fix","add ","update "])&&n.push("Implementation request: plan first with concrete-plan and `scip-query plan-context <target>`, then verify with scip-verify."),Xn(t,["review","maintainability","architecture","boundary"])&&n.push("Review request: use scip-maintainability, scip-api-impact, or scip-verify depending on whether this is architecture, API impact, or post-change verification."),Xn(t,["setup","adopt","install","bootstrap"])&&n.push("Setup request: use scip-adoption or scip-query-setup; keep CI setup out of the default path."),Xn(t,["health","score","dossier","cleanup","dead code","duplicate","debloat","perfect code","as high as","maximize","maximise"])&&n.push("Health or cleanup request: use scip-health-audit before editing; use scip-health-improve when the user wants the score raised as high as reasonably possible."),n.length===0?"":["scip-query routing reminder:",...n].join(`
|
|
878
|
+
`)}function Xn(e,t){return t.some(n=>e.includes(n))}function Iy(e){if(!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function gB(e){let t=e.hook_event_name??e.hookEventName;return typeof t=="string"?t:void 0}function Ly(e){let t=typeof e.cwd=="string"?e.cwd:process.cwd(),n=hB(t);if(n)try{let i=je(n),r=wt(n,i);return{projectRoot:n,config:i,paths:r}}catch{return}}function hB(e){try{return Qj("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function yB(e,t){let n={dbPath:e.paths.dbPath,indexPath:e.paths.indexPath,projectRoot:e.projectRoot,entryRoots:e.config.entryRoots,semantic:e.config.semantic,suppressions:e.config.suppressions,declaredCouplings:e.config.declaredCouplings,locality:e.config.locality},i=new Oi(n,an(e.projectRoot));try{return t(i)}finally{i.close()}}import{existsSync as mu,mkdirSync as bB,symlinkSync as SB,readlinkSync as xB,unlinkSync as CB}from"fs";import{join as co,dirname as Dy,resolve as pu}from"path";import{homedir as fu,platform as vB}from"os";import{fileURLToPath as RB}from"url";var kB=vB()==="win32",gu=["scip-query","scip-query-setup","scip-adoption","scip-health-audit","scip-health-improve","scip-hyper-optimization","scip-api-impact","concrete-plan","scip-ai-cleanup","scip-debug","scip-explore","scip-triage-issue","scip-diagram","scip-debloat","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook"];function ea(e={}){let t=e.quiet?()=>{}:console.log,n=RB(import.meta.url),i=pu(Dy(n),"..","skills"),r=[co(fu(),".claude","skills"),co(fu(),".codex","skills"),co(fu(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[]};for(let s of r){let a=Dy(s);if(!mu(a))continue;bB(s,{recursive:!0});let c=wB(s);for(let l of gu){let u=co(i,l),d=co(s,l);if(!mu(u)){o.skipped.push(`${c}/${l}`);continue}if(mu(d)){try{let m=xB(d);if(pu(m)===pu(u)){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}CB(d)}SB(u,d,kB?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function wB(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{spawnSync as Jy}from"child_process";import{existsSync as Qi,renameSync as zy,rmSync as h1}from"fs";import{dirname as y1,extname as b1}from"path";import{execFileSync as IB,fork as LB}from"child_process";import{statSync as DB,watch as PB}from"fs";import{join as NB,relative as EB}from"path";import TB from"ignore";var ta=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.config=t.config,this.watchConfig=Bi(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.indexerConcurrency=t.config.indexerConcurrency,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=an(t.projectRoot),this.extraIgnore=TB(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let t=PB(this.projectRoot,{recursive:!0},(n,i)=>{i&&!this.stopped&&this.handleFileChange(i)});this.fsWatchers.push(t)}catch{this.onError(new Error("Failed to start file watcher. On Linux, you may need to increase inotify limits: sysctl -w fs.inotify.max_user_watches=524288"))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}handleFileChange(t){let n=EB(this.projectRoot,NB(this.projectRoot,t));n===".git"||n.startsWith(".git/")||this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:n})}scheduleReindex(t){if(this.pendingTrigger=FB(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=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(r),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(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=je(this.projectRoot),s=Object.keys(o).length>0?o:this.config,a=wt(this.projectRoot,s),c=s.indexer?.typescript,l=LB(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_TRIGGER_KIND:t.kind,SCIP_REINDEX_TRIGGER_DETAIL:t.detail??""},stdio:"pipe"});l.on("exit",u=>{u===0?n(Date.now()-r):i(new Error(`Reindex worker exited with code ${u}`))}),l.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=Py(this.projectRoot,["rev-parse","--git-path","index"]);if(!t)return null;let n={head:Py(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=DB(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Py(e,t){try{return IB("git",["-C",e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function FB(e,t){return e?e.kind===t.kind?e.detail===t.detail?e:{kind:e.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${e.kind}, ${t.kind}`}:t}import{existsSync as WB}from"fs";import{existsSync as _B,mkdirSync as AB,readFileSync as $B,writeFileSync as MB}from"fs";import{dirname as OB,join as Ny}from"path";function Ty(e){let t={markdownPath:Ny(e.projectRoot,"docs","scip-query","health-dossier.md"),jsonPath:Ny(e.projectRoot,"docs","scip-query","health-dossier.json"),status:"written",written:[],unchanged:[]},n={...e,healthDossier:t};try{return Ey(t.markdownPath,jB(n),t),Ey(t.jsonPath,`${JSON.stringify(n,null,2)}
|
|
879
|
+
`,t),t}catch(i){return{...t,status:"failed",error:i instanceof Error?i.message:String(i)}}}function jB(e){return`${["# scip-query Health Dossier","",`Generated: ${new Date().toISOString()}`,`Project: ${e.projectRoot}`,`Setup verdict: ${e.verdict}`,`Health score: ${qB(e)}`,"","## Items That Need Attention","",...BB(e),"","## Blocked Or Unavailable Checks","",...HB(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","",...VB(e),"","## JSON","",`Machine-readable report: \`${UB(e)}\``,""].join(`
|
|
880
|
+
`)}`}function BB(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 HB(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 VB(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 qB(e){return e.health.score===null?`unavailable (${e.health.unavailableReason??"not checked"})`:`${e.health.score} (risk ${e.health.riskScore}, hygiene ${e.health.hygieneScore})`}function UB(e){return e.healthDossier?.jsonPath.replace(`${e.projectRoot}/`,"")??"docs/scip-query/health-dossier.json"}function Ey(e,t,n){if(AB(OB(e),{recursive:!0}),(_B(e)?$B(e,"utf-8"):null)===t){n.unchanged.push(e);return}MB(e,t),n.written.push(e)}async function My(e={}){let t=[],{projectRoot:n,config:i,paths:r,dbPath:o}=Hi(),s=eo();te(t,{id:"scip-cli",label:"scip CLI",status:s?"ok":"warn",message:s?"scip CLI is available.":"scip CLI is not available; reindex may attempt install."});let a=ea({quiet:!0});te(t,{id:"skills",label:"Agent skills",status:a.skipped.length>0?"warn":"ok",message:`${a.installed.length} installed, ${a.alreadyLinked.length} already linked, ${a.skipped.length} skipped.`,details:a.skipped.map(w=>`Skipped ${w}`)});let c=ji(i,{projectRoot:n}),l=c.filter(w=>w.level==="error");te(t,{id:"config",label:"Project config",status:l.length>0?"failed":c.length>0?"warn":"ok",message:c.length===0?"Config OK.":`${c.length} diagnostic(s), ${l.length} error(s).`,details:c.map(w=>`${w.level.toUpperCase()} ${w.path}: ${w.message}`)});let u=Bi(i);te(t,{id:"watch-refresh",label:"Watch refresh policy",status:u.autoRefresh===!1?"skipped":"ok",message:u.autoRefresh===!1?"Project hooks report freshness but do not auto-refresh stale indexes.":`Project hooks auto-refresh stale indexes; live watch defaults are ${u.debounceMs}ms debounce, ${u.cooldownMs}ms cooldown, and ${u.gitPollMs}ms Git polling.`});let d=Dt(n,i);te(t,{id:"readiness",label:"Indexer readiness",status:d.languages.length===0?"failed":d.indexers.some(w=>!w.runnable)?"warn":"ok",message:d.languages.length===0?"No supported project languages detected.":`Detected languages: ${d.languages.join(", ")}`,details:d.indexers.map(w=>`${w.runnable?"OK":w.installed?"WARN":"MISSING"} ${w.language}: ${w.binaryLabel}${w.note?` - ${w.note}`:""}`)});let m=e1(n,d,t),p=Dt(n,i),f=null;if(p.languages.length===0||l.length>0)te(t,{id:"reindex",label:"Index refresh",status:"skipped",message:p.languages.length===0?"Skipped because no supported languages were detected.":"Skipped because config validation has errors."});else{let w=[];try{f=await ln({projectRoot:n,languages:p.languages,outputScip:r.indexPath,outputDb:r.dbPath,pnpmWorkspaces:i.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:i.indexer?.typescript?.projectMode,typescriptProjects:i.indexer?.typescript?.projects,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:i.indexerConcurrency,trigger:{kind:"setup",detail:"scip-query setup"},onStatus:j=>w.push(j)}),te(t,{id:"reindex",label:"Index refresh",status:f.skipped.length>0?"warn":"ok",message:`${f.reused?"Reused":"Indexed"} ${f.languages.join(", ")} in ${(f.durationMs/1e3).toFixed(1)}s.`,details:[...w,...f.skipped.map(j=>`Skipped ${j.language}: ${j.reason}`)]})}catch(j){te(t,{id:"reindex",label:"Index refresh",status:"failed",message:na(j),details:w})}}let g=Dt(n,i),y=Qn(g),S=Kn(n,i,r);te(t,{id:"capabilities",label:"Capability matrix",status:o1(y),message:s1(y)});let R=await n1(r.dbPath,t),k=null;try{k=Zs(n),te(t,{id:"project-hooks",label:"Project agent hooks",status:k.skipped.length>0?"warn":"ok",message:`${k.installed.length} installed, ${k.updated.length} updated, ${k.unchanged.length} already configured, ${k.removed.length} legacy user hook config(s) cleaned up, ${k.skipped.length} skipped.`,details:[...k.removed.map(w=>`Removed legacy user-level ${w}`),...k.skipped.map(w=>`Skipped ${w.target}: ${w.reason}`)]})}catch(w){te(t,{id:"project-hooks",label:"Project agent hooks",status:"failed",message:na(w)})}let x=null;try{x=Ys(n,{gitHook:e.gitHook}),te(t,{id:"agent-guidance",label:"Project agent guidance",status:x.skipped.length>0?"warn":"ok",message:`${x.written.length} written, ${x.unchanged.length} already wired, ${x.skipped.length} skipped.`,details:x.skipped.map(w=>`Skipped ${w.target}: ${w.reason}`)})}catch(w){te(t,{id:"agent-guidance",label:"Project agent guidance",status:"failed",message:na(w)})}let b=zB({reindexResult:f,readiness:g,capabilities:y,freshness:S,health:R,hooksResult:k,agentResult:x,steps:t});te(t,{id:"smoke-tests",label:"Setup smoke tests",status:GB(b),message:JB(b),details:b.map(w=>`${w.command}: ${w.status} - ${w.evidence}`)});let C={projectRoot:n,dbPath:o,configuredDbPath:r.dbPath,scipCliInstalled:s,languages:g.languages,steps:t,skills:a,initialReadiness:d,indexerRemediation:m,readiness:g,capabilities:y,freshness:S,reindex:f,health:R,smokeTests:b,healthDossier:null,hooks:k,setupAgent:x,filesWritten:x?.written??[],verdict:$y(t,g)},D=Ty(C);return C.healthDossier=D,C.filesWritten=[...C.filesWritten,...D.written],te(t,{id:"health-dossier",label:"Health dossier",status:D.status==="failed"?"failed":"ok",message:D.status==="failed"?D.error:`${D.written.length} written, ${D.unchanged.length} unchanged.`,details:[D.markdownPath,D.jsonPath]}),C.verdict=$y(t,g),C}function Oy(e){if(console.log("scip-query setup"),console.log(`Project: ${e.projectRoot}`),console.log(`Verdict: ${e.verdict}`),console.log(`Health score: ${a1(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("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 zB(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==="missing"?"fail":"pass",evidence:`Index freshness is ${e.freshness.state}: ${e.freshness.reason}`},{id:"config-validate",command:"scip-query config-validate",status:KB(e.steps),evidence:QB(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?XB(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:Fy(e.readiness,e.freshness),evidence:_y(e.readiness,e.freshness)},{id:"diff-gate",command:"scip-query diff-gate --json",status:Fy(e.readiness,e.freshness),evidence:_y(e.readiness,e.freshness)},{id:"cleanup-verification",command:"scip-query cleanup-plan --verify",status:YB(e.capabilities),evidence:ZB(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:`printf %s '{"hook_event_name":"SessionStart"}' | scip-query hook-context`,status:r?.status==="ok"?"pass":"unavailable",evidence:r?.message??"Watch refresh policy was not evaluated."},{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 GB(e){return e.some(t=>t.status==="fail")?"failed":e.some(t=>t.status==="unavailable")?"warn":"ok"}function JB(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 KB(e){return e.find(n=>n.id==="config")?.status==="failed"?"fail":"pass"}function QB(e){return e.find(n=>n.id==="config")?.message??"Config diagnostics were not produced."}function XB(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 Fy(e,t){return e.gitAvailable?t.state==="missing"?"fail":"pass":"unavailable"}function _y(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 YB(e){let t=e.matrix.map(n=>n.cleanupVerification.status);return t.some(n=>n==="available")||t.some(n=>n==="partial")?"pass":"unavailable"}function ZB(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 e1(e,t,n){let i=[];if(t.languages.length===0)return te(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=zn(s.language),c=[],l=!s.installed&&!!a.installMethods?.length,u=!1;l?u=Ws(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 d=t1(Us(a,e));i.push({language:s.language,binaryLabel:s.binaryLabel,attempted:l,installed:u,before:s,after:d,messages:c,recovery:d.runnable?void 0:d.note??d.installUrl??`Install ${s.binaryLabel} and put it on PATH.`})}if(i.length===0)return te(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 te(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 t1(e){return{...e,resolvedBinary:e.resolvedBinary??void 0}}async function n1(e,t){if(!WB(e)){let n="Skipped because no SQLite index database exists yet.";return te(t,{id:"health",label:"Health audit",status:"skipped",message:n}),Ay(n)}try{let n=await $s({full:!0,json:!0});return te(t,{id:"health",label:"Health audit",status:"ok",message:`Health score ${n.score}. ${n.actions.length} prioritized action(s).`}),i1(n)}catch(n){let i=na(n);return te(t,{id:"health",label:"Health audit",status:"failed",message:i}),Ay(i)}}function i1(e){return{score:e.score,riskScore:e.riskScore,hygieneScore:e.hygieneScore,issuesNeedAttention:e.actions.map(r1),warnings:e.warnings??[]}}function r1(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-health-audit to confirm this signal; use scip-health-improve when the user wants confirmed issues fixed autonomously."}}function Ay(e){return{score:null,riskScore:null,hygieneScore:null,issuesNeedAttention:[],warnings:[],unavailableReason:e}}function $y(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 o1(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 s1(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 a1(e){return e.score===null?`unavailable (${e.unavailableReason??"not checked"})`:`${e.score} (risk ${e.riskScore}, hygiene ${e.hygieneScore})`}function te(e,t){e.push({...t,details:t.details?.filter(n=>n.trim()!=="")})}function na(e){return e instanceof Error?e.message:String(e)}import{existsSync as c1,mkdirSync as l1,writeFileSync as u1}from"fs";import{dirname as d1,join as m1}from"path";function jy(e,t={}){let n=m1(e,".github","workflows","scip-query.yml"),i=p1();return c1(n)&&!t.force?{path:n,written:!1,skipped:!0,content:i,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(l1(d1(n),{recursive:!0}),u1(n,i)),{path:n,written:!t.dryRun,skipped:!1,content:i})}function p1(){return`name: scip-query
|
|
828
881
|
|
|
829
882
|
on:
|
|
830
883
|
pull_request:
|
|
@@ -842,48 +895,49 @@ jobs:
|
|
|
842
895
|
- run: npm ci
|
|
843
896
|
- run: npx scip-query reindex
|
|
844
897
|
- run: npx scip-query diff-gate --base "origin/\${{ github.base_ref }}"
|
|
845
|
-
`}var ey=Symbol("option-value-source");function K(e){return(...t)=>{let{args:n,opts:r}=PO(t);Je(i=>e({db:i,args:n,opts:r}))}}function Q(e,t){return K(n=>{let r=Ss(n.db,e,R(n.opts,"full"),{quiet:R(n.opts,"json")});t({...n,budget:r})})}function ty(e){return K(t=>Ar(t,e,{kind:"list"}))}function ny(e){return K(t=>Ar(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function ry(e){return K(t=>Ar(t,e,{kind:"grouped",key:e.key}))}function Vn(e){return K(t=>Xl(t,e))}function iy(e){return Vn({commandName:e.commandName,query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>P.sectionedReport(e.sections(t,n)),toJson:e.toJson,after:e.after})}function Xe(e,t){return Q(e,n=>Xl(n,{...t,commandName:t.commandName??e}))}function oy(e,t){return Xe(e,{commandName:t.commandName??e,query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,r)=>P.sectionedReport(t.sections(n,r)),toJson:t.toJson,after:t.after})}function Ft(e,t){return Q(e,n=>Ar(n,{...t,commandName:e},{kind:"list"}))}function Hs(e,t){return Q(e,n=>Ar(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Vs(e,t){return Q(e,n=>Ar(n,{...t,commandName:e},{kind:"grouped",key:t.key}))}function H(e,t){return String(e[t])}function pe(e,t){let n=e[t];return typeof n=="string"?n:void 0}function E(e,t){let n=e[t];return typeof n=="string"?n:void 0}function ke(e,t){let n=e[t];return typeof n=="number"?n:void 0}function R(e,t){return!!e[t]}function Jl(e,t){let n=e[t];return Array.isArray(n)&&n.every(r=>typeof r=="string")?n:[]}function N(e,t,n){return ke(e,t)??n}function O(e,t,n){let r=ke(e,t),i=r!==void 0&&Kl(e,t)!=="default";if(R(e,"full")){if(i)throw new Error("--full cannot be combined with --limit. Use --full for all findings, or --limit N for a capped report.");return Number.POSITIVE_INFINITY}return r??n}function Kl(e,t){return e[ey]?.(t)}function Ar(e,t,n){Xl(e,{commandName:t.commandName,query:t.query,emptyMessage:(r,i)=>r.length===0&&t.emptyMessage?t.emptyMessage(i):void 0,heuristicLabel:t.heuristicLabel,render:(r,i)=>{n.kind==="list"?P.list(r,o=>t.format(o,i)):n.kind==="table"?P.table(n.headers,r.map(o=>t.format(o,i)),n.dashWidths):P.groupedByFile(r,o=>t.format(o,i),n.key?o=>n.key(o,i):void 0)},toJson:t.toJson,after:t.after})}function Xl(e,t){let n=t.query(e);if(R(e.opts,"json")){A(t.commandName,e.args,e.opts,t.toJson?t.toJson(n,e):n);return}let r=t.emptyMessage?.(n,e);if(r){P.empty(r);return}t.heuristicLabel&&Er(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function A(e,t,n,r){console.log(JSON.stringify({command:e,args:DO(t),options:n,result:r},null,2))}function DO(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function PO(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:se(t)}}function se(e){if(!e||typeof e!="object")return{};let t=e;if(typeof t.opts=="function"){let n=t.opts();return!n||typeof n!="object"?{}:(typeof t.getOptionValueSource=="function"&&Object.defineProperty(n,ey,{value:r=>t.getOptionValueSource(r),enumerable:!1}),n)}return e}var _O=new Set(["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"]),FO=18e4,ly=100*1024*1024,$O=new Set(aa),AO=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],MO=[["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 jO(e){return e.filter(t=>_O.has(t))}async function uy(e){let t=se(e),n=de(),r=Pe(n),i=bt(n,r);try{let o=jO(Jl(t,"language")),s=await tn({projectRoot:n,languages:o.length>0?o:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:R(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:r.indexer?.typescript?.projectMode,typescriptProjects:r.indexer?.typescript?.projects,skipIfUnchanged:!R(t,"force"),allowPartial:R(t,"allowPartial"),indexerConcurrency:ke(t,"indexerConcurrency")??r.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"}});console.log(`${s.reused?"Reused":"Indexed"} ${s.languages.join(", ")} in ${(s.durationMs/1e3).toFixed(1)}s`)}catch(o){console.error(`error: ${o instanceof Error?o.message:o}`),process.exit(1)}}function dy(){let e=de(),t=Nr(e);try{let n=en({projectRoot:e,dbPath:t,onStatus:r=>console.log(r)});console.log(`Scanned ${n.scanned} auxiliary source files; inserted ${n.inserted}.`)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function my(e){let t=se(e),n=de(),r=Nr(n);try{let i=El({projectRoot:n,dbPath:r,tsconfig:E(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${i.vueFiles}; resolved references: ${i.resolvedReferences}; inserted mentions: ${i.insertedMentions}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}}function py(e){let t=se(e);Je(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=gt(n,{base:E(t,"base")}),o=Xo(n,r,i.changedFiles,i.changedRanges);console.log(JSON.stringify(o))})}async function fy(e){let t=se(e);try{let n=await rg({base:E(t,"base")});if(R(t,"json")){A("diff-impact",[],t,n);return}og(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function gy(e,t){let n=se(t),r=String(e).split(",").filter(i=>i.length>0);Je(i=>{let o=[];for(let c of r)wr.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:E(n,"scope"),full:R(n,"full")},a=o.length===1?zc(i,o[0],s):Jc(i,o,s);console.log(JSON.stringify(a))})}async function hy(e){let t=se(e);if(R(t,"writeBaseline")||R(t,"baseline")){GO(t);return}try{let n=await xs({scope:E(t,"scope"),full:!0,json:R(t,"json")});if(R(t,"json")){A("health",[],t,n);return}ng(n,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function yy(e){let t=se(e),n=de(),r=ke(t,"timeoutMs")??FO,i={projectRoot:n,...UO(n),index:Ql(Mr(Nr(n))),commands:[]};R(t,"coldIndex")&&(i.coldIndex=await OO(n),i.warmIndex=await BO(n),i.index=Ql(Mr(Nr(n))));for(let o of HO(t))i.commands.push(qO(n,o,r));if(R(t,"json")){A("bench",[],t,i);return}WO(i)}async function OO(e){let t=Pe(e),n=bt(e,t),r=EO(n.dbPath),i=`${r}.bench-backup-${Date.now()}`,o=!1;Mr(r)&&(sy(r,i),o=!0);try{let s=await by(()=>tn({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,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench --cold-index"},onStatus:()=>{}}));return o&&NO(i,{recursive:!0,force:!0}),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...Sy(e)}}catch(s){throw o&&!Mr(r)&&sy(i,r),s}}async function BO(e){let t=Pe(e),n=bt(e,t),r=await by(()=>tn({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,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench warm index"},onStatus:()=>{}}));return{durationMs:r.durationMs,result:r.value.reused?"reused":"rebuilt",languages:r.value.languages,...Sy(e)}}async function by(e){let t=performance.now(),n=await e();return{durationMs:Math.round(performance.now()-t),value:n}}function Sy(e){return Mr(Nr(e))?Je(t=>{let n=$e(t);return{files:n.documents,symbols:n.symbols}}):{}}function HO(e){let t=Jl(e,"command");return t.length>0?t.map(VO).filter(n=>n.length>0):[...AO.map(n=>[...n]),...R(e,"includeHeavy")?MO.map(n=>[...n]):[]]}function VO(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function qO(e,t,n){let r=performance.now(),i=cy(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,encoding:"buffer",maxBuffer:ly,timeout:n}),o=Math.round(performance.now()-r);return{command:`scip-query ${t.join(" ")}`,durationMs:o,exitCode:i.status,signal:i.signal,timedOut:i.error?.name==="ETIMEDOUT",stdoutBytes:i.stdout?.length??0,stderrBytes:i.stderr?.length??0}}function UO(e){let t=cy("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:ly});if(t.status!==0)return{repoFiles:null,sourceFiles:null};let n=t.stdout.split(`
|
|
846
|
-
`)
|
|
847
|
-
|
|
848
|
-
|
|
898
|
+
`}var By=Symbol("option-value-source");function Y(e){return(...t)=>{let{args:n,opts:i}=g1(t);rt(r=>e({db:r,args:n,opts:i}))}}function ne(e,t){return Y(n=>{let i=As(n.db,e,I(n.opts,"full"),{quiet:I(n.opts,"json")});t({...n,budget:i})})}function Hy(e){return Y(t=>Ji(t,e,{kind:"list"}))}function Vy(e){return Y(t=>Ji(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function qy(e){return Y(t=>Ji(t,e,{kind:"grouped",key:e.key}))}function Yn(e){return Y(t=>bu(t,e))}function Uy(e){return Yn({commandName:e.commandName,query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>N.sectionedReport(e.sections(t,n)),toJson:e.toJson,after:e.after})}function st(e,t){return ne(e,n=>bu(n,{...t,commandName:t.commandName??e}))}function Wy(e,t){return st(e,{commandName:t.commandName??e,query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,i)=>N.sectionedReport(t.sections(n,i)),toJson:t.toJson,after:t.after})}function Bt(e,t){return ne(e,n=>Ji(n,{...t,commandName:e},{kind:"list"}))}function ia(e,t){return ne(e,n=>Ji(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function ra(e,t){return ne(e,n=>Ji(n,{...t,commandName:e},{kind:"grouped",key:t.key}))}function q(e,t){return String(e[t])}function ve(e,t){let n=e[t];return typeof n=="string"?n:void 0}function _(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Te(e,t){let n=e[t];return typeof n=="number"?n:void 0}function I(e,t){return!!e[t]}function hu(e,t){let n=e[t];return Array.isArray(n)&&n.every(i=>typeof i=="string")?n:[]}function E(e,t,n){return Te(e,t)??n}function H(e,t,n){let i=Te(e,t),r=i!==void 0&&yu(e,t)!=="default";if(I(e,"full")){if(r)throw new Error("--full cannot be combined with --limit. Use --full for all findings, or --limit N for a capped report.");return Number.POSITIVE_INFINITY}return i??n}function yu(e,t){return e[By]?.(t)}function Ji(e,t,n){bu(e,{commandName:t.commandName,query:t.query,emptyMessage:(i,r)=>i.length===0&&t.emptyMessage?t.emptyMessage(r):void 0,heuristicLabel:t.heuristicLabel,render:(i,r)=>{n.kind==="list"?N.list(i,o=>t.format(o,r)):n.kind==="table"?N.table(n.headers,i.map(o=>t.format(o,r)),n.dashWidths):N.groupedByFile(i,o=>t.format(o,r),n.key?o=>n.key(o,r):void 0)},toJson:t.toJson,after:t.after})}function bu(e,t){let n=t.query(e);if(I(e.opts,"json")){O(t.commandName,e.args,e.opts,t.toJson?t.toJson(n,e):n);return}let i=t.emptyMessage?.(n,e);if(i){N.empty(i);return}t.heuristicLabel&&qi(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function O(e,t,n,i){console.log(JSON.stringify({command:e,args:f1(t),options:n,result:i},null,2))}function f1(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function g1(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:he(t)}}function he(e){if(!e||typeof e!="object")return{};let t=e;if(typeof t.opts=="function"){let n=t.opts();return!n||typeof n!="object"?{}:(typeof t.getOptionValueSource=="function"&&Object.defineProperty(n,By,{value:i=>t.getOptionValueSource(i),enumerable:!1}),n)}return e}var S1=new Set(["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"]),x1=18e4,Ky=100*1024*1024,C1=new Set(va),v1=[["status","--json"],["status","--capabilities"],["capabilities","--json"],["capability-matrix","--json"],["stats"],["kind-counts"],["diff-impact","--json"],["diff-gate","--json"]],R1=[["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 k1(e){return e.filter(t=>S1.has(t))}async function Qy(e){let t=he(e),n=xe(),i=je(n),r=wt(n,i);try{let o=k1(hu(t,"language")),s=await ln({projectRoot:n,languages:o.length>0?o:i.languages,outputScip:r.indexPath,outputDb:r.dbPath,pnpmWorkspaces:I(t,"pnpmWorkspaces")||i.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:i.indexer?.typescript?.projectMode,typescriptProjects:i.indexer?.typescript?.projects,skipIfUnchanged:!I(t,"force"),allowPartial:I(t,"allowPartial"),indexerConcurrency:Te(t,"indexerConcurrency")??i.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query reindex"}});console.log(`${s.reused?"Reused":"Indexed"} ${s.languages.join(", ")} in ${(s.durationMs/1e3).toFixed(1)}s`)}catch(o){console.error(`error: ${o instanceof Error?o.message:o}`),process.exit(1)}}function Xy(){let e=xe(),t=Vi(e);try{let n=cn({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 Yy(e){let t=he(e),n=xe(),i=Vi(n);try{let r=Zl({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}.`)}catch(r){console.error(`error: ${r instanceof Error?r.message:r}`),process.exit(1)}}function Zy(e){let t=he(e);rt(n=>{let i=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),r=vt(n,{base:_(t,"base")}),o=ms(n,i,r.changedFiles,r.changedRanges);console.log(JSON.stringify(o))})}async function eb(e){let t=he(e);try{let n=await qg({base:_(t,"base")});if(I(t,"json")){O("diff-impact",[],t,n);return}Wg(n)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function tb(e,t){let n=he(t),i=String(e).split(",").filter(r=>r.length>0);rt(r=>{let o=[];for(let c of i)Mi.includes(c)||(console.error(`error: Unknown health phase: ${c}`),process.exit(1)),o.push(c);let s={scope:_(n,"scope"),full:I(n,"full")},a=o.length===1?Gr(r,o[0],s):hl(r,o,s);console.log(JSON.stringify(a))})}async function nb(e){let t=he(e);if(I(t,"writeBaseline")||I(t,"baseline")){F1(t);return}try{let n=await $s({scope:_(t,"scope"),full:!0,json:I(t,"json")});if(I(t,"json")){O("health",[],t,n);return}Vg(n,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function ib(e){let t=he(e),n=xe(),i=Te(t,"timeoutMs")??x1,r=I(t,"progress"),o=I(t,"profile"),s=_(t,"profileOut"),a={projectRoot:n,...E1(n),index:Su(Qi(Vi(n))),commands:[]};I(t,"coldIndex")&&(Ki(r,"cold index started"),a.coldIndex=await w1(n),Ki(r,`cold index finished ${a.coldIndex.durationMs}ms`),In({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),Ki(r,"warm index started"),a.warmIndex=await I1(n),Ki(r,`warm index finished ${a.warmIndex.durationMs}ms`),In({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=Su(Qi(Vi(n))));for(let c of L1(t))a.commands.push(P1(n,c,i,{progress:r,profile:o,profileOut:s}));if(I(t,"json")){O("bench",[],t,a);return}T1(a)}async function w1(e){let t=je(e),n=wt(e,t),i=y1(n.dbPath),r=`${i}.bench-backup-${Date.now()}`,o=!1;Qi(i)&&(zy(i,r),o=!0);try{let s=await rb(()=>ln({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,skipIfUnchanged:!0,allowPartial:!0,indexerConcurrency:t.indexerConcurrency,trigger:{kind:"manual-cli",detail:"scip-query bench --cold-index"},onStatus:()=>{}}));return o&&h1(r,{recursive:!0,force:!0}),{durationMs:s.durationMs,result:s.value.reused?"reused":"rebuilt",languages:s.value.languages,...ob(e)}}catch(s){throw o&&!Qi(i)&&zy(r,i),s}}async function I1(e){let t=je(e),n=wt(e,t),i=await rb(()=>ln({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,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,...ob(e)}}async function rb(e){let t=performance.now(),n=await e();return{durationMs:Math.round(performance.now()-t),value:n}}function ob(e){return Qi(Vi(e))?rt(t=>{let n=Ue(t);return{files:n.documents,symbols:n.symbols}}):{}}function L1(e){let t=hu(e,"command");return t.length>0?t.map(D1).filter(n=>n.length>0):[...v1.map(n=>[...n]),...I(e,"includeHeavy")?R1.map(n=>[...n]):[]]}function D1(e){return e.trim().split(/\s+/).filter(Boolean).filter((t,n)=>!(n===0&&t==="scip-query"))}function P1(e,t,n,i={}){let r=`scip-query ${t.join(" ")}`;Ki(i.progress,`${r} started`),In({type:"bench-command-start",command:r,projectRoot:e},i.profileOut);let o=performance.now(),s=i.profile?N1(r,i.profileOut):process.env,a=Jy(process.execPath,[...process.execArgv,process.argv[1]??"",...t],{cwd:e,env:s,encoding:"buffer",maxBuffer:Ky,timeout:n}),c=Math.round(performance.now()-o),l={command:r,durationMs:c,exitCode:a.status,signal:a.signal,timedOut:a.error?.name==="ETIMEDOUT",stdoutBytes:a.stdout?.length??0,stderrBytes:a.stderr?.length??0,...i.profileOut?{profilePath:i.profileOut}:{}};return Ki(i.progress,`${r} finished ${c}ms exit=${l.exitCode??l.signal??"unknown"}${l.timedOut?" timed-out":""}`),In({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 Ki(e,t){e&&process.stderr.write(`[bench] ${t}
|
|
899
|
+
`)}function N1(e,t){return{...process.env,SCIP_QUERY_PROFILE:"1",SCIP_QUERY_PROFILE_COMMAND:e,...t?{SCIP_QUERY_PROFILE_OUT:t}:{}}}function E1(e){let t=Jy("git",["-C",e,"ls-files","-co","--exclude-standard"],{encoding:"utf8",maxBuffer:Ky});if(t.status!==0)return{repoFiles:null,sourceFiles:null};let n=t.stdout.split(`
|
|
900
|
+
`).filter(Boolean);return{repoFiles:n.length,sourceFiles:n.filter(i=>C1.has(b1(i).toLowerCase())).length}}function T1(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, ${Wn(e.index.indexSizeBytes)}`),e.coldIndex&&Gy("Cold index",e.coldIndex),e.warmIndex&&Gy("Warm index",e.warmIndex),console.log(`
|
|
901
|
+
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 Gy(e,t){console.log(`${e}: ${t.durationMs}ms, ${t.result}, ${t.languages.join(", ")}${t.files?`, ${t.files} files`:""}${t.symbols?`, ${t.symbols} symbols`:""}`)}function F1(e){let t=_(e,"scope");rt(n=>{if(I(e,"writeBaseline")){let r=ul(n,{scope:t});console.log(`Baseline written to ${r.path} (${r.findingCount} finding(s)).`);return}let i=jr(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 sb(){let e=ea(),t=e.installed.length+e.alreadyLinked.length;console.log(`
|
|
902
|
+
${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function ab(e){let t=he(e),n=xe(),i=Zs(n);if(I(t,"json")){O("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: legacy user-level ${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(`
|
|
849
903
|
Project-local scip-query hooks are configured for this repository.`),console.log("Review new or changed hooks in Codex/Claude Code with /hooks before they run.")):console.log(`
|
|
850
|
-
No project-local hook config was written.`)}function
|
|
904
|
+
No project-local hook config was written.`)}function cb(){let e=!1;eo()?console.log("scip CLI: installed"):(Ml(),e=!0);let t=xe(),n=je(t),i=Dt(t,n);if(i.languages.length===0){console.log(`
|
|
851
905
|
No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
|
|
852
|
-
Detected languages: ${
|
|
853
|
-
Indexer readiness:`);for(let
|
|
854
|
-
Semantic provider readiness:`),console.log(`${o} typescript: ts-morph${s}`),
|
|
855
|
-
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
|
|
906
|
+
Detected languages: ${i.languages.join(", ")}`),console.log(`
|
|
907
|
+
Indexer readiness:`);for(let r of i.indexers){let o=r.runnable?" OK":r.installed?" WARN":" MISSING",s=r.resolvedBinary?` (${r.resolvedBinary})`:"";console.log(`${o} ${r.language}: ${r.binaryLabel}${s}`),r.note&&console.log(` ${r.note}`),!r.installed&&r.installUrl&&console.log(` install: ${r.installUrl}`),r.runnable||(e=!0)}if(i.semantic){let r=i.semantic,o=r.available?" OK":r.dependencyAvailable?" WARN":" MISSING",s=r.tsconfigPaths&&r.tsconfigPaths.length>1?` (${r.tsconfigPaths.length} tsconfigs)`:r.tsconfigPath?` (${r.tsconfigPath})`:"";console.log(`
|
|
908
|
+
Semantic provider readiness:`),console.log(`${o} typescript: ts-morph${s}`),r.reason&&console.log(` ${r.reason}; semantic checks will fall back to SCIP/source evidence`)}process.exitCode=e?1:0}function lb(e){db(e,"capabilities")}function ub(e){db(e,"capability-matrix")}function db(e,t){let n=he(e),i=xe(),r=je(i),o=Dt(i,r),s=Qn(o);if(I(n,"json")){O(t,[],n,s);return}xu(s)}function mb(){let e=xe(),t=Ot(e),n=Fg(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function pb(e){let t=he(e),n=xe(),i=je(n),r=ji(i,{projectRoot:n});if(I(t,"json"))O("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 fb(e,t){let n=he(t),i=_(n,"reason");if(!i||i.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let r=_g(xe(),{id:String(e),check:_(n,"check"),file:_(n,"file"),reason:i,expiresAt:_(n,"expiresAt")});if(I(n,"json")){O("suppress",[String(e)],n,r);return}console.log(`Suppression added to ${r.path} (${r.suppressionCount} total).`)}catch(r){console.error(`error: ${r instanceof Error?r.message:r}`),process.exitCode=1}}function gb(e){let t=he(e),{report:n,hasIndexerProblems:i,hasErrors:r}=hb("doctor");I(t,"json")?O("doctor",[],t,n):_1(n,i),process.exitCode=r?1:0}function hb(e){let{projectRoot:t,config:n,paths:i,dbPath:r}=Hi(),o=ji(n,{projectRoot:t}),s=Dt(t,n),a=Qn(s),c=Kn(t,n,i),l=s.indexers.some(d=>!d.runnable),u=o.some(d=>d.level==="error")||l||c.state==="missing"||c.state==="stale";return{report:{command:e,projectRoot:t,dbPath:r,configuredDbPath:i.dbPath,exists:Qi(r),configDiagnostics:o,readiness:s,freshness:c,capabilities:a,ok:!u},hasIndexerProblems:l,hasErrors:u}}function yb(e){let t=he(e),n=xe(),i=Ys(n,{gitHook:I(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(`
|
|
909
|
+
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 bb(e){let t=he(e);try{let n=await My({gitHook:I(t,"gitHook")});I(t,"json")?O("setup",[],t,n):Oy(n),process.exitCode=n.verdict==="blocked"?1:0}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Sb(e){let t=he(e),n=xe(),i=jy(n,{force:I(t,"force"),dryRun:I(t,"dryRun")});if(I(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 xb(e){let t=he(e),n=xe(),i=je(n),r=Te(t,"debounce"),o=Te(t,"cooldown"),s=Te(t,"gitPoll");r&&((i.watch??={}).debounceMs=r),o&&((i.watch??={}).cooldownMs=o),s&&((i.watch??={}).gitPollMs=s);let a=new ta({projectRoot:n,config:i,languages:i.languages,onStatus:c=>{process.stdout.write(`\r\x1B[K${$g(c)}`)},onReindexComplete:c=>{console.log(`
|
|
856
910
|
Reindex complete in ${(c/1e3).toFixed(1)}s`)},onError:c=>{console.error(`
|
|
857
|
-
Watch error: ${c.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${
|
|
911
|
+
Watch error: ${c.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${i.watch?.debounceMs??3e4}ms | Cooldown: ${i.watch?.cooldownMs??6e4}ms | Git poll: ${i.watch?.gitPollMs??2e3}ms`),console.log(`Press Ctrl+C to stop.
|
|
858
912
|
`),a.start(),process.on("SIGINT",()=>{a.stop(),console.log(`
|
|
859
|
-
Stopped.`),process.exit(0)})}function
|
|
860
|
-
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
|
|
861
|
-
Safe to delete.`,m),d.length>0&&(u.length>0&&console.log(""),
|
|
913
|
+
Stopped.`),process.exit(0)})}function Cb(e){let t=he(e),{report:n}=hb("status");if(I(t,"json")){O("status",[],t,{...n,stats:Su(n.exists)});return}A1(n,{capabilities:I(t,"capabilities")})}function _1(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})`:""}`),xu(e.capabilities)}function A1(e,t){if(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)`),e.readiness.semantic){let n=e.readiness.semantic.available?"available":"fallback",i=e.readiness.semantic.tsconfigPaths&&e.readiness.semantic.tsconfigPaths.length>1?` (${e.readiness.semantic.tsconfigPaths.length} tsconfigs)`:e.readiness.semantic.tsconfigPath?` (${e.readiness.semantic.tsconfigPath})`:"";console.log(`TS sem: ${n}${i}`),e.readiness.semantic.reason&&console.log(`TS note: ${e.readiness.semantic.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: ${$1(e.freshness.lastRefresh)}`),M1(e.exists),t.capabilities&&(console.log(""),xu(e.capabilities))}function $1(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 Su(e){if(e)return rt(t=>{let n=Ue(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function M1(e){e&&rt(t=>{let n=Ue(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${Wn(n.indexSizeBytes)}`),n.lastBuilt){let i=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${i}s ago`)}})}function xu(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(`
|
|
914
|
+
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 lo(e){return{...e,options:$(e.options)}}function Pt({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,...o}){let s=lo(o);return{...s,renderShape:"list",handler:Hy({commandName:s.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r})}}function oa({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,headers:o,dashWidths:s,...a}){let c=lo(a);return{...c,renderShape:"table",handler:Vy({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,headers:o,dashWidths:s})}}function vb({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,key:o,...s}){let a=lo(s);return{...a,renderShape:"grouped-by-file",handler:qy({commandName:a.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,key:o})}}function Rb({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:r,after:o,...s}){let a=lo(s);return{...a,renderShape:"sectioned-report",handler:Uy({commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:r,sections:i,after:o})}}function sa({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:r,after:o,...s}){let a=lo(s);return{...a,budget:a.budget??"semantic",renderShape:"sectioned-report",handler:Wy(a.id,{commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:r,sections:i,after:o})}}function Cu(e,t,n,i){console.log(`\u2550\u2550\u2550 ${t} (${e.length}, ${i} LOC) \u2550\u2550\u2550`),console.log(n),console.log("");let r=new Map;for(let a of e){let c=r.get(a.relativePath)??[];c.push(a),r.set(a.relativePath,c)}let o=[...r.entries()].map(([a,c])=>({file:a,bucket:c,totalLoc:c.reduce((l,u)=>l+u.loc,0)})).sort((a,c)=>c.totalLoc-a.totalLoc||a.file.localeCompare(c.file)),s=!0;for(let{file:a,bucket:c}of o){s||console.log(""),s=!1,console.log(` ${a}`),c.sort((l,u)=>l.startLine-u.startLine);for(let l of c)console.log(` ${Ee(l.startLine,l.endLine)} (${l.loc} LOC) ${l.shortName}`)}}var kb=ne("dead",({db:e,args:t,opts:n,budget:i})=>{let r={scope:ve(t,0)||void 0,minLoc:E(n,"minLoc",1),includeTests:I(n,"includeTests"),skipBarrels:I(n,"skipBarrels"),includeMembers:I(n,"includeMembers"),scanLimit:i.scanLimit,semantic:i.semantic},o=At(e,r),s=o.symbols.filter(y=>y.kind==="dead-code"),a=o.symbols.filter(y=>y.kind!=="dead-code"),c=!I(n,"onlyInternal"),l=!I(n,"onlyDead"),u=c?s:[],d=l?a:[],m=u.reduce((y,S)=>y+S.loc,0),p=d.reduce((y,S)=>y+S.loc,0),f={total:u.length+d.length,deadCode:u.length,fileInternal:d.length,loc:m+p};if(I(n,"json")){O("dead",t,n,{...o,shown:{deadCode:u,fileInternal:d},shownCounts:f,totals:{total:o.counts.total,deadCode:o.counts.deadCode,fileInternal:o.counts.fileInternal,loc:o.counts.loc}});return}if(u.length===0&&d.length===0){N.empty("No matching dead-code symbols found.");return}u.length>0&&Cu(u,"DEAD CODE",` Zero references anywhere \u2014 no cross-file callers AND no same-file uses.
|
|
915
|
+
Safe to delete.`,m),d.length>0&&(u.length>0&&console.log(""),Cu(d,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
|
|
862
916
|
single-use helper, an abstraction-in-progress, or a callback registered
|
|
863
917
|
through a framework path that static analysis cannot trace (signal
|
|
864
918
|
handlers, event listeners, dependency injection). NOT necessarily dead \u2014
|
|
865
|
-
review case by case.`,
|
|
866
|
-
\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: ${u.length+d.length} symbols \u2014 ${g.join(" + ")}`)}),
|
|
867
|
-
${e.length} unused import(s)`)}),
|
|
868
|
-
${e.length} isolated symbol(s)`)}),
|
|
869
|
-
${
|
|
870
|
-
${
|
|
919
|
+
review case by case.`,p));let g=[];c&&g.push(`${u.length} dead code (${m} LOC)`),l&&g.push(`${d.length} file-internal (${p} LOC)`),console.log(`
|
|
920
|
+
\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: ${u.length+d.length} symbols \u2014 ${g.join(" + ")}`)}),wb=Bt("unused-imports",{query:({db:e,args:t,budget:n})=>dc(e,q(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
|
|
921
|
+
${e.length} unused import(s)`)}),Ib=ra("isolated",{query:({db:e,opts:t,budget:n})=>Nn(e,{scope:_(t,"scope"),minLoc:E(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${Ee(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
|
|
922
|
+
${e.length} isolated symbol(s)`)}),Lb=ne("extract-candidates",({db:e,args:t,opts:n,budget:i})=>{let r=$n(e,{scope:_(n,"scope"),minLoc:E(n,"minLoc",10),minCallees:E(n,"minCallees",6),limit:H(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(I(n,"json")){O("extract-candidates",t,n,r);return}if(r.length===0)return N.empty("No extraction candidates found.");qi("extraction candidates");for(let o of r){console.log(`
|
|
923
|
+
${Pe(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(`
|
|
924
|
+
${r.length} extraction candidate(s) found.`)}),Db=ne("locality-candidates",({db:e,args:t,opts:n,budget:i})=>{let r=Oc(e,{target:ve(t,0)||void 0,scope:_(n,"scope"),minConsumers:E(n,"minConsumers",1),limit:H(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(I(n,"json")){O("locality-candidates",t,n,r);return}if(r.length===0)return N.empty("No locality candidates found.");qi("locality candidates");for(let o of r){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?Pe(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
|
|
871
925
|
${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(`
|
|
872
|
-
${
|
|
926
|
+
${r.length} locality candidate(s) found.`)}),Pb=Bt("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>qn(e,{scope:_(t,"scope"),maxLoc:E(t,"maxLoc",15),limit:H(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${Pe(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
|
|
873
927
|
Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
|
|
874
928
|
Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
|
|
875
|
-
${e.length} wrapper candidate(s).`)}),
|
|
929
|
+
${e.length} wrapper candidate(s).`)}),Nb=Bt("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>Hn(e,{scope:_(t,"scope"),maxLoc:E(t,"maxLoc",15),limit:H(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${Pe(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
|
|
876
930
|
Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
|
|
877
931
|
Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
|
|
878
932
|
Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
|
|
879
933
|
Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
|
|
880
|
-
${e.length} passthrough candidate(s).`)}),
|
|
934
|
+
${e.length} passthrough candidate(s).`)}),Eb=Bt("stale-abstractions",{query:({db:e,opts:t,budget:n})=>Vn(e,{scope:_(t,"scope"),minLoc:E(t,"minLoc",3),limit:H(t,"limit",30),includeLowConfidence:I(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}] ${Pe(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
|
|
881
935
|
${e.reason}
|
|
882
936
|
Kind: ${e.stalenessKind}; tier: ${e.actionTier}
|
|
883
937
|
Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
|
|
884
|
-
${e.length} stale abstraction(s).`)}),
|
|
885
|
-
${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}`,` ${
|
|
886
|
-
`)});return}
|
|
938
|
+
${e.length} stale abstraction(s).`)}),Tb=ia("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>Wr(e,{scope:_(t,"scope"),minLoc:E(t,"minLoc",10),limit:H(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]}),Fb=st("similar",{query:({db:e,args:t,opts:n,budget:i})=>{let r=ve(t,0);return r?{mode:"target",rows:Dr(e,r,{minSimilarity:E(n,"minSimilarity",.4),limit:H(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic})}:{mode:"all",rows:En(e,{minSimilarity:E(n,"minSimilarity",.4),limit:H(n,"limit",20),scope:_(n,"scope"),minCallees:E(n,"minCallees",4),crossFileOnly:I(n,"crossFileOnly"),scanLimit:i.scanLimit,semantic:i.semantic})}},emptyMessage:e=>{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==="target"){N.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=[`
|
|
939
|
+
${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(`
|
|
940
|
+
`)});return}N.list(e.rows,t=>`
|
|
887
941
|
${Math.round(t.similarity*100)}% similar:
|
|
888
942
|
A: ${t.shortNameA} (${t.fileA})
|
|
889
943
|
B: ${t.shortNameB} (${t.fileB})
|
|
@@ -891,85 +945,85 @@ ${Math.round(t.similarity*100)}% similar:
|
|
|
891
945
|
Recommendation: ${t.recommendation}
|
|
892
946
|
`+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
|
|
893
947
|
`:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
|
|
894
|
-
${e.rows.length} similar pair(s) found.`)}}),
|
|
948
|
+
${e.rows.length} similar pair(s) found.`)}}),_b=Yn({commandName:"similar-files",query:({db:e,args:t,opts:n})=>Tc(e,{minSimilarity:E(n,"minSimilarity",.5),limit:H(n,"limit",20),scope:_(n,"scope"),minDeps:Te(n,"minDeps"),filePattern:ve(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{N.list(e,t=>{let n=[`
|
|
895
949
|
${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(`
|
|
896
950
|
`)}),console.log(`
|
|
897
|
-
${e.length} similar pair(s) found.`)}}),
|
|
898
|
-
\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
|
|
899
|
-
${e.length} similar chain pair(s) found.`)}})
|
|
951
|
+
${e.length} similar pair(s) found.`)}}),Ab=Yn({commandName:"similar-chains",query:({db:e,opts:t})=>Fc(e,{minSimilarity:E(t,"minSimilarity",.5),limit:H(t,"limit",15),scope:_(t,"scope"),minChainLength:E(t,"minLength",3),maxChainLength:E(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(`
|
|
952
|
+
\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(`
|
|
953
|
+
${e.length} similar chain pair(s) found.`)}}),$b=st("drift",{query:({db:e,args:t,opts:n,budget:i})=>Bn(e,{scope:ve(t,0),minDeviation:E(n,"minDeviation",5),semantic:i.semantic}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),N.groupedByFile(e.results,t=>{let n=t.kind==="unused-import"?"UNUSED":t.kind==="layer-violation"?"LAYER":"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(`
|
|
900
954
|
`)},t=>t.file),console.log(`
|
|
901
|
-
${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)`)}}),
|
|
955
|
+
${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)`)}}),Mb=st("convergence",{query:({db:e,args:t,budget:n})=>xl(e,q(t,0),q(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols not found.",render:e=>{if(e){console.log(`
|
|
902
956
|
${Math.round(e.similarity*100)}% callee overlap
|
|
903
957
|
`),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)
|
|
904
958
|
`),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
|
|
905
959
|
Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
|
|
906
960
|
Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
|
|
907
|
-
Strategy: ${e.consolidationStrategy}`)}}}),
|
|
908
|
-
Signature: ${e.signature} (${e.functions.length} functions)`,n=e.functions.map(
|
|
961
|
+
Strategy: ${e.consolidationStrategy}`)}}}),Ob=Bt("similar-signatures",{query:({db:e,opts:t,budget:n})=>wl(e,{scope:_(t,"scope"),minLoc:E(t,"minLoc",3),limit:H(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=`
|
|
962
|
+
Signature: ${e.signature} (${e.functions.length} functions)`,n=e.functions.map(i=>` ${Pe(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
|
|
909
963
|
`);return`${t}
|
|
910
964
|
${n}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
|
|
911
|
-
${e.length} group(s) found.`)}),
|
|
912
|
-
`);for(let d of
|
|
913
|
-
Verifying batches against the project checker (throwaway worktree at HEAD)...`),u.checkers.length===0){console.log(" No checker detected (need tsconfig.json or a Cargo.toml) \u2014 skipped.");return}for(let d of u.checkers)console.log(` Checker: ${d}`);u.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${u.uncoveredFiles.join(", ")}`),u.baselineErrors>0&&console.log(` Baseline has ${u.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),u.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${u.dirtyOverlap.join(", ")}`);for(let d of u.batches)if(d.status==="verified")console.log(` Batch ${d.depth}: COMPILER-VERIFIED`);else{console.log(` Batch ${d.depth}: FAILED \u2014 the errors below name references the static evidence missed:`);for(let m of d.errors??[])console.log(` ${m}`)}}}),
|
|
914
|
-
`);let o=
|
|
915
|
-
${
|
|
916
|
-
`);for(let
|
|
917
|
-
Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),
|
|
965
|
+
${e.length} group(s) found.`)}),jb=ne("cleanup-plan",({db:e,args:t,opts:n,budget:i})=>{let r=cs(e,{scope:_(n,"scope"),minLoc:E(n,"minLoc",1),maxDepth:E(n,"maxDepth",5),scanLimit:i.scanLimit}),o=xe(),s=I(n,"patch"),a=I(n,"json"),c=I(n,"verify")||s;if(s&&!I(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(r.batches.length===0){if(a){O("cleanup-plan",t,n,r);return}return N.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=cu(r),u=c?ou(o,r):void 0;if(a){O("cleanup-plan",t,n,{result:r,verification:u});return}if(s){let d=lu(u,l);if(d.length>0){for(let p of d)console.error(`error: ${p}`);process.exitCode=1;return}let m=my(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} compiler-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.
|
|
966
|
+
`);for(let d of r.batches){let m=d.depth===0?`\u2500\u2500 Batch 0: deletable now (graph-fact, ${d.loc} LOC) \u2500\u2500`:`\u2500\u2500 Batch ${d.depth}: dead once batch ${d.depth-1} lands (cascade, ${d.loc} LOC) \u2500\u2500`;console.log(m);for(let p of d.entries)console.log(` ${p.file}:${p.startLine+1}-${p.endLine+1} ${p.shortName} (${p.loc} LOC)`);d.filesEmptied.length>0&&console.log(` -> empties: ${d.filesEmptied.join(", ")}`),console.log("")}if(r.blocked.length>0){console.log("Cascade blocked (references outside the removal set):");for(let d of r.blocked)console.log(` ${d.shortName} (${d.file}) blocked by ${d.blockingFiles.join(", ")}`)}if(u){if(console.log(`
|
|
967
|
+
Verifying batches against the project checker (throwaway worktree at HEAD)...`),u.checkers.length===0){console.log(" No checker detected (need tsconfig.json or a Cargo.toml) \u2014 skipped.");return}for(let d of u.checkers)console.log(` Checker: ${d}`);u.uncoveredFiles.length>0&&console.log(` WARNING: no checker covers these plan files (entries there are NOT verified): ${u.uncoveredFiles.join(", ")}`),u.baselineErrors>0&&console.log(` Baseline has ${u.baselineErrors} pre-existing error(s) \u2014 verifying differentially (no NEW errors).`),u.dirtyOverlap.length>0&&console.log(` WARNING: plan files dirty in working tree (verification runs at HEAD): ${u.dirtyOverlap.join(", ")}`);for(let d of u.batches)if(d.status==="verified")console.log(` Batch ${d.depth}: COMPILER-VERIFIED`);else{console.log(` Batch ${d.depth}: FAILED \u2014 the errors below name references the static evidence missed:`);for(let m of d.errors??[])console.log(` ${m}`)}}}),Bb=ne("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!I(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let i=I(t,"all"),r=Te(t,"batch");if(i===(r!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=cs(e,{scope:_(t,"scope"),minLoc:E(t,"minLoc",1),maxDepth:E(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){N.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=cu(o,{all:i,batch:r});if(s.length===0){console.error(`error: No cleanup batch ${r} exists.`),process.exitCode=1;return}let a=xe(),c=ou(a,o),l=lu(c,s,{allowDirty:I(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}au(a,s);let u=s.reduce((m,p)=>m+p.entries.length,0),d=s.reduce((m,p)=>m+p.loc,0);console.log(`Applied ${s.length} compiler-verified cleanup batch(es): ${u} symbol(s), ${d} LOC.`)}),Hb=ne("recent-duplicates",({db:e,args:t,opts:n,budget:i})=>{let r=pl(e,{windowCommits:E(n,"window",100),minSimilarity:Te(n,"minSimilarity"),limit:H(n,"limit",30),scope:_(n,"scope"),scanLimit:i.scanLimit,semantic:i.semantic});if(I(n,"json")){O("recent-duplicates",t,n,r);return}if(!r.available)return N.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return N.empty(`No recent re-implementations found (window: last ${r.windowCommits} commits).`);console.log(`Recent re-implementations (window: last ${r.windowCommits} commits):
|
|
968
|
+
`);let o=r.rootCauseGroups?.filter(s=>s.count>1)??[];if(o.length>0){console.log(`Root-cause groups (${o.length}):`);for(let s of o)console.log(` ${s.count} pair(s) ${s.kind.toUpperCase()} ${s.domain} ${Math.round(s.maxSimilarity*100)}% max`),s.establishedFile&&s.establishedSymbol&&console.log(` established: ${s.establishedFile} ${s.establishedSymbol}`),console.log(` files: ${s.relatedFiles.slice(0,6).join(", ")}`),console.log(` -> ${s.recommendation}`);console.log("")}for(let s of r.findings){let a=s.sharedEvidence.slice(0,16).join(", ");s.kind==="echo"?(console.log(` ${Math.round(s.similarity*100)}% ECHO ${s.domain} ${s.echoFile} ${s.echoSymbol} (added ${s.echoAgeCommits} commits ago)`),console.log(` duplicates established ${s.establishedFile} ${s.establishedSymbol}`)):(console.log(` ${Math.round(s.similarity*100)}% TWIN ${s.domain} ${s.echoFile} ${s.echoSymbol}`),console.log(` and ${s.establishedFile} ${s.establishedSymbol} (both new \u2014 consolidate before they diverge)`)),console.log(` basis: ${s.basis}`),a.length>0&&console.log(` shared: ${a}`)}console.log(`
|
|
969
|
+
${r.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),Vb=Y(({db:e,args:t,opts:n})=>{let i=ol(e,{doc:t[0]===void 0?void 0:q(t,0),limit:H(n,"limit",20),minCoupling:E(n,"minCoupling",3)});if(I(n,"json")){O("doc-drift",t,n,i);return}if(!i.available)return N.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return N.empty(`No drifting docs found across ${i.docsScanned} doc(s) \u2014 referenced and co-changed code has not moved since each doc last changed.`);console.log(`Docs whose referenced or co-changed code moved on without them (${i.docsScanned} docs scanned, ${i.commitsAnalyzed} commits analyzed):
|
|
970
|
+
`);for(let r of i.findings){console.log(` staleness ${r.staleness} ${r.doc}`);for(let o of r.brokenReferences.slice(0,4))console.log(` BROKEN REFERENCE: cites ${o} \u2014 that file no longer exists`);for(let o of r.subjects.slice(0,4)){let s=o.evidence==="both"?`referenced by doc + coupled ${o.coChanges}x`:o.evidence==="reference"?"referenced by doc":`coupled ${o.coChanges}x historically`;console.log(` ${o.changesSinceDocUpdate} change(s) since doc update ${o.file} (${s}; ${o.actionTier}/${o.docIntent})`);let a=o.docIntentReasons[0];a&&console.log(` intent: ${a}`);let c=o.citationContexts?.[0];c&&console.log(` cited claim: ${Ts(c)}`)}}console.log(`
|
|
971
|
+
Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),qb=Bt("unused-params",{query:({db:e,opts:t,budget:n})=>Hr(e,{scope:_(t,"scope"),limit:H(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${Pe(e.file,e.startLine,e.endLine)} ${e.shortName}
|
|
918
972
|
trailing unused: ${e.unusedTrailing.join(", ")} (${e.unusedTrailing.length} of ${e.paramCount} params \u2014 safe to drop)`,emptyMessage:()=>"No trailing unused parameters found.",heuristicLabel:"unused trailing parameter candidates",after:e=>console.log(`
|
|
919
|
-
${e.length} function(s) with trailing unused parameters.`)});var
|
|
973
|
+
${e.length} function(s) with trailing unused parameters.`)});var Ub=st("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>Tn(e,{minSimilarity:E(n,"minSimilarity",.62),minTokens:E(n,"minTokens",8),limit:H(n,"limit",20),scope:_(n,"scope"),scanLimit:i.scanLimit,filePattern:ve(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{N.list(e,t=>{let n=[`
|
|
920
974
|
${Math.round(t.similarity*100)}% similar React structure:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`];return 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(`
|
|
921
975
|
`)}),console.log(`
|
|
922
|
-
${e.length} duplicated React component pair(s) found.`)}}),
|
|
976
|
+
${e.length} duplicated React component pair(s) found.`)}}),Wb=st("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:i})=>Fn(e,{minSimilarity:E(n,"minSimilarity",.45),minSharedBehaviors:E(n,"minSharedBehaviors",6),limit:H(n,"limit",20),scope:_(n,"scope"),scanLimit:i.scanLimit,filePattern:ve(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{N.list(e,t=>{let n=[`
|
|
923
977
|
${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(`
|
|
924
978
|
`)}),console.log(`
|
|
925
|
-
${e.length} React hook candidate pair(s) found.`)}}),
|
|
979
|
+
${e.length} React hook candidate pair(s) found.`)}}),zb=st("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:i})=>Nr(e,{minComponentLines:E(n,"minComponentLines",300),minFileLines:E(n,"minFileLines",800),minJsxTokens:E(n,"minJsxTokens",80),minBehaviorTokens:E(n,"minBehaviorTokens",40),limit:H(n,"limit",20),scope:_(n,"scope"),scanLimit:i.scanLimit,filePattern:ve(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{N.list(e,t=>[`
|
|
926
980
|
${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(`
|
|
927
981
|
`)),console.log(`
|
|
928
|
-
${e.length} large React component(s) found.`)}}),
|
|
982
|
+
${e.length} large React component(s) found.`)}}),Gb=st("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>_n(e,{minSimilarity:E(n,"minSimilarity",.62),minTokens:E(n,"minTokens",8),limit:H(n,"limit",20),scope:_(n,"scope"),scanLimit:i.scanLimit,filePattern:ve(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{N.list(e,t=>{let n=[`
|
|
929
983
|
${Math.round(t.similarity*100)}% similar Vue structure:`,` ${t.fileA}`,` ${t.fileB}`];return 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(`
|
|
930
984
|
`)}),console.log(`
|
|
931
|
-
${e.length} duplicated Vue component pair(s) found.`)}}),
|
|
985
|
+
${e.length} duplicated Vue component pair(s) found.`)}}),Jb=st("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:i})=>An(e,{minSimilarity:E(n,"minSimilarity",.45),minSharedBehaviors:E(n,"minSharedBehaviors",6),limit:H(n,"limit",20),scope:_(n,"scope"),scanLimit:i.scanLimit,filePattern:ve(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{N.list(e,t=>{let n=[`
|
|
932
986
|
${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(`
|
|
933
987
|
`)}),console.log(`
|
|
934
|
-
${e.length} Vue composable candidate pair(s) found.`)}}),
|
|
988
|
+
${e.length} Vue composable candidate pair(s) found.`)}}),Kb=st("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:i})=>Er(e,{minTotalLines:I(n,"reviewThresholds")&&yu(n,"minTotalLines")==="default"?300:E(n,"minTotalLines",800),minTemplateLines:E(n,"minTemplateLines",300),minScriptLines:E(n,"minScriptLines",300),minStyleLines:E(n,"minStyleLines",500),limit:H(n,"limit",20),scope:_(n,"scope"),scanLimit:i.scanLimit,filePattern:ve(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{N.list(e,t=>{let n=[`
|
|
935
989
|
${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(`
|
|
936
990
|
`)}),console.log(`
|
|
937
|
-
${e.length} large Vue view pressure file(s) found.`)}});function ct(e){return{docs:w("Cleanup"),...e}}function we({heuristicLabel:e,...t}){return ct({...t,heuristic:{label:e}})}var Ws=[ct({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:_([p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Maximum findings",v,30),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:w("Cleanup",["scip-query unused-params -s src/services"]),handler:rb}),ct({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",v,1),p("--max-depth <n>","Maximum cascade depth",v,5),p("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),p("--patch","With --verify, print the compiler-verified deletion patch to stdout"),p("--json","Output as JSON for programmatic consumption"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:w("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:Zy}),ct({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Only include symbols >= N lines",v,1),p("--max-depth <n>","Maximum cascade depth",v,5),p("--verified","Required: verify the selected cleanup batch before applying it"),p("--batch <n>","Apply one batch depth",v),p("--all","Apply every compiler-verified batch in the plan"),p("--force-dirty","Allow applying when plan files already have working-tree edits"),p("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:w("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:eb}),ct({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:_([p("--window <n>",'How many commits back counts as "recent"',v,100),p("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",st),p("-n, --limit <n>","Maximum findings",v,30),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:w("Cleanup",["scip-query recent-duplicates --window 50"]),handler:tb}),ct({id:"doc-drift",command:"doc-drift [doc]",description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:_([p("-n, --limit <n>","Maximum docs to report",v,20),p("--min-coupling <n>","Minimum historical co-changes to track a subject",v,3),p("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:w("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:nb}),ct({id:"dead",command:"dead [scope]",description:"Find dead code and file-internal symbols (no cross-file consumers)",options:_([p("--min-loc <n>","Only show symbols >= N lines",v,1),p("--include-tests","Include test files"),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 only])"),p("--only-internal","Show only [file-internal only] symbols (skip [dead code])"),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:w("Cleanup",["scip-query dead --min-loc 10"]),handler:jy}),ct({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:_([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:Oy}),ct({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum lines of code",v,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:By}),we({id:"similar",command:"similar [symbol]",description:"Find heuristic function similarity candidates from callee fingerprints",options:_([p("--min-similarity <n>","Minimum Jaccard similarity (0-1)",st,.4),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-callees <n>","Minimum callees to consider",v,4),p("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:zy}),we({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:_([p("--min-similarity <n>","Minimum Jaccard similarity (0-1)",st,.5),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-deps <n>","Minimum dependencies to consider",v),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:Jy}),we({id:"react-component-duplicates",command:"react-component-duplicates [file]",description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:_([p("--min-similarity <n>","Minimum JSX structure similarity (0-1)",st,.62),p("--min-tokens <n>","Minimum structural tokens to consider",v,8),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:ib}),we({id:"react-hook-candidates",command:"react-hook-candidates [file]",description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:_([p("--min-similarity <n>","Minimum behavior similarity (0-1)",st,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",v,6),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:ob}),we({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:_([p("--min-component-lines <n>","Minimum component lines",v,300),p("--min-file-lines <n>","Minimum file lines",v,800),p("--min-jsx-tokens <n>","Minimum JSX structure tokens",v,80),p("--min-behavior-tokens <n>","Minimum behavior tokens",v,40),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:sb}),we({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:_([p("--min-similarity <n>","Minimum template similarity (0-1)",st,.62),p("--min-tokens <n>","Minimum structural tokens to consider",v,8),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:ab}),we({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:_([p("--min-similarity <n>","Minimum behavior similarity (0-1)",st,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",v,6),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:cb}),we({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:_([p("--min-total-lines <n>","Minimum total component lines",v,800),p("--min-template-lines <n>","Minimum template lines",v,300),p("--min-script-lines <n>","Minimum script lines",v,300),p("--min-style-lines <n>","Minimum style lines",v,500),p("--review-thresholds","Use lower review thresholds without changing health scoring"),p("-n, --limit <n>","Number of results",v,20),p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:lb}),we({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:_([p("--min-similarity <n>","Minimum chain similarity (0-1)",st,.5),p("-n, --limit <n>","Number of results",v,15),p("-s, --scope <path>","Limit to files matching path"),p("--min-length <n>","Minimum chain length",v,3),p("--max-length <n>","Maximum chain length",v,8),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Ky}),we({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum function LOC",v,10),p("--min-callees <n>","Minimum callees to analyze",v,6),p("-n, --limit <n>","Number of results",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Hy}),we({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:_([p("-s, --scope <path>","Limit scan mode to files matching path"),p("--min-consumers <n>","Minimum consumers in scan mode",v,1),p("-n, --limit <n>","Number of results",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:w("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:Vy}),we({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations",options:_([p("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",Fi,5),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:Xy}),we({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",v,15),p("-n, --limit <n>","Number of results",v,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:qy}),we({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--max-loc <n>","Maximum LOC for candidates",v,15),p("-n, --limit <n>","Number of results",v,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:Uy}),we({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",v,3),p("-n, --limit <n>","Number of results",v,30),p("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:Wy}),we({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:_([p("-s, --scope <path>","Limit to files matching path"),p("--min-loc <n>","Minimum LOC",v,10),p("-n, --limit <n>","Number of results",v,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:Gy}),ct({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Show what a consolidated version of two similar functions would look like",options:_([p("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:Qy}),Ay({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[p("-s, --scope <path>","Limit to files matching path"),p("-n, --limit <n>","Number of results",v,30),p("--full","Run unbounded analysis on large indexes")],docs:w("Cleanup"),query:({db:e,opts:t})=>el(e,{scope:E(t,"scope"),limit:O(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
|
|
991
|
+
${e.length} large Vue view pressure file(s) found.`)}});function ht(e){return{docs:P("Cleanup"),...e}}function Fe({heuristicLabel:e,...t}){return ht({...t,heuristic:{label:e}})}var aa=[ht({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:$([h("-s, --scope <path>","Limit to files matching path"),h("-n, --limit <n>","Maximum findings",L,30),h("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:P("Cleanup",["scip-query unused-params -s src/services"]),handler:qb}),ht({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[h("-s, --scope <path>","Limit to files matching path"),h("--min-loc <n>","Only include symbols >= N lines",L,1),h("--max-depth <n>","Maximum cascade depth",L,5),h("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),h("--patch","With --verify, print the compiler-verified deletion patch to stdout"),h("--json","Output as JSON for programmatic consumption"),h("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:P("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:jb}),ht({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[h("-s, --scope <path>","Limit to files matching path"),h("--min-loc <n>","Only include symbols >= N lines",L,1),h("--max-depth <n>","Maximum cascade depth",L,5),h("--verified","Required: verify the selected cleanup batch before applying it"),h("--batch <n>","Apply one batch depth",L),h("--all","Apply every compiler-verified batch in the plan"),h("--force-dirty","Allow applying when plan files already have working-tree edits"),h("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:P("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:Bb}),ht({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:$([h("--window <n>",'How many commits back counts as "recent"',L,100),h("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",ft),h("-n, --limit <n>","Maximum findings",L,30),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:P("Cleanup",["scip-query recent-duplicates --window 50"]),handler:Hb}),ht({id:"doc-drift",command:"doc-drift [doc]",description:"Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped",options:$([h("-n, --limit <n>","Maximum docs to report",L,20),h("--min-coupling <n>","Minimum historical co-changes to track a subject",L,3),h("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:P("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:Vb}),ht({id:"dead",command:"dead [scope]",description:"Find dead code and file-internal symbols (no cross-file consumers)",options:$([h("--min-loc <n>","Only show symbols >= N lines",L,1),h("--include-tests","Include test files"),h("--skip-barrels","Ignore refs from barrel re-export files"),h("--include-members","Include class members"),h("--only-dead","Show only [dead code] symbols (skip [file-internal only])"),h("--only-internal","Show only [file-internal only] symbols (skip [dead code])"),h("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:P("Cleanup",["scip-query dead --min-loc 10"]),handler:kb}),ht({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:$([h("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:wb}),ht({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:$([h("-s, --scope <path>","Limit to files matching path"),h("--min-loc <n>","Minimum lines of code",L,3),h("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:Ib}),Fe({id:"similar",command:"similar [symbol]",description:"Find heuristic function similarity candidates from callee fingerprints",options:$([h("--min-similarity <n>","Minimum Jaccard similarity (0-1)",ft,.4),h("-n, --limit <n>","Number of results",L,20),h("-s, --scope <path>","Limit to files matching path"),h("--min-callees <n>","Minimum callees to consider",L,4),h("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:Fb}),Fe({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:$([h("--min-similarity <n>","Minimum Jaccard similarity (0-1)",ft,.5),h("-n, --limit <n>","Number of results",L,20),h("-s, --scope <path>","Limit to files matching path"),h("--min-deps <n>","Minimum dependencies to consider",L),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:_b}),Fe({id:"react-component-duplicates",command:"react-component-duplicates [file]",description:"Find heuristic duplicated React component structure candidates from JSX tags, props, events, and bindings",options:$([h("--min-similarity <n>","Minimum JSX structure similarity (0-1)",ft,.62),h("--min-tokens <n>","Minimum structural tokens to consider",L,8),h("-n, --limit <n>","Number of results",L,20),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Ub}),Fe({id:"react-hook-candidates",command:"react-hook-candidates [file]",description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:$([h("--min-similarity <n>","Minimum behavior similarity (0-1)",ft,.45),h("--min-shared-behaviors <n>","Minimum shared behavior tokens",L,6),h("-n, --limit <n>","Number of results",L,20),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Wb}),Fe({id:"react-large-component-pressure",command:"react-large-component-pressure [file]",description:"Find heuristic large React component pressure candidates from component lines, JSX structure, and hook behavior",options:$([h("--min-component-lines <n>","Minimum component lines",L,300),h("--min-file-lines <n>","Minimum file lines",L,800),h("--min-jsx-tokens <n>","Minimum JSX structure tokens",L,80),h("--min-behavior-tokens <n>","Minimum behavior tokens",L,40),h("-n, --limit <n>","Number of results",L,20),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:zb}),Fe({id:"vue-component-duplicates",command:"vue-component-duplicates [file]",description:"Find heuristic duplicated Vue component structure candidates from template tags, bindings, slots, and directives",options:$([h("--min-similarity <n>","Minimum template similarity (0-1)",ft,.62),h("--min-tokens <n>","Minimum structural tokens to consider",L,8),h("-n, --limit <n>","Number of results",L,20),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:Gb}),Fe({id:"vue-composable-candidates",command:"vue-composable-candidates [file]",description:"Find heuristic Vue composable extraction candidates from shared state, effects, requests, and template bindings",options:$([h("--min-similarity <n>","Minimum behavior similarity (0-1)",ft,.45),h("--min-shared-behaviors <n>","Minimum shared behavior tokens",L,6),h("-n, --limit <n>","Number of results",L,20),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Jb}),Fe({id:"vue-large-view-pressure",command:"vue-large-view-pressure [file]",description:"Find heuristic large Vue view pressure candidates from template, script, style, and external script line counts",options:$([h("--min-total-lines <n>","Minimum total component lines",L,800),h("--min-template-lines <n>","Minimum template lines",L,300),h("--min-script-lines <n>","Minimum script lines",L,300),h("--min-style-lines <n>","Minimum style lines",L,500),h("--review-thresholds","Use lower review thresholds without changing health scoring"),h("-n, --limit <n>","Number of results",L,20),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Kb}),Fe({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:$([h("--min-similarity <n>","Minimum chain similarity (0-1)",ft,.5),h("-n, --limit <n>","Number of results",L,15),h("-s, --scope <path>","Limit to files matching path"),h("--min-length <n>","Minimum chain length",L,3),h("--max-length <n>","Maximum chain length",L,8),h("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Ab}),Fe({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:$([h("-s, --scope <path>","Limit to files matching path"),h("--min-loc <n>","Minimum function LOC",L,10),h("--min-callees <n>","Minimum callees to analyze",L,6),h("-n, --limit <n>","Number of results",L,20),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Lb}),Fe({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:$([h("-s, --scope <path>","Limit scan mode to files matching path"),h("--min-consumers <n>","Minimum consumers in scan mode",L,1),h("-n, --limit <n>","Number of results",L,20),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:P("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:Db}),Fe({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations",options:$([h("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",Yr,5),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:$b}),Fe({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer",options:$([h("-s, --scope <path>","Limit to files matching path"),h("--max-loc <n>","Maximum LOC for candidates",L,15),h("-n, --limit <n>","Number of results",L,30),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:Pb}),Fe({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:$([h("-s, --scope <path>","Limit to files matching path"),h("--max-loc <n>","Maximum LOC for candidates",L,15),h("-n, --limit <n>","Number of results",L,30),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:Nb}),Fe({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers",options:$([h("-s, --scope <path>","Limit to files matching path"),h("--min-loc <n>","Minimum LOC",L,3),h("-n, --limit <n>","Number of results",L,30),h("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:Eb}),Fe({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:$([h("-s, --scope <path>","Limit to files matching path"),h("--min-loc <n>","Minimum LOC",L,10),h("-n, --limit <n>","Number of results",L,20),h("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:Tb}),ht({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Show what a consolidated version of two similar functions would look like",options:$([h("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:Mb}),vb({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[h("-s, --scope <path>","Limit to files matching path"),h("-n, --limit <n>","Number of results",L,30),h("--full","Run unbounded analysis on large indexes")],docs:P("Cleanup"),query:({db:e,opts:t})=>vl(e,{scope:_(t,"scope"),limit:H(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
|
|
938
992
|
barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
|
|
939
993
|
Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
|
|
940
994
|
Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
|
|
941
|
-
${e.length} redundant re-export(s).`)}),
|
|
942
|
-
Cycle ${
|
|
943
|
-
${t.length} real cycle(s) found.`),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.)`)}}),
|
|
944
|
-
Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].chain)console.log(` \u2192 ${n}`);console.log(` Tier: ${e[t].actionTier} Risk: ${e[t].chainKind}`),console.log(` Recommendation: ${e[t].recommendation}`),console.log(` Evidence: ${e[t].evidenceReasons.join("; ")}`)}}}),
|
|
945
|
-
`)},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
|
|
946
|
-
`),console.log(` LOC: ${
|
|
947
|
-
`),console.log("Agreement with compiler semantics (file-level):");for(let
|
|
948
|
-
Top disagreements (debugging targets):`);for(let
|
|
949
|
-
\u2500\u2500 Depth ${o.depth} \u2500\u2500`),
|
|
950
|
-
${
|
|
951
|
-
`:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${
|
|
952
|
-
`);for(let o of
|
|
953
|
-
${
|
|
954
|
-
`),
|
|
955
|
-
No incomplete migrations detected.`);return}for(let o of
|
|
995
|
+
${e.length} redundant re-export(s).`)}),ht({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:$([h("-s, --scope <path>","Limit to files matching path"),h("--min-loc <n>","Minimum LOC per function",L,3),h("-n, --limit <n>","Number of groups",L,20),h("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:Ob})];var j1=Y(({db:e,args:t,opts:n})=>{let i=Ue(e);if(I(n,"json")){O("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: ${Wn(i.indexSizeBytes)}`),i.lastBuilt&&console.log(`Last built: ${i.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),Qb=[{id:"stats",command:"stats",description:"Show index statistics",options:[Al()],renderShape:"custom",docs:P("Core"),handler:j1}];var B1=ia("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>xc(e,{limit:H(t,"limit",20),scope:_(t,"scope"),minFanIn:E(t,"minFanIn",2),minFanOut:E(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."}),H1=Y(({db:e,args:t,opts:n})=>{let i=ve(t,0),r=H(n,"limit",30);if(i){let s=fc(e,i);if(I(n,"json")){O("fan-in",t,n,{mode:"symbol",symbol:i,rows:s});return}if(s.length===0)return N.empty(`No fan-in for ${i}.`);N.list(s,a=>` ${String(a.count).padStart(4)} files ${a.name}`);return}let o=hc(e,{limit:r,scope:_(n,"scope")});if(I(n,"json")){O("fan-in",t,n,{mode:"top",rows:o});return}N.table(["files","symbol"],o.map(s=>` ${String(s.count).padStart(5)} ${s.name}`))}),V1=Y(({db:e,args:t,opts:n})=>{let i=ve(t,0),r=H(n,"limit",30);if(i){let s=gc(e,i);if(I(n,"json")){O("fan-out",t,n,{mode:"file",file:i,rows:s});return}if(s.length===0)return N.empty(`No fan-out for ${i}.`);N.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=yc(e,{limit:r,scope:_(n,"scope")});if(I(n,"json")){O("fan-out",t,n,{mode:"top",rows:o});return}N.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),q1=Y(({db:e,args:t,opts:n})=>{let i=ve(t,0),r=ve(t,1),o=H(n,"limit",20);if(i&&r){let a=bc(e,i,r);if(I(n,"json")){O("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=Sc(e,{limit:o,scope:_(n,"scope")});if(I(n,"json")){O("coupling",t,n,{mode:"top",rows:s});return}N.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}`))}),U1=Yn({commandName:"cycles",query:({db:e,opts:t})=>Pn(e,{scope:_(t,"scope"),maxDepth:E(t,"maxDepth",10)}),emptyMessage:e=>e.length===0?"No circular dependencies found.":void 0,render:e=>{let t=e.filter(i=>i.kind==="real"),n=e.filter(i=>i.kind==="module-hierarchy");for(let i=0;i<t.length;i++){console.log(`
|
|
996
|
+
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(`
|
|
997
|
+
${t.length} real cycle(s) found.`),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.)`)}}),W1=Yn({commandName:"deep-chains",query:({db:e,opts:t})=>wc(e,{limit:H(t,"limit",10),scope:_(t,"scope"),minDepth:E(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(`
|
|
998
|
+
Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].chain)console.log(` \u2192 ${n}`);console.log(` Tier: ${e[t].actionTier} Risk: ${e[t].chainKind}`),console.log(` Recommendation: ${e[t].recommendation}`),console.log(` Evidence: ${e[t].evidenceReasons.join("; ")}`)}}}),Xb=[oa({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[h("-n, --limit <n>","Number of results",L,30),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")],docs:P("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>cc(e,{limit:H(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:"How many files reference a symbol (or top fan-in across codebase)",options:$([h("-n, --limit <n>","Number of results for top mode",L,30),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:P("Graph"),handler:H1},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:$([h("-n, --limit <n>","Number of results for top mode",L,30),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:P("Graph"),handler:V1},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:$([h("-n, --limit <n>","Number of results for top mode",L,20),h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:P("Graph"),handler:q1},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:$([h("-s, --scope <path>","Limit to files matching path"),h("--max-depth <n>","Maximum cycle depth",L,10)]),renderShape:"custom",docs:P("Graph"),handler:U1},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:$([h("-n, --limit <n>","Number of results",L,20),h("-s, --scope <path>","Limit to files matching path"),h("--min-fan-in <n>","Minimum fan-in",L,2),h("--min-fan-out <n>","Minimum fan-out",L,2),h("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:P("Graph"),handler:B1},{id:"deep-chains",command:"deep-chains",description:"Find the longest transitive dependency chains",options:$([h("-n, --limit <n>","Number of chains to show",L,10),h("-s, --scope <path>","Limit to files matching path"),h("--min-depth <n>","Minimum chain depth",L,3),h("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:P("Graph"),handler:W1},sa({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[h("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:P("Graph"),query:({db:e,args:t,budget:n})=>Ir(e,String(t[0]),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"Symbol not found.",before:e=>{e&&console.log(`Symbol: ${e.shortName}
|
|
999
|
+
`)},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 z1=ne("complexity",({db:e,args:t,opts:n,budget:i})=>{let r=qr(e,q(t,0),{semantic:i.semantic});if(I(n,"json")){O("complexity",t,n,r);return}if(!r)return N.empty("Symbol not found.");console.log(`${Pe(r.relativePath,r.startLine,r.endLine)} ${r.shortName}
|
|
1000
|
+
`),console.log(` LOC: ${r.loc}`),console.log(` Branches: ${r.branches}`),console.log(` Cyclomatic estimate: ${r.cyclomaticEstimate}`),console.log(` Callees: ${r.calleeCount}`),console.log(` Fan-in: ${r.fanIn}`),console.log(` Fan-out: ${r.fanOut}`)}),G1=Y(({db:e,args:t,opts:n})=>{let i=kl(e,{samples:E(n,"samples",50),scope:_(n,"scope")});if(I(n,"json")){O("self-audit",t,n,i);return}if(!i.available)return N.empty("No semantic provider available to audit against (TypeScript projects only).");console.log(`Sampled ${i.sampleSize} symbols; oracle answered ${Math.round(i.oracleCoverage*100)}%.
|
|
1001
|
+
`),console.log("Agreement with compiler semantics (file-level):");for(let r of i.scores){let o=r.precision===null?`unverified ${r.unverified} (oracle partial \u2014 no precision claim)`:`precision ${r.precision}`;console.log(` ${r.question.padEnd(11)} ${o} recall ${r.recall} (${r.comparedSymbols} symbols)`)}if(i.topDisagreements.length>0){console.log(`
|
|
1002
|
+
Top disagreements (debugging targets):`);for(let r of i.topDisagreements)console.log(` ${r.symbol} [${r.question}]`),r.cheapOnly.length>0&&console.log(` cheap-only: ${r.cheapOnly.join(", ")}`),r.oracleOnly.length>0&&console.log(` oracle-only: ${r.oracleOnly.join(", ")}`)}}),Yb=[{id:"self-audit",command:"self-audit",description:"Score the cheap evidence paths against the TypeScript compiler oracle on sampled symbols",options:$([h("--samples <n>","Number of symbols to sample",L,50),h("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:P("Health",["scip-query self-audit --samples 100"]),handler:G1},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:$([h("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:P("Health"),handler:z1}];var J1=Y(({db:e,args:t,opts:n})=>{let i=Tr(e,q(t,0),{maxDepth:E(n,"maxDepth",5),scope:_(n,"scope")});if(I(n,"json")){O("affected",t,n,i);return}if(i.length===0)return N.empty("No affected symbols found.");let r=-1;for(let o of i)o.depth!==r&&(console.log(`
|
|
1003
|
+
\u2500\u2500 Depth ${o.depth} \u2500\u2500`),r=o.depth),console.log(` ${o.file} ${o.shortName}`);console.log(`
|
|
1004
|
+
${i.length} affected symbol(s) across ${new Set(i.map(o=>o.file)).size} files.`)}),K1=Y(({db:e,args:t,opts:n})=>{let i=t[0]===void 0?void 0:q(t,0),r=Mn(e,i,{minTogether:E(n,"minTogether",4),limit:H(n,"limit",30),includeLinked:n.all===!0});if(I(n,"json")){O("co-change",t,n,r);return}if(!r.available)return N.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return N.empty(i?`No co-change partners found for ${i} in ${r.commitsAnalyzed} commits.`:`No hidden coupling found in ${r.commitsAnalyzed} commits.`);console.log(i?`Co-change partners (${r.commitsAnalyzed} commits analyzed):
|
|
1005
|
+
`:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${r.commitsAnalyzed} commits analyzed):
|
|
1006
|
+
`);for(let o of r.findings){let s=o.structurallyLinked?" [dep edge]":"",a=` [${o.partnerClass}]`,c=` [${o.commitScope}/${o.recency}]`;console.log(` ${o.together}x (${Math.round(o.confidence*100)}%) ${o.fileA} <-> ${o.fileB}${a}${c}${s}`),console.log(` history: ${o.focusedTogether} focused, ${o.broadTogether} broad-sweep (${Math.round(o.broadCommitRatio*100)}% broad), ${o.recentTogether} recent; last ${Q1(o.lastTogetherAt)}`),console.log(` subjects: ${X1(o.subjectContext)}`),o.declaredCouplingSuggestion&&console.log(` declare coupling: ${o.declaredCouplingSuggestion.name} (${o.declaredCouplingSuggestion.reason})`)}console.log(`
|
|
1007
|
+
${r.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function Q1(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function X1(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 Y1=ne("change-surface",({db:e,args:t,opts:n,budget:i})=>{let r=Fr(e,q(t,0),{semantic:i.semantic});if(I(n,"json")){O("change-surface",t,n,r);return}if(!r)return N.empty("File not found in index.");console.log(`File: ${r.file}`),console.log(`External consumers: ${r.totalExternalConsumers}
|
|
1008
|
+
`),N.list(r.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${Ee(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),Z1=ne("incomplete-migration",({db:e,args:t,opts:n,budget:i})=>{let r=Br(e,{base:_(n,"base"),minContainment:E(n,"minContainment",.7),maxHelpers:Te(n,"maxHelpers"),limit:H(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(I(n,"json")){O("incomplete-migration",t,n,r),r.available&&r.findings.length>0&&(process.exitCode=1);return}if(!r.available)return N.empty("No git history available (not a repository, or git missing).");if(r.changedFiles.length===0)return N.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(`
|
|
1009
|
+
No incomplete migrations detected.`);return}for(let o of r.findings){console.log(`
|
|
956
1010
|
${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(`
|
|
957
|
-
${
|
|
958
|
-
`);for(let s of
|
|
959
|
-
FAIL: ${
|
|
960
|
-
`).map((s,a)=>` ${
|
|
961
|
-
`))}let n=[],
|
|
962
|
-
`);let i
|
|
963
|
-
`);for(let o=0;o<
|
|
964
|
-
`),
|
|
965
|
-
\u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let o of
|
|
966
|
-
\u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let o of
|
|
967
|
-
\u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let o of
|
|
968
|
-
`),o.connectedSymbols.length===0){console.log(" No connected symbols found.");return}
|
|
1011
|
+
${r.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function eH(e){let t=Array.isArray(e)?e:[],n=t.filter(i=>!ws.includes(i));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${ws.join(", ")}`),process.exit(1)),t}var tH=Y(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&Xs(oo()))return;let i=As(e,"diff-gate",I(t,"full"),{quiet:n||I(t,"json")}),r=Vr(e,{base:_(t,"base"),minTogether:E(t,"minTogether",6),maxEchoChecks:Te(t,"maxEchoChecks"),maxHelpers:Te(t,"maxHelpers"),includeBaseline:I(t,"baseline"),scanLimit:i.scanLimit,semantic:i.semantic,skip:eH(t.skip)});if(!n&&I(t,"json")){O("diff-gate",[],t,{exitCode:r.findings.length>0?1:0,...r}),r.findings.length>0&&(process.exitCode=1);return}if(n){if(r.findings.length===0)return;console.error(so(r)),process.exitCode=2;return}if(r.changedFiles.length===0)return N.empty(r.note??`No changes vs ${r.base}.`);console.log(`Diff gate vs ${r.base}: ${r.changedFiles.length} file(s), ${r.changedSymbols} symbol(s) changed.`),console.log(`Checks: ${r.checksRun.join(", ")}
|
|
1012
|
+
`);for(let s of r.skipped)console.log(` skipped ${s.check}: ${s.reason}`);if(r.findings.length===0){console.log("PASS: this change introduces no gate findings.");return}let o=r.rootCauseGroups?.filter(s=>s.count>1)??[];if(o.length>0){console.log(`Root-cause groups (${o.length}):`);for(let s of o){console.log(` [${s.check}] ${s.count} finding(s), ${s.severity}${s.actionTier?`, tier: ${s.actionTier}`:""}`),(s.sourceAnalyzer||s.rootCauseKey)&&console.log(` source: ${s.sourceAnalyzer??s.check}${s.rootCauseKey?` root cause: ${s.rootCauseKey}`:""}`);let a=[...new Set([...s.files,...s.relatedFiles])].slice(0,6);a.length>0&&console.log(` files: ${a.join(", ")}`),console.log(` -> ${s.remediation}`)}console.log("")}for(let s of r.findings){if(console.log(` [${s.check}] ${s.message}`),s.partnerClass){console.log(` partner class: ${s.partnerClass}`);for(let a of s.partnerClassReasons??[])console.log(` reason: ${a}`)}s.citationKind&&console.log(` citation kind: ${s.citationKind}${s.actionTier?` (tier: ${s.actionTier})`:""}`);for(let a of s.citedClaims?.slice(0,2)??[])console.log(` cited claim: ${Ts(a)}`);s.declaredCouplingSuggestion&&console.log(` declare coupling: ${s.declaredCouplingSuggestion.name} (${s.declaredCouplingSuggestion.reason})`),console.log(` -> ${s.remediation}`)}console.log(`
|
|
1013
|
+
FAIL: ${r.findings.length} finding(s), ${r.rootCauseGroups?.length??r.findings.length} root-cause group(s). Fix or knowingly accept before merging.`),process.exitCode=1}),Zb=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:$([h("--max-depth <n>","Maximum traversal depth",L,5),h("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:P("Impact"),handler:J1},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:$([h("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:P("Impact"),handler:Y1},{id:"diff-gate",command:"diff-gate",description:"Gate the current diff: echo candidates, incomplete migrations, missing co-change partners, uncited doc updates, unused params, new dead symbols; exit 1 on findings",options:[h("--base <ref>","Git ref to diff against (default: HEAD)"),h("--min-together <n>","Minimum historical co-changes for the partner check",L,6),h("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",L),h("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",L),h("--baseline","Also run the full health-baseline ratchet"),h("--full","Run unbounded semantic analysis on large indexes"),h("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, doc-reference, unused-params, new-dead, baseline",Xr,[]),h("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),h("--json","Output as JSON for programmatic consumption")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:P("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:tH},{id:"incomplete-migration",command:"incomplete-migration",description:"Partially-completed extraction candidates: new helpers in the diff wired into some sites while similar un-migrated sites remain",options:$([h("--base <ref>","Git ref to diff against (default: HEAD)"),h("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",ft,.7),h("--max-helpers <n>","Maximum new helpers to score (default: all)",L),h("-n, --limit <n>","Maximum findings to report",L,20),h("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:P("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:Z1},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:$([h("--min-together <n>","Minimum commits where both files changed",L,4),h("-n, --limit <n>","Maximum pairs to report",L,30),h("--all","Include pairs that already have a dependency edge"),h("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:P("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:K1}];function nH(e){let t=[];for(let r of e.definitions){let o=r.signature?` \u2014 ${r.signature}`:"";t.push(` ${Pe(r.relativePath,r.startLine,r.endLine)}${o}`),r.source&&t.push(r.source.split(`
|
|
1014
|
+
`).map((s,a)=>` ${Je(r.startLine+a)} ${s}`).join(`
|
|
1015
|
+
`))}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 ${Je(r.line)} in ${r.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var iH=Y(({db:e,args:t,opts:n})=>{let i=q(t,0),r=I(n,"signatures"),o=mc(e,i);if(I(n,"json")){O("outline",t,n,o);return}if(o.length===0)return N.empty(`No symbols found for "${i}".`);function s(a,c){for(let l of a){let u=" ".repeat(c),d=r&&l.signature?` - ${rH(l.signature)}`:"";console.log(`${u}${Ee(l.startLine,l.endLine)} ${l.shortName}${d}`),s(l.children,c+1)}}s(o,0)});function rH(e){return e.length>120?`${e.slice(0,117)}...`:e}var oH=Bt("imports",{query:({db:e,args:t,budget:n})=>lc(e,q(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)."}),sH=ra("refs",{query:({db:e,args:t,budget:n})=>ic(e,q(t,0),{semantic:n.semantic}),format:e=>` line ${Je(e.line)}`}),aH=Y(({db:e,args:t,opts:n})=>{let i=Cl(e,q(t,0),{context:E(n,"context",0)});if(I(n,"json")){O("code",t,n,i);return}if(!i)return N.empty("Symbol not found or file unreadable.");console.log(`${Pe(i.relativePath,i.startLine,i.endLine)} ${i.shortName} [${i.language??"unknown"}]
|
|
1016
|
+
`);let r=i.source.split(`
|
|
1017
|
+
`);for(let o=0;o<r.length;o++)console.log(` ${String(Je(i.startLine+o)).padStart(4)} ${r[o]}`)}),cH=ne("dataflow",({db:e,args:t,opts:n,budget:i})=>{let r=Ur(e,q(t,0),{semantic:i.semantic});if(I(n,"json")){O("dataflow",t,n,r);return}if(!r)return N.empty("Symbol not found.");if(console.log(`${r.shortName} (${r.relativePath})
|
|
1018
|
+
`),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let o of r.definitionSites)console.log(` ${o.file}:${Je(o.line)}`)}if(r.usageSites.length>0){console.log(`
|
|
1019
|
+
\u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let o of r.usageSites)console.log(` ${o.file}:${Je(o.line)} in ${o.enclosingShort}`)}if(r.producers.length>0){console.log(`
|
|
1020
|
+
\u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let o of r.producers)console.log(` ${o.file} ${o.shortName}`)}if(r.consumers.length>0){console.log(`
|
|
1021
|
+
\u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let o of r.consumers)console.log(` ${o.file} ${o.shortName}`)}}),lH=ne("slice",({db:e,args:t,opts:n,budget:i})=>{let r=I(n,"forward")?"forward":"backward",o=$i(e,q(t,0),{direction:r,maxDepth:E(n,"depth",3),semantic:i.semantic});if(I(n,"json")){O("slice",t,n,o);return}if(!o)return N.empty("Symbol not found.");if(console.log(`${o.direction} slice of ${o.shortName}
|
|
1022
|
+
`),o.connectedSymbols.length===0){console.log(" No connected symbols found.");return}N.list(o.connectedSymbols,s=>` ${s.file} ${s.shortName}
|
|
969
1023
|
${s.relationship}`),console.log(`
|
|
970
|
-
${o.connectedSymbols.length} connected symbol(s).`)}),
|
|
971
|
-
${e.length} symbol(s)`)}),
|
|
972
|
-
`).map((o,s)=>` ${String(Oe(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${Re(r.startLine,r.endLine)} ${r.shortName}`)),nn(n,t).rows}function LB(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${Oe(r.line)} in ${r.enclosingShort}`);return qn(nn(n,t))}function IB(e,t){if(!e.callGraph)return[];let n=e.callGraph.callers.map(i=>` caller ${i.file} ${i.shortName}`),r=e.callGraph.callees.map(i=>` callee ${i.file} ${i.shortName}`);return qn(nn([...n,...r],t))}function DB(e,t){if(!e.dataflow)return[];let n=e.dataflow.producers.map(o=>` producer ${o.file} ${o.shortName}`),r=e.dataflow.consumers.map(o=>` consumer ${o.file} ${o.shortName}`),i=e.dataflow.usageSites.map(o=>` usage ${o.file}:${Oe(o.line)} in ${o.enclosingShort}`);return qn(nn([...n,...r,...i],t))}function PB(e,t){let n=[...e.deps.map(r=>` file depends on ${r.relativePath}`),...e.rdeps.map(r=>` file depended on by ${r.relativePath}`),...e.system.dependsOn.map(r=>` module depends on ${r}`),...e.system.dependedOnBy.map(r=>` module used by ${r}`)];return qn(nn(n,t))}function NB(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${Re(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return qn(nn(n,t))}function EB(e,t){let n=[],r=-1;for(let i of e.affected)i.depth!==r&&(n.push(` -- Depth ${i.depth} --`),r=i.depth),n.push(` ${i.file} ${i.shortName}`);return qn(nn(n,t))}function TB(e,t){let n=[];return e.changeSurface&&(n.push(` File: ${e.changeSurface.file}`),n.push(` External consumers: ${e.changeSurface.totalExternalConsumers}`),n.push(...e.changeSurface.symbols.map(r=>{let i=r.riskLevel==="high"?" *** HIGH RISK ***":r.riskLevel==="medium"?" * medium risk *":"";return` ${Re(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${Se(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}`)),qn(nn(n,t))}function _B(e){let t=e.history;if(!t.available||!t.file)return[];let n=[];if(t.churn){let r=t.churn.fixChanges>0?`, ${t.churn.fixChanges} in fix commits`:"";n.push(` Churn: ${t.churn.changes} change(s) in recent history${r}`)}for(let r of t.coChangePartners)n.push(` Usually changes with: ${r.file} (${r.together}x, ${Math.round(r.confidence*100)}%)`);return t.suppressionsInFile>0&&n.push(` Detector suppressions in file: ${t.suppressionsInFile} (accepted findings \u2014 read the reasons before refactoring)`),n}function FB(e){let t=e.warnings.map(r=>` ${r}`);return e.history.coChangePartners.length>0&&t.push(" Check the HISTORY co-change partners \u2014 editing this file usually means editing them too."),(e.changeSurface?.symbols.filter(r=>r.riskLevel==="high")??[]).length>0&&t.push(" Inspect high-risk consumers before editing public behavior."),e.affected.length>0&&t.push(" Validate downstream consumers at the shallowest affected depths first."),t}function nn(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function qn(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function eu(e){return e?"yes":"no"}var hb=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","bottlenecks","isolated","by-kind","kind-counts","deep-chains","hierarchy","call-graph","similar","similar-files","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","similar-chains","extract-candidates","locality-candidates","affected","change-surface","cleanup-plan","cleanup-apply","co-change","recent-duplicates","doc-drift","unused-params","diff-gate","incomplete-migration","plan-context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","dataflow","slice","redundant-reexports","similar-signatures"],$B=[ub,fb,db,Ws,pb,gb,mb],yb=$B.flat(),AB=new Map(yb.map(e=>[e.id,e]));for(let e of yb)if(!hb.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var jr=hb.map(e=>MB(e));function MB(e){let t=AB.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var jB=jr.slice(0,tu("plan-context")),OB=jr.slice(Gs("drift"),tu("self-audit")),BB=jr.slice(Gs("convergence"),tu("slice")),HB=jr.slice(Gs("redundant-reexports")),bb=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[p("-l, --language <lang>","Index only this language (can be repeated)",_i,[]),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",Fi)],renderShape:"custom",docs:w("Indexing",["scip-query reindex"]),handler:uy},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:w("Indexing"),handler:dy},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[p("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:w("Indexing"),handler:my},...jB,{id:bs,command:bs,description:"Internal diff-impact batch worker",hidden:!0,options:[p("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:py},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:_([p("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:w("Impact"),handler:fy},...OB,{id:Ti,command:Ti,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:gy},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[p("-s, --scope <path>","Limit to files matching path"),p("--full","Compatibility flag; health already runs unbounded candidate analyses by default"),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:w("Health",["scip-query health --json","scip-query health --baseline"]),handler:hy},{id:"bench",command:"bench",description:"Benchmark indexing and command runtimes for this repository",options:[p("--json","Output as JSON for programmatic consumption"),p("--cold-index","Temporarily clear this project index cache and measure a cold rebuild"),p("--include-heavy","Include expensive full-detector commands in the command matrix"),p("--command <cmd>","Benchmark a specific scip-query command (can be repeated)",_i,[]),p("--timeout-ms <n>","Per-command timeout in milliseconds",Fi,18e4)],renderShape:"custom",docs:w("Maintenance",["scip-query bench","scip-query bench --json --cold-index"]),handler:yy},...BB,{id:"install-skills",command:"install-skills",description:`Install skills (${zl.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:w("Maintenance"),handler:xy},{id:"setup-hooks",command:"setup-hooks",description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:Cy},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:jh},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:Oh},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:w("Maintenance"),handler:vy},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance"),handler:Ry},{id:"capability-matrix",command:"capability-matrix",description:"Report the evidence and verification capability matrix by language",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance"),handler:ky},...HB,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:w("Maintenance"),handler:Ly},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance",["scip-query config-validate"]),handler:Iy},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding in .scipquery.json with a required reason",options:_([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:w("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:Dy},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[p("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:w("Maintenance"),handler:Py},{id:"setup",command:"setup",description:"Bootstrap this project: install agent skills, refresh the index, verify capabilities, and report health",options:_([p("--git-hook","Also install a git pre-commit hook that runs diff-gate")]),renderShape:"custom",docs:w("Maintenance",["scip-query setup","scip-query setup --json"]),handler:Ty},{id:"setup-agent",command:"setup-agent",description:"Seed agent guidance for this project: AGENTS.md/CLAUDE.md block pointing agents at the scip-query skills and diff gate, plus an optional git pre-commit backstop",options:[p("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:w("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:Ey},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[p("--force","Overwrite an existing workflow"),p("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:w("Maintenance",["scip-query setup-ci"]),handler:_y},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[p("--debounce <ms>","Ms to wait after last change (default: 30000)",Cs),p("--cooldown <ms>","Min ms between reindexes (default: 60000)",Cs),p("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",Cs)],renderShape:"custom",docs:w("Maintenance"),handler:Fy},{id:"status",command:"status",description:"Show index status for this project",options:[p("--json","Output as JSON for programmatic consumption"),p("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:w("Maintenance"),handler:$y}];function Gs(e){let t=jr.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function tu(e){return Gs(e)+1}function Sb(e,t){return t.map(n=>{let r=n.hidden?e.command(n.command,{hidden:!0}):e.command(n.command);r.description(n.description);for(let i of n.arguments??[])r.argument(i.name);for(let i of n.options??[])i.parser&&Object.hasOwn(i,"defaultValue")?r.option(i.flags,i.description,i.parser,i.defaultValue):i.parser?r.option(i.flags,i.description,i.parser):Object.hasOwn(i,"defaultValue")?r.option(i.flags,i.description,i.defaultValue):r.option(i.flags,i.description);return r.action(async(...i)=>{try{await n.handler(...i)}catch(o){VB(o)}}),{descriptor:n,command:r}})}function VB(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${t}`),process.exitCode=1}import{existsSync as qB,mkdirSync as UB,readFileSync as WB,writeFileSync as GB}from"fs";import{homedir as zB}from"os";import{join as zs}from"path";var JB=1440*60*1e3,Cb="update-check.json",KB="https://registry.npmjs.org/scip-query/latest";async function vb(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let n=e.cacheDir??YB(t),r=e.now??Date.now(),i=e.currentVersion??ys,o=ZB(n),s=o&&r-o.checkedAt<JB?o.latestVersion:await e1(n,e.fetchLatestVersion??n1,r);if(!s||!QB(s,i))return;(e.writeNotice??(c=>console.error(c)))(XB(i,s))}function XB(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
|
|
973
|
-
`)}function
|
|
974
|
-
`)}catch{}}async function
|
|
1024
|
+
${o.connectedSymbols.length} connected symbol(s).`)}),eS=[Pt({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:P("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>da(e,q(t,0)),format:e=>e.relativePath}),Pt({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:P("Navigation"),query:({db:e,args:t})=>nc(e,q(t,0)),format:e=>` ${Ee(e.startLine,e.endLine)} ${e.name}`}),{id:"refs",command:"refs <symbol>",description:"Find all files referencing a symbol",options:[h("--full","Run unbounded semantic analysis on large indexes"),h("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"grouped-by-file",docs:P("Navigation",["scip-query refs login"]),handler:sH},sa({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[h("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:P("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>xr(e,q(t,0),{semantic:n.semantic}),sections:nH}),Pt({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:P("Navigation"),query:({db:e,args:t})=>Cr(e,q(t,0)),format:e=>e.relativePath}),Pt({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:P("Navigation"),query:({db:e,args:t})=>vr(e,q(t,0)),format:e=>e.relativePath}),Rb({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",docs:P("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>Rr(e,q(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${Ee(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}`)}]}),Pt({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:P("Navigation"),query:({db:e,args:t})=>kr(e,q(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[h("--full","Run unbounded semantic analysis on large indexes"),h("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:P("Navigation"),handler:oH},Pt({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:P("Navigation"),query:({db:e,args:t})=>uc(e,q(t,0)),format:e=>` ${e.fromFile}`}),{id:"outline",command:"outline <file>",description:"Tree view of symbols in a file, with line ranges",options:$([h("--signatures","Show trimmed symbol signatures")]),renderShape:"custom",docs:P("Navigation"),handler:iH},Pt({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:P("Navigation"),query:({db:e,args:t})=>pc(e,q(t,0)),format:e=>` ${Ee(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`}),Pt({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[h("-s, --scope <path>","Limit to files matching path"),h("-n, --limit <n>","Number of results",L,100),h("--full","Run unbounded analysis on large indexes")],docs:P("Navigation"),query:({db:e,args:t,opts:n})=>Rc(e,q(t,0),{scope:_(n,"scope"),limit:H(n,"limit",100)}),format:e=>` ${Pe(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${q(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
|
|
1025
|
+
${e.length} symbol(s)`)}),oa({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[h("-s, --scope <path>","Limit to files matching path")],docs:P("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>kc(e,{scope:_(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),Pt({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:P("Navigation"),query:({db:e,args:t})=>Ic(e,q(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,emptyMessage:()=>"Symbol not found."}),{id:"code",command:"code <symbol>",description:"Read the source code for a symbol (bounded to its definition range)",options:$([h("-C, --context <n>","Extra lines of context above/below",L,0)]),renderShape:"custom",docs:P("Navigation"),handler:aH},{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:$([h("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:P("Navigation"),handler:cH},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:$([h("--forward","Forward slice (what does this affect). Default is backward."),h("--depth <n>","Max transitive depth for backward slice",L,3),h("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:P("Navigation"),handler:lH}];var uH=ne("plan-context",({db:e,args:t,opts:n,budget:i})=>{let r=H(n,"limit",20),o=fl(e,q(t,0),{semantic:i.semantic,impactDepth:E(n,"impactDepth",3),sliceDepth:E(n,"sliceDepth",3),scope:_(n,"scope")});if(o.warnings.length===1&&o.warnings[0]==="No symbol, file, or module matched target."){if(I(n,"json")){O("plan-context",t,n,o);return}return N.empty(o.warnings[0])}if(I(n,"json")){O("plan-context",t,n,o);return}let s=[{title:"TARGET",rows:dH(o)},{title:"DEFINITIONS",rows:mH(o,r),skipIfEmpty:!0},{title:"REFERENCES",rows:pH(o,r),skipIfEmpty:!0},{title:"CALL GRAPH",rows:fH(o,r),skipIfEmpty:!0},{title:"DATAFLOW",rows:gH(o,r),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:hH(o,r),skipIfEmpty:!0},{title:"SURFACE",rows:yH(o,r),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:bH(o,r),skipIfEmpty:!0},{title:"CHANGE RISK",rows:SH(o,r),skipIfEmpty:!0},{title:"HISTORY",rows:xH(o),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:CH(o),skipIfEmpty:!0}];N.sectionedReport(s)}),tS=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:$([h("--impact-depth <n>","Maximum affected traversal depth",L,3),h("--slice-depth <n>","Maximum backward slice depth",L,3),h("-s, --scope <path>","Limit downstream impact to files matching path"),h("-n, --limit <n>","Rows per section",L,20),h("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:P("Planning",["scip-query plan-context parseSymbol"]),handler:uH}];function dH(e){return[`Target: ${e.target}`,`Matched: symbol=${vu(e.matched.symbol)} file=${vu(e.matched.file)} module=${vu(e.matched.module)}`]}function mH(e,t){let n=[];for(let i of e.trace.definitions){let r=i.signature?` -- ${i.signature}`:"";n.push(` ${Pe(i.relativePath,i.startLine,i.endLine)}${r}`),i.source&&n.push(...i.source.split(`
|
|
1026
|
+
`).map((o,s)=>` ${String(Je(i.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(i=>` ${Ee(i.startLine,i.endLine)} ${i.shortName}`)),un(n,t).rows}function pH(e,t){let n=e.trace.referencedBy.map(i=>` ${i.relativePath}:${Je(i.line)} in ${i.enclosingShort}`);return Zn(un(n,t))}function fH(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 Zn(un([...n,...i],t))}function gH(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}:${Je(o.line)} in ${o.enclosingShort}`);return Zn(un([...n,...i,...r],t))}function hH(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 Zn(un(n,t))}function yH(e,t){let n=[...e.system.files.map(i=>` file ${i}`),...e.system.symbols.map(i=>` export ${Ee(i.startLine,i.endLine)} ${i.shortName}`),...e.surface.map(i=>` use ${i.consumer} -> ${i.shortName}`)];return Zn(un(n,t))}function bH(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 Zn(un(n,t))}function SH(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` ${Ee(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${r}`}))),e.complexity&&(n.push(` Complexity: ${Pe(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}`)),Zn(un(n,t))}function xH(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 CH(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 un(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function Zn(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function vu(e){return e?"yes":"no"}var nS=["stats","files","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","bottlenecks","isolated","by-kind","kind-counts","deep-chains","hierarchy","call-graph","similar","similar-files","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","similar-chains","extract-candidates","locality-candidates","affected","change-surface","cleanup-plan","cleanup-apply","co-change","recent-duplicates","doc-drift","unused-params","diff-gate","incomplete-migration","plan-context","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","self-audit","convergence","code","complexity","dataflow","slice","redundant-reexports","similar-signatures"],vH=[Qb,eS,Xb,aa,Zb,tS,Yb],iS=vH.flat(),RH=new Map(iS.map(e=>[e.id,e]));for(let e of iS)if(!nS.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);var Xi=nS.map(e=>kH(e));function kH(e){let t=RH.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var wH=Xi.slice(0,Ru("plan-context")),IH=Xi.slice(ca("drift"),Ru("self-audit")),LH=Xi.slice(ca("convergence"),Ru("slice")),DH=Xi.slice(ca("redundant-reexports")),rS=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[h("-l, --language <lang>","Index only this language (can be repeated)",Xr,[]),h("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),h("--force","Rebuild even if source inputs are unchanged"),h("--allow-partial","Write an incomplete index when one or more detected languages fail"),h("--indexer-concurrency <n>","Number of language indexers to run at once",Yr)],renderShape:"custom",docs:P("Indexing",["scip-query reindex"]),handler:Qy},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:P("Indexing"),handler:Xy},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[h("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:P("Indexing"),handler:Yy},...wH,{id:_s,command:_s,description:"Internal diff-impact batch worker",hidden:!0,options:[h("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:Zy},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:$([h("--base <ref>","Git ref to diff against (default: HEAD)")]),renderShape:"custom",docs:P("Impact"),handler:eb},...IH,{id:Qr,command:Qr,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[h("-s, --scope <path>","Limit to files matching path"),h("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:tb},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[h("-s, --scope <path>","Limit to files matching path"),h("--full","Compatibility flag; health already runs unbounded candidate analyses by default"),h("--json","Output as JSON for programmatic consumption"),h("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),h("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:P("Health",["scip-query health --json","scip-query health --baseline"]),handler:nb},{id:"bench",command:"bench",description:"Benchmark indexing and command runtimes for this repository",options:[h("--json","Output as JSON for programmatic consumption"),h("--cold-index","Temporarily clear this project index cache and measure a cold rebuild"),h("--include-heavy","Include expensive full-detector commands in the command matrix"),h("--command <cmd>","Benchmark a specific scip-query command (can be repeated)",Xr,[]),h("--timeout-ms <n>","Per-command timeout in milliseconds",Yr,18e4),h("--progress","Print benchmark command start/finish progress to stderr"),h("--profile","Enable low-overhead phase profiling in benchmarked commands"),h("--profile-out <path>","Append benchmark and phase profile events as JSONL")],renderShape:"custom",docs:P("Maintenance",["scip-query bench","scip-query bench --json --cold-index"]),handler:ib},...LH,{id:"install-skills",command:"install-skills",description:`Install skills (${gu.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:P("Maintenance"),handler:sb},{id:"setup-hooks",command:"setup-hooks",description:"Install or refresh project-local Codex and Claude Code lifecycle hooks",options:[h("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:P("Maintenance",["scip-query setup-hooks","scip-query setup-hooks --json"]),handler:ab},{id:"hook-context",command:"hook-context",description:"Internal agent lifecycle hook context renderer",hidden:!0,renderShape:"custom",handler:ky},{id:"hook-stop",command:"hook-stop",description:"Internal agent Stop hook wrapper for diff-gate",hidden:!0,renderShape:"custom",handler:wy},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:P("Maintenance"),handler:cb},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[h("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:P("Maintenance"),handler:lb},{id:"capability-matrix",command:"capability-matrix",description:"Report the evidence and verification capability matrix by language",options:[h("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:P("Maintenance"),handler:ub},...DH,{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:P("Maintenance"),handler:mb},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[h("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:P("Maintenance",["scip-query config-validate"]),handler:pb},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding in .scipquery.json with a required reason",options:$([h("--reason <text>","Required human reason for accepting the finding"),h("--check <check>","Optional detector/check name to narrow the suppression"),h("--file <path>","Optional file path to narrow the suppression"),h("--expires-at <iso>","Optional ISO date after which the suppression expires")]),renderShape:"custom",docs:P("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:fb},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[h("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:P("Maintenance"),handler:gb},{id:"setup",command:"setup",description:"Bootstrap this project: install agent skills, refresh the index, verify capabilities, and report health",options:$([h("--git-hook","Also install a git pre-commit hook that runs diff-gate")]),renderShape:"custom",docs:P("Maintenance",["scip-query setup","scip-query setup --json"]),handler:bb},{id:"setup-agent",command:"setup-agent",description:"Seed agent guidance for this project: AGENTS.md/CLAUDE.md block pointing agents at the scip-query skills and diff gate, plus an optional git pre-commit backstop",options:[h("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:P("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:yb},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[h("--force","Overwrite an existing workflow"),h("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:P("Maintenance",["scip-query setup-ci"]),handler:Sb},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[h("--debounce <ms>","Ms to wait after last change (default: 30000)",Ms),h("--cooldown <ms>","Min ms between reindexes (default: 60000)",Ms),h("--git-poll <ms>","Ms between Git HEAD/index checks (default: 2000)",Ms)],renderShape:"custom",docs:P("Maintenance"),handler:xb},{id:"status",command:"status",description:"Show index status for this project",options:[h("--json","Output as JSON for programmatic consumption"),h("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:P("Maintenance"),handler:Cb}];function ca(e){let t=Xi.findIndex(n=>n.id===e);if(t<0)throw new Error(`Ordered query command descriptor is missing: ${e}`);return t}function Ru(e){return ca(e)+1}function oS(e,t){return t.map(n=>{let i=n.hidden?e.command(n.command,{hidden:!0}):e.command(n.command);i.description(n.description);for(let r of n.arguments??[])i.argument(r.name);for(let r of n.options??[])r.parser&&Object.hasOwn(r,"defaultValue")?i.option(r.flags,r.description,r.parser,r.defaultValue):r.parser?i.option(r.flags,r.description,r.parser):Object.hasOwn(r,"defaultValue")?i.option(r.flags,r.description,r.defaultValue):i.option(r.flags,r.description);return i.action(async(...r)=>{try{await n.handler(...r)}catch(o){PH(o)}}),{descriptor:n,command:i}})}function PH(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${t}`),process.exitCode=1}import{existsSync as NH,mkdirSync as EH,readFileSync as TH,writeFileSync as FH}from"fs";import{homedir as _H}from"os";import{join as la}from"path";var AH=1440*60*1e3,aS="update-check.json",$H="https://registry.npmjs.org/scip-query/latest";async function cS(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let n=e.cacheDir??jH(t),i=e.now??Date.now(),r=e.currentVersion??Fs,o=BH(n),s=o&&i-o.checkedAt<AH?o.latestVersion:await HH(n,e.fetchLatestVersion??qH,i);if(!s||!OH(s,r))return;(e.writeNotice??(c=>console.error(c)))(MH(r,s))}function MH(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
|
|
1027
|
+
`)}function OH(e,t){let n=sS(e),i=sS(t);if(!n||!i)return e!==t;for(let r=0;r<n.length;r++){let o=n[r]-i[r];if(o>0)return!0;if(o<0)return!1}return!1}function jH(e){let t=e.XDG_CACHE_HOME||la(_H(),".cache");return la(t,"scip-query")}function BH(e){let t=la(e,aS);if(!NH(t))return null;try{let n=JSON.parse(TH(t,"utf8"));return typeof n.checkedAt=="number"&&(typeof n.latestVersion=="string"||n.latestVersion===null)?{checkedAt:n.checkedAt,latestVersion:n.latestVersion}:null}catch{return null}}async function HH(e,t,n){let i;try{i=await t()}catch{i=null}return VH(e,{checkedAt:n,latestVersion:i}),i}function VH(e,t){try{EH(e,{recursive:!0}),FH(la(e,aS),`${JSON.stringify(t,null,2)}
|
|
1028
|
+
`)}catch{}}async function qH(){let e=await fetch($H,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function sS(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}ua.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(Fs);oS(ua,rS);ua.hook("preAction",async()=>{await cS()});WH()&&await ua.parseAsync();function WH(){if(!process.argv[1])return!1;let e=UH(import.meta.url);try{return lS(e)===lS(process.argv[1])}catch{return e===process.argv[1]}}export{ua as program,qi as renderHeuristicNotice};
|
|
975
1029
|
//# sourceMappingURL=cli.js.map
|