scip-query 0.10.1 → 0.10.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/augment-vue-worker.js +1 -1
- package/dist/{chunk-24PFLKFK.js → chunk-3KLLFNT4.js} +2 -2
- package/dist/{chunk-UIWAZ2NT.js → chunk-3UVJJ6Z7.js} +1 -1
- package/dist/chunk-3UW7VM4H.js +62 -0
- package/dist/chunk-3ZYF3ELZ.js +2 -0
- package/dist/{chunk-6YKJSETN.js → chunk-47UA45TU.js} +2 -2
- package/dist/chunk-4HOMAEDD.js +2 -0
- package/dist/{chunk-5VB3WU7K.js → chunk-4ZUJJRWT.js} +2 -2
- package/dist/{chunk-LWPEZ4FP.js → chunk-5FOPAXWY.js} +2 -2
- package/dist/{chunk-CCB45WDY.js → chunk-5M4TYWVI.js} +2 -2
- package/dist/{chunk-PV4CEDIL.js → chunk-5QJXH6ZL.js} +5 -5
- package/dist/{chunk-NN3O7TPH.js → chunk-64MNV6AB.js} +1 -1
- package/dist/{chunk-LWWZBABT.js → chunk-77YBOOYT.js} +2 -2
- package/dist/chunk-7ADUXFRZ.js +2 -0
- package/dist/chunk-7KCSELEV.js +2 -0
- package/dist/{chunk-GZXXBDJA.js → chunk-7OHWPJ5N.js} +2 -2
- package/dist/{chunk-BJ7OHKB5.js → chunk-7S5E7KWT.js} +1 -1
- package/dist/chunk-A3VNUGKJ.js +2 -0
- package/dist/{chunk-CMGOXDVP.js → chunk-A4L36SZS.js} +2 -2
- package/dist/{chunk-5D3BT4B4.js → chunk-AUVBR62P.js} +2 -2
- package/dist/chunk-AW4N6MGC.js +18 -0
- package/dist/{chunk-65UWNXEH.js → chunk-B6MJ5VQV.js} +2 -2
- package/dist/chunk-BKDXBJDQ.js +2 -0
- package/dist/{chunk-WZVTADY7.js → chunk-C2QSK7E7.js} +1 -1
- package/dist/chunk-C3MZZ2ZN.js +2 -0
- package/dist/{chunk-GTNPPGZJ.js → chunk-CAWSSEVM.js} +2 -2
- package/dist/chunk-CFL2CNIF.js +10 -0
- package/dist/{chunk-E55WCTLH.js → chunk-CJJP64OC.js} +2 -2
- package/dist/{chunk-ADKQX2OY.js → chunk-CRU42NJU.js} +2 -2
- package/dist/chunk-CSWZFD46.js +2 -0
- package/dist/{chunk-QOFKVNFE.js → chunk-CTCAF3YA.js} +2 -2
- package/dist/{chunk-YVQUQIBM.js → chunk-D322LMSA.js} +2 -2
- package/dist/{chunk-IJYWCB57.js → chunk-DAI74TJU.js} +2 -2
- package/dist/chunk-DE7MA6OD.js +3 -0
- package/dist/chunk-DJMK4DBL.js +2 -0
- package/dist/{chunk-FVX4GEAC.js → chunk-E44ZMVNA.js} +2 -2
- package/dist/{chunk-MESUJJVQ.js → chunk-E7KERP7E.js} +2 -2
- package/dist/{chunk-YIE5FZAF.js → chunk-EOZIZWW4.js} +2 -2
- package/dist/{chunk-XGGTESMN.js → chunk-ERHOS6AW.js} +2 -2
- package/dist/{chunk-5HDYAOSF.js → chunk-ESG4HBEF.js} +2 -2
- package/dist/{chunk-HCQ7J2N5.js → chunk-EWC3UK4V.js} +3 -3
- package/dist/chunk-EYLXU575.js +2 -0
- package/dist/chunk-FIB4JPEX.js +2 -0
- package/dist/chunk-FNRPGGVI.js +2 -0
- package/dist/{chunk-QUKZ77A6.js → chunk-FOQHUKNZ.js} +2 -2
- package/dist/{chunk-QH5GTVVB.js → chunk-FUPDW5AC.js} +2 -2
- package/dist/{chunk-B3HMRQDA.js → chunk-G3WGZU5Q.js} +2 -2
- package/dist/chunk-GLJAAKDW.js +4 -0
- package/dist/{chunk-TUAPDKBI.js → chunk-GS33KGAY.js} +2 -2
- package/dist/{chunk-623UQCVG.js → chunk-GZCQTZLK.js} +2 -2
- package/dist/{chunk-SA6B3EGD.js → chunk-HVTYSC26.js} +2 -2
- package/dist/chunk-I7TSQZ3J.js +4 -0
- package/dist/{chunk-R7S3UCDR.js → chunk-ICXVNWMI.js} +2 -2
- package/dist/chunk-JM72FNGA.js +2 -0
- package/dist/{chunk-DRU74YUM.js → chunk-KPHKX4LP.js} +1 -1
- package/dist/chunk-KRGBLZT2.js +7 -0
- package/dist/{chunk-YYCQQBMG.js → chunk-LPLGJ4HO.js} +2 -2
- package/dist/chunk-MUULWXSJ.js +2 -0
- package/dist/chunk-MZ7APUFN.js +3 -0
- package/dist/{chunk-LYS4SMAQ.js → chunk-NNDYO2DX.js} +2 -2
- package/dist/{chunk-ATGRITZP.js → chunk-NP5HYVLX.js} +4 -4
- package/dist/{chunk-MHAQXOZY.js → chunk-NVFERV4U.js} +2 -2
- package/dist/{chunk-LWYIGRHR.js → chunk-NXIAHE7F.js} +1 -1
- package/dist/chunk-O3OKSF6O.js +2 -0
- package/dist/chunk-O4L4AB3T.js +2 -0
- package/dist/{chunk-TMS4JPWY.js → chunk-OBBDKQAG.js} +2 -2
- package/dist/chunk-OLD6PBU6.js +7 -0
- package/dist/{chunk-5BZOSICN.js → chunk-PFOCOG57.js} +1 -1
- package/dist/{chunk-CFLYMEUS.js → chunk-PVZMPG5I.js} +1 -1
- package/dist/{chunk-T67R7V5I.js → chunk-QLNGUWR7.js} +2 -2
- package/dist/chunk-QSXQT3NE.js +2 -0
- package/dist/{chunk-6TWFT4Y5.js → chunk-QVCCLDZI.js} +2 -2
- package/dist/{chunk-PNN3D4BE.js → chunk-RHTJBYZ5.js} +2 -2
- package/dist/chunk-SPE4YCOT.js +7 -0
- package/dist/{chunk-4N7LFYSD.js → chunk-TM6GVHA6.js} +2 -2
- package/dist/chunk-TO54DY4O.js +2 -0
- package/dist/{chunk-HQHFMPLJ.js → chunk-UMNENNTX.js} +2 -2
- package/dist/chunk-UQJGTVHV.js +5 -0
- package/dist/{chunk-TKDJQ2WD.js → chunk-UUBMFL3F.js} +1 -1
- package/dist/chunk-VAA5FFIW.js +2 -0
- package/dist/chunk-X474LKJX.js +2 -0
- package/dist/chunk-X7ZY6FFF.js +4 -0
- package/dist/{chunk-RNLUCQJB.js → chunk-YQH353VA.js} +2 -2
- package/dist/{chunk-44JOJLMO.js → chunk-YTR4CO5S.js} +2 -2
- package/dist/chunk-YUOAAR24.js +2 -0
- package/dist/chunk-YVLHL6KQ.js +8 -0
- package/dist/{chunk-ADTG377O.js → chunk-YYD245WG.js} +2 -2
- package/dist/{chunk-I6PTB2CM.js → chunk-Z4VHYJ5U.js} +2 -2
- package/dist/chunk-ZFMPHDAT.js +4 -0
- package/dist/chunk-ZQLO2SCU.js +6 -0
- package/dist/chunk-ZSLT7NWQ.js +61 -0
- package/dist/cli.js +242 -225
- package/dist/{config-types-Bok4jrO3.d.ts → config-types-Bj4sh28g.d.ts} +8 -0
- package/dist/{db-BkFlkzI3.d.ts → db-CTarohbZ.d.ts} +1 -1
- package/dist/git-history-Dao3_Pu9.d.ts +12 -0
- package/dist/{health-CbGMdRPg.d.ts → health-Bx0x1HAG.d.ts} +23 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/postinstall.js +1 -1
- package/dist/queries/affected.d.ts +2 -2
- package/dist/queries/affected.js +1 -1
- package/dist/queries/bottlenecks.d.ts +6 -2
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +2 -2
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +2 -2
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +2 -2
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +2 -2
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +37 -3
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +2 -2
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +2 -2
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +2 -2
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.d.ts +2 -2
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +6 -2
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +2 -2
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +2 -2
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +10 -3
- package/dist/queries/dead.js +1 -1
- package/dist/queries/deep-chains.d.ts +6 -2
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/deps.d.ts +2 -2
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-gate.d.ts +53 -3
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.d.ts +2 -2
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +20 -3
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +10 -3
- package/dist/queries/drift.js +1 -1
- package/dist/queries/extract-candidates.d.ts +11 -3
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +2 -2
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +2 -2
- package/dist/queries/files.js +1 -1
- package/dist/queries/health.d.ts +3 -3
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +2 -2
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +2 -2
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +2 -2
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +14 -3
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +17 -15
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +2 -2
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.d.ts +51 -0
- package/dist/queries/locality-candidates.js +2 -0
- package/dist/queries/members.d.ts +2 -2
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +2 -2
- package/dist/queries/methods.js +1 -1
- package/dist/queries/outline.d.ts +2 -2
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +8 -3
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +4 -2
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +2 -2
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +9 -3
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +9 -3
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.d.ts +25 -3
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +7 -3
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +2 -2
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.d.ts +2 -2
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.d.ts +2 -2
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.d.ts +2 -2
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.d.ts +2 -2
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +24 -3
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.d.ts +2 -2
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.d.ts +10 -3
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/stats.d.ts +2 -2
- package/dist/queries/stats.js +1 -1
- package/dist/queries/surface.d.ts +2 -2
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.d.ts +2 -2
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +2 -2
- package/dist/queries/system.js +1 -1
- package/dist/queries/trace.d.ts +2 -2
- package/dist/queries/trace.js +1 -1
- package/dist/queries/unused-imports.d.ts +4 -0
- package/dist/queries/unused-imports.js +2 -0
- package/dist/queries/unused-params.d.ts +2 -2
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.d.ts +2 -2
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.d.ts +9 -3
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.d.ts +9 -3
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/queries/wrapper-candidates.d.ts +6 -3
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +1 -1
- package/dist/reindex.d.ts +1 -1
- package/dist/reindex.js +1 -1
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.js +2 -2
- package/docs/COMMAND_REFERENCE.md +3 -2
- package/docs/analyzer-inventory.md +162 -0
- package/docs/analyzer-validation-ledger.md +262 -0
- package/docs/analyzer-validation-protocol.md +192 -0
- package/docs/locality-analyzer-design.md +193 -0
- package/package.json +14 -3
- package/skills/scip-directory-architecture/SKILL.md +178 -0
- package/skills/scip-maintainability/SKILL.md +1 -1
- package/skills/scip-query/SKILL.md +2 -1
- package/skills/scip-query-setup/SKILL.md +118 -0
- package/skills/scip-react-maintainability/SKILL.md +1 -1
- package/skills/scip-vue-maintainability/SKILL.md +1 -1
- package/dist/chunk-23FVN4Y5.js +0 -2
- package/dist/chunk-27KPKLRJ.js +0 -7
- package/dist/chunk-2NLK4INB.js +0 -2
- package/dist/chunk-2XKAMW6B.js +0 -61
- package/dist/chunk-332L7SRO.js +0 -2
- package/dist/chunk-4EAANIWC.js +0 -2
- package/dist/chunk-5ALI77D7.js +0 -3
- package/dist/chunk-5IDEQEM4.js +0 -4
- package/dist/chunk-62NMBOA5.js +0 -2
- package/dist/chunk-64LH2QUP.js +0 -62
- package/dist/chunk-6U4EODW3.js +0 -2
- package/dist/chunk-A2GVUCZR.js +0 -8
- package/dist/chunk-DBIG4QAJ.js +0 -2
- package/dist/chunk-DMLPJ75B.js +0 -2
- package/dist/chunk-DTERBKUE.js +0 -7
- package/dist/chunk-F4PKYBQB.js +0 -2
- package/dist/chunk-JTRY2YRJ.js +0 -2
- package/dist/chunk-L77GXANO.js +0 -6
- package/dist/chunk-LT6GJ27X.js +0 -10
- package/dist/chunk-LUBKUISI.js +0 -2
- package/dist/chunk-LVYXX7ZW.js +0 -2
- package/dist/chunk-LXM7AHQG.js +0 -4
- package/dist/chunk-LY6NRJPJ.js +0 -2
- package/dist/chunk-N2T2GPYQ.js +0 -2
- package/dist/chunk-OB6PEVI3.js +0 -2
- package/dist/chunk-R42LZMLX.js +0 -2
- package/dist/chunk-RGDUIMNE.js +0 -3
- package/dist/chunk-RYBMW2EN.js +0 -2
- package/dist/chunk-TTGWDUJ4.js +0 -5
- package/dist/chunk-UVK3SL4Z.js +0 -2
- package/dist/chunk-W3PQRAI4.js +0 -2
- package/dist/chunk-WWFBDM5Y.js +0 -2
- package/dist/chunk-Y33GRQK6.js +0 -18
- package/dist/chunk-YISMWW66.js +0 -7
package/dist/cli.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{program as
|
|
2
|
+
import{program as is}from"commander";import{realpathSync as Uh}from"fs";import{fileURLToPath as eM}from"url";import{createRequire as q_}from"module";import{fileURLToPath as Yp}from"url";import{statSync as Gh}from"fs";function Ae(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,...zh(e.config.dbPath)}}function zh(e){try{let t=Gh(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function M(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 Kh(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function ss(e,t){let n=Kh(t);return M(e,{like:n,includeIgnored:!1}).map(i=>({relativePath:i}))}import{extname as ml}from"path";var Jh={".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 W(e){return Jh[ml(e).toLowerCase()]??null}function gt(e){return ml(e).toLowerCase()===".vue"}var pl=[];function Et(e){e.groups.length>0&&pl.push(e)}function as(e,t){let n=new Set(t.groups);for(let i of pl)i.groups.some(r=>n.has(r))&&(t.file!==void 0&&i.clearFile?i.clearFile(e,t.file):i.clearAll(e))}function fl(){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}=fl(),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 Et({name:e,groups:t.clearGroups,clearAll:o=>r.invalidateAll(o),clearFile:(o,s)=>r.invalidate(o,s)}),r}function X(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 Et({name:e,groups:t.clearGroups,clearAll:r=>i.invalidate(r)}),i}var Qh={clearGroups:["whole-project","source-file"]};function pr(e){return Ut(e,Qh)}function Ut(e,t){let{cache:n,ensure:i}=fl(),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 Et({name:e,groups:t.clearGroups,clearAll:o=>r.invalidateAll(o),clearFile:(o,s)=>r.invalidate(o,s)}),r}import{createRequire as Xh}from"module";var ve=Xh(import.meta.url),fr=null,gl=!1;function Yh(){if(gl)return null;if(fr)return fr;try{return fr=ve("tree-sitter"),fr}catch{return gl=!0,null}}var hl=new Map,cs=new Set;function Zh(e){if(cs.has(e))return null;let t=hl.get(e);if(t)return t;let n;try{switch(e){case"rust":n=ve("tree-sitter-rust");break;case"typescript":n=ve("tree-sitter-typescript").typescript;break;case"tsx":n=ve("tree-sitter-typescript").tsx;break;case"javascript":n=ve("tree-sitter-javascript");break;case"python":n=ve("tree-sitter-python");break;case"java":n=ve("tree-sitter-java");break;case"kotlin":n=ve("tree-sitter-kotlin");break;case"scala":n=ve("tree-sitter-scala");break;case"ruby":n=ve("tree-sitter-ruby");break;case"c":n=ve("tree-sitter-c");break;case"cpp":n=ve("tree-sitter-cpp");break;case"csharp":n=ve("tree-sitter-c-sharp");break;case"php":n=ve("tree-sitter-php").php;break;case"vb":{let i=ve("tree-sitter-vb-dotnet");n=i.language??i;break}}}catch{return cs.add(e),null}return hl.set(e,n),n}var bl=new Map;function eb(e){let t=bl.get(e);if(t)return t;let n=Zh(e);if(!n)return null;let i=Yh();if(!i)return null;let r=new i;try{r.setLanguage(n)}catch{return cs.add(e),null}return bl.set(e,r),r}function tb(e,t){return e.parse(i=>i>=t.length?null:t.slice(i,Math.min(t.length,i+16384)))}function fi(e,t){let n=eb(e);if(!n)return null;try{return tb(n,t)}catch{return null}}import{existsSync as nb,readFileSync as ib}from"fs";import{join as rb}from"path";var ob=U("source-text",{clearGroups:["whole-project","source-file"]}),sb=U("source-lines",{clearGroups:["whole-project","source-file"]});function A(e,t){let n=t.replace(/\\/g,"/");return ob.get(e,n,()=>{let i=rb(e.config.projectRoot,n);return nb(i)?ib(i,"utf-8"):""})}function Pe(e,t){let n=t.replace(/\\/g,"/");return sb.get(e,n,()=>{let i=A(e,n);return i?i.split(`
|
|
9
|
+
`):[]})}var ab=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar))?\b/i;function gi(e){let t=ab.exec(e);return t?t[1]??"":null}function gr(e,t,n){if(n<=0)return!1;let i=Pe(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(gi(o)!==null)return!0;if(!o.startsWith("//")&&!o.startsWith("*")&&!o.startsWith("/*")&&!o.startsWith("@")&&!o.startsWith("#"))return!1}}return!1}import{parse as pb}from"@vue/compiler-sfc";import{posix as ls}from"path";import{parse as cb}from"@vue/compiler-sfc";var lb=pr("vue-sfc-units");function br(e,t){let n=xl(t),i=A(e,n);return lb.get(e,n,i,()=>ub(e,n,i))}function xl(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function us(e){let t=e?.toLowerCase();return!t||t==="js"||t==="javascript"||t==="jsx"?"javascript":t==="ts"||t==="typescript"?"typescript":t==="tsx"?"tsx":null}function Wt(e){return!e||e.body.length===0?0:e.body.split(`
|
|
10
|
+
`).length}function ub(e,t,n){let i={relativePath:t,template:null,scripts:[],styles:[],customBlocks:[],errors:[]};if(!n)return i;let r;try{r=cb(n,{filename:t})}catch(s){return i.errors.push(Sl(s)),i}i.errors.push(...r.errors.map(Sl));let{descriptor:o}=r;return o.template&&(i.template=hr(e,t,"template",o.template)),o.script&&i.scripts.push(yl(e,t,o.script,!1)),o.scriptSetup&&i.scripts.push(yl(e,t,o.scriptSetup,!0)),i.styles=o.styles.map(s=>hr(e,t,"style",s)),i.customBlocks=o.customBlocks.map(s=>hr(e,t,"custom",s)),i.errors.push(...[i.template,...i.scripts,...i.styles,...i.customBlocks].flatMap(s=>s?.errors??[])),i}function yl(e,t,n,i){let r=hr(e,t,"script",n);return{...r,kind:"script",setup:i,astLanguage:us(r.lang)}}function hr(e,t,n,i){let r=mb(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=db(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=A(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 db(e,t){let n=t.split(/[?#]/,1)[0];if(!n||n.startsWith("/")||n.includes("://"))return null;let i=xl(ls.normalize(ls.join(ls.dirname(e),n)));return i===".."||i.startsWith("../")?null:i}function mb(e){return{...e}}function Sl(e){return e instanceof Error?e.message:String(e)}function yr(e){let t=pb(e),n=t.descriptor.scriptSetup??t.descriptor.script;if(!n||n.src)return null;let i=us(n.lang??null);return i?{body:n.content,startLine:Math.max(0,n.loc.start.line-1),language:i}:null}var Cl=Ut("ast-trees",{clearGroups:["whole-project","source-file"]});function le(e,t){if(gt(t))return fb(e,t);let n=W(t);if(!n)return null;let i=A(e,t);return i?Cl.get(e,t,i,()=>fi(n,i)):null}function fb(e,t){let n=A(e,t);return n?Cl.get(e,t,n,()=>{let i=yr(n);if(!i)return null;let r=`
|
|
12
|
+
`.repeat(i.startLine)+i.body;return fi(i.language,r)}):null}function En(e,t){let n=gb(e,t);if(!n)return null;let i=Nn(n);return i?{calleeLeaf:i,memberAccess:hb(n),line:e.startPosition.row}:null}function gb(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 hb(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function Nn(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?Nn(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?Nn(t):null}case"super":case"self":case"this":return null;default:return null}}import{createHash as bb}from"crypto";import{createRequire as yb}from"module";import{dirname as Sb,join as xb}from"path";import Cb from"better-sqlite3";var vb=yb(import.meta.url),Rb="evidence.db",Sr=new WeakMap,Lb=U("evidence-content-hash",{clearGroups:["whole-project","source-file"]});function wb(){for(let e of["../package.json","../../package.json"])try{return vb(e).version}catch{}return"0.0.0"}var xr=wb();function ds(e){return bb("sha256").update(e).digest("hex")}function Gt(e,t,n){return Lb.get(e,t,()=>ds(n))}function vl(e,t){process.env.SCIP_QUERY_DEBUG&&console.error(`evidence-cache: ${e}: ${t instanceof Error?t.message:String(t)}`)}function hi(e){if(Sr.has(e))return Sr.get(e)??null;let t=null;try{let n=new Cb(xb(Sb(e.config.dbPath),Rb));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,
|
|
@@ -29,15 +29,15 @@ import{program as To}from"commander";import{realpathSync as zf}from"fs";import{f
|
|
|
29
29
|
);
|
|
30
30
|
`),t={evidence:n,readFileEvidence:n.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),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
|
|
31
31
|
WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND version = ?`),writeCallees:n.prepare(`INSERT OR REPLACE INTO semantic_callees
|
|
32
|
-
(relative_path, symbol, content_hash, deps_digest, version, payload) VALUES (?, ?, ?, ?, ?, ?)`),dropStaleCallees:n.prepare("DELETE FROM semantic_callees WHERE relative_path = ? AND content_hash != ?")}}catch(n){_c("disabled (open failed)",n)}return ai.set(e,t),t}function ar(e,t,n){_c(`disabled (${t})`,n),ai.set(e,null)}function li(e,t,n,r){let i=sr(e);if(!i)return null;try{return i.readFileEvidence.get(t,n,r,ci)?.payload??null}catch(o){return ar(e,"file_evidence read",o),null}}function ui(e,t,n,r,i){let o=sr(e);if(o)try{o.writeFileEvidence.run(t,n,r,ci,i)}catch(s){ar(e,"file_evidence write",s)}}function Ec(e){let t=sr(e);if(!t)return 0;try{return t.evidence.prepare("SELECT COUNT(*) AS count FROM semantic_callees").get()?.count??0}catch(n){return ar(e,"semantic_callees count",n),0}}function Fc(e,t,n,r,i){let o=sr(e);if(!o)return null;try{return o.readCallees.get(t,n,r,i,ci)?.payload??null}catch(s){return ar(e,"semantic_callees read",s),null}}function Tc(e,t){if(t.length===0)return;let n=sr(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,ci,i.payload)}})()}catch(r){ar(e,"semantic_callees write",r)}}function cr(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var Pg=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function di(e,t){let n=Eg(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:Mc(n.functionNode),params:Ac(n.functionNode),paramsEndLine:$c(n.functionNode),isLiteralPassthrough:Oc(n.functionNode,t)};if(!_g(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:Mc(e),params:Ac(e),paramsEndLine:$c(e),isLiteralPassthrough:Oc(e,t)}:null}function jc(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function Ac(e){let t=jc(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(cr(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 $c(e){let t=jc(e);return t?t.endPosition.row:e.startPosition.row}function _g(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?Pg.has(e):!1}function Eg(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 Mc(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)cr(r)||(n+=1);return n}function Oc(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=>!cr(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=>!cr(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 Fg=new Set(["identifier","type_identifier","field_identifier"]),Tg=new Set(["identifier"]),Ag=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),$g=new Set(["rust","python"]),Mg=/\{([^{}]*)\}/g,Og=/\b([A-Za-z_][\w]*)\b/g;function Bc(e,t){return jg(t).has(e.type)}function Vc(e,t){return $g.has(t)&&e.type==="string_content"}function Wo(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 jg(e){return e==="rust"?Fg:e==="python"?Tg:Ag}function Hc(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(Mg)){let i=r[1]??"";for(let o of i.matchAll(Og))o[1]&&t(o[1],n)}}var Bg=[/\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],Vg=/^#!?\[\s*serde\s*\(/,Hg=/^#!?\[\s*schemars\s*\(/,qg=/^#!?\[\s*validate\s*\(/,Wg=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function qc(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=Ln(r);if(!i||!Wg.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 Wc(e,t){let n=Vg.test(e),r=Hg.test(e),i=qg.test(e);if(!(!n&&!r&&!i))for(let o of Bg){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 Uc(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 Ug=Bt("source-facts",{clearGroups:["whole-project","source-file"]});function ee(e,t){let n=A(e,t);if(!n)return null;let r=Jg(t,n);return r?Ug.get(e,t,n,()=>Gg(e,t,r,n)):null}function Jg(e,t){return ut(e)?si(t)?.language??null:U(e)}function Gg(e,t,n,r){let i=Ht(e,t,r),o=li(e,"source-facts",t,i);if(o){let c=Kg(o);if(c&&c.language===n)return c}let s=oe(e,t);if(!s)return null;let a=Xg(s,n);return ui(e,"source-facts",t,i,zg(a)),a}function zg(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 Kg(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:Wo(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function Uo(e,t,n,r){let i=ee(e,t);return i?Qg(i,n,r)?.isLiteralPassthrough??!0:!0}function Qg(e,t,n){return e.callables.find(r=>r.startLine===t&&r.endLine===n)??null}function Xg(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=di(l,t);u&&n.push(u);let d=In(l,t);d&&r.push(d),qc(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&Wc(l.text,i),Bc(l,t)&&a(l.text,l.startPosition.row),Vc(l,t)&&Hc(l,a);for(let m of l.children)c(m)};return c(e.rootNode),{language:t,callables:n,callSites:r,typeContainerMap:Uc(e,t),identifierLineMap:s,identifiersByLine:Wo(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:i,crossLanguageDispatchNames:o}}var Jc=new Set(["rust","typescript","tsx","javascript","python"]);function Jo(e,t){let n=ee(e,t);return!n||!Jc.has(n.language)?null:n.callables.map(r=>({name:r.name,startLine:r.startLine,endLine:r.endLine}))}function Dn(e,t){let n=ee(e,t);return!n||!Jc.has(n.language)?null:n.callSites}function Go(e,t){return ee(e,t)?.typeContainerMap??new Map}import{ElementTypes as Yg,NodeTypes as zc,parse as Zg}from"@vue/compiler-dom";import{parse as _F}from"@vue/compiler-sfc";function mi(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var eh=ti("vue-template-facts"),th=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),nh=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"]),rh=new Set(["div","span","template"]),ih=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 Kc(e,t){let n=t.replace(/\\/g,"/"),r=A(e,n);return eh.get(e,n,r,()=>oh(n,oi(e,n).template))}function oh(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=Zg(t.body,{comments:!1})}catch{return n}let i=new Set,o=s=>{s.trim()&&i.add(s)};return Qc(r.children,t.startLine,n,o),n.structuralTokens=[...i].sort(),n}function Qc(e,t,n,r){for(let i of e)i.type===zc.ELEMENT&&(sh(i,t,n,r),Qc(i.children,t,n,r))}function sh(e,t,n,r){let i=fh(e.tag),o={tag:e.tag,normalized:i,kind:ph(e),startLine:kn(t,e.loc.start.line),endLine:kn(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),rh.has(e.tag)||r(`native:${e.tag}`));for(let s of e.props)ah(s,t,n,r)}function ah(e,t,n,r){if(e.type===zc.ATTRIBUTE){let a=e.value?.content??null,c=Gc("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),r(`prop:${e.name}`);return}let i=lh(e),o=Xc(e.exp),s=Gc(ch(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&&uh(o,t,e.loc.start.line,n,r)}function Gc(e,t,n,r,i,o){return{kind:e,name:t,value:n,startLine:kn(r,i),endLine:kn(r,o)}}function ch(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function lh(e){let t=Xc(e.arg);return t||e.name}function Xc(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function uh(e,t,n,r,i){for(let o of dh(e)){let s={name:o,startLine:kn(t,n),endLine:kn(t,n)};r.expressionIdentifiers.push(s),i(`id:${o}`)}}function dh(e){let t=new Set,n=mh(e),r=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,i;for(;i=r.exec(n);){let o=i[0];ih.has(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function mh(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 ph(e){let t=e.tag;return e.tagType===Yg.COMPONENT?"component":th.has(t)?"builtin":nh.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function fh(e){return mi(e,/[-_:]/)}function kn(e,t){return e+Math.max(0,t-1)}import{readdirSync as gh}from"fs";import{execFileSync as hh}from"child_process";import{extname as zo,join as bh}from"path";var yh=[".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"],Yc=[".vue"],Zc=new Set(yh.map(e=>e.toLowerCase())),Sh=[...Zc].sort().join(","),Ko=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function Le(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(c=>c.toLowerCase()),o=i?new Set(i):Zc,s=i?[...o].sort().join(","):Sh,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return xh.get(e,a,()=>{let c=new Set;if(n)for(let l of V(e,{includeIgnored:!1}))o.has(zo(l).toLowerCase())&&c.add(l);if(r)for(let l of Ch(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}var xh=W("source-files",{clearGroups:[]});function Ch(e,t){return vh(e,t)??Rh(e,t)}function vh(e,t){try{let n=hh("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(`
|
|
33
|
-
`)){let o=i.trim();o&&t.has(zo(o).toLowerCase())&&r.add(o)}return r}catch{return null}}function Rh(e,t){let n=new Set,r=i=>{let o=i?bh(e,i):e,s;try{s=gh(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!Ko.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(zo(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}var Lh=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),Ih=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),Dh=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),kh=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),wh=new Set(["catch","for","function","if","return","switch","while"]);function el(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+=Vt(n),n.external&&(t.externalLineCount+=Vt(n),t.externalScriptPaths.push(n.sourcePath));for(let i of n.errors)t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:i});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(...Eh(n));let r=or(n.astLanguage,n.body);r?Ph(n,r.rootNode,t):_h(n,t)}return Nh(t),t.externalScriptPaths=nl(t.externalScriptPaths),t}function Nh(e){e.composables=wn(e,"composable"),e.stores=wn(e,"store"),e.reactivity=wn(e,"reactivity"),e.lifecycle=wn(e,"lifecycle"),e.requests=wn(e,"request"),e.macros=wn(e,"macro")}function wn(e,t){return nl(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function Ph(e,t,n){let r=new Set,i=new Set,o=s=>{let a=di(s,e.astLanguage);if(a){let l=`${a.name}:${a.startLine}:${a.endLine}`;i.has(l)||(i.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=In(s,e.astLanguage);if(c){let l=`${c.calleeLeaf}:${c.line}`;r.has(l)||(r.add(l),n.calls.push({name:c.calleeLeaf,sourcePath:e.sourcePath,line:e.startLine+c.line,categories:tl(c.calleeLeaf),setup:e.setup}))}for(let l of s.children)o(l)};o(t)}function _h(e,t){for(let n of e.body.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)){let r=n[1];!r||wh.has(r)||t.calls.push({name:r,sourcePath:e.sourcePath,line:e.startLine+pi(e.body,n.index??0),categories:tl(r),setup:e.setup})}for(let n of e.body.matchAll(/\bfunction\s+([A-Za-z_$][\w$]*)\b/g)){let r=n[1];if(!r)continue;let i=e.startLine+pi(e.body,n.index??0);t.functions.push({name:r,sourcePath:e.sourcePath,startLine:i,endLine:i,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 r=n[1];if(!r)continue;let i=e.startLine+pi(e.body,n.index??0);t.functions.push({name:r,sourcePath:e.sourcePath,startLine:i,endLine:i,setup:e.setup})}}function Eh(e){let t=[];for(let n of e.body.matchAll(/\bimport\s+(?:type\s+)?([^'";]+?)\s+from\s+['"]([^'"]+)['"]/g)){let r=n[1]?.trim(),i=n[2];if(!r||!i)continue;let o=e.startLine+pi(e.body,n.index??0);for(let s of Fh(r))t.push({local:s,source:i,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function Fh(e){let t=[],r=e.split(",").map(s=>s.trim()).filter(Boolean)[0];r&&!r.startsWith("{")&&!r.startsWith("*")&&t.push(r);let i=/\{([^}]*)\}/.exec(e)?.[1];if(i)for(let s of i.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 tl(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),Lh.has(e)&&t.push("reactivity"),Ih.has(e)&&t.push("lifecycle"),Dh.has(e)&&t.push("request"),kh.has(e)&&t.push("macro"),t}function pi(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}function nl(e){return[...new Set(e)].sort()}var Th=new Set(["in","key","of"]),Ah=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]);function Nn(e,t={}){let n=Le(e,{extensions:[".vue"]}).filter(i=>!t.scope||i.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).map(i=>$h(e,i)).filter(i=>(t.minTemplateTokens===void 0||i.templateTokens.size>=t.minTemplateTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function $h(e,t){let n=t.replace(/\\/g,"/"),r=oi(e,n),i=Kc(e,n),o=el(r),s=Oh(i),a=i.expressionIdentifiers.map(g=>g.name).filter(g=>!s.includes(g)).filter((g,h,b)=>b.indexOf(g)===h).sort(),c=i.componentTags.map(g=>g.normalized).filter((g,h,b)=>b.indexOf(g)===h).sort(),l=dt(e,n).length,u=Vt(r.template),d=o.lineCount,m=r.styles.reduce((g,h)=>g+Vt(h),0),f=r.customBlocks.reduce((g,h)=>g+Vt(h),0);return{file:n,sfc:r,templateFacts:i,scriptFacts:o,templateTokens:new Set(i.structuralTokens),behaviorTokens:Mh(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 Mh(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(Ah.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 Oh(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let r of jh(n.value))t.add(r);for(let n of e.slots)if(n.value)for(let r of rl(n.value))t.add(r);return[...t].sort()}function jh(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?rl(t[1]??""):[]}function rl(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];Th.has(r)||t.push(r)}return t}import{extname as Bh}from"path";var Vh=[".tsx",".jsx"],il=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),Hh=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),qh=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),Wh=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),Uh=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),Jh=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),Gh=new Set(["children","className","false","key","null","style","true","undefined"]),zh=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]);function Pn(e,t={}){let n=Le(e,{extensions:Vh}).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=>Kh(e,i)).filter(i=>(t.minJsxTokens===void 0||i.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function Kh(e,t){let n=t.replace(/\\/g,"/"),r=Qh(n);if(!r)return[];let i=oe(e,n);if(!i)return[];let o=dt(e,n).length;return Xh(i.rootNode,r).filter(a=>a.kind==="hook"||ll(a.bodyNode)).map(a=>{let c=nb(a.bodyNode),l=ab(a.bodyNode,r);return{file:n,name:a.name,kind:a.kind,startLine:a.node.startPosition.row,endLine:a.node.endPosition.row,loc:Math.max(1,a.node.endPosition.row-a.node.startPosition.row+1),fileLines:o,jsxTokens:c.tokens,behaviorTokens:l.tokens,componentNames:mt(c.componentNames),nativeTags:mt(c.nativeTags),propNames:mt(c.propNames),eventNames:mt(c.eventNames),hookNames:mt(l.hookNames),requestNames:mt(l.requestNames),stateNames:mt(l.stateNames),effectNames:mt(l.effectNames),handlerNames:mt(l.handlerNames)}})}function Qh(e){let t=Bh(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:U(e)}function Xh(e,t){let n=[],r=new Set,i=o=>{let s=Yh(o);if(s&&!eb(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 Yh(e){if(e.type==="function_declaration"){let o=cl(e);return!o||!ol(o)?null:{name:o,kind:sl(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=lr(t);if(!r||!n||!ol(r))return null;let i=Zh(n);return i?{name:r,kind:sl(r),node:e,bodyNode:i}:null}function ol(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function sl(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function Zh(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=tb(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 eb(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 cl(e){return lr(e.childForFieldName("name")??e.namedChild(0))}function tb(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function ll(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(ll)}function nb(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"?rb(r,t):r.type==="jsx_expression"?ib(r,t):r.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let i of r.namedChildren)n(i)};return n(e),t}function rb(e,t){let n=ob(e),r=!1;if(n){let i=al(n);r=mb(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=sb(i);if(!o)continue;let s=al(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 zh.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 ib(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 pb(n))Gh.has(r)||t.tokens.add(`binding:${r}`)}function ob(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 sb(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 ab(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=In(i,t);o&&cb(o.calleeLeaf,n)}else if(i.type==="variable_declarator")ub(i,n);else if(i.type==="function_declaration"){let o=cl(i);o&&ul(o,n)}for(let o of i.namedChildren)r(o)};return r(e),n}function cb(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!il.has(e)&&!Wh.has(e)&&t.tokens.add(`hook:${e}`)),il.has(e)&&t.tokens.add(`react-hook:${e}`),Hh.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),qh.has(e)&&t.tokens.add(`state-hook:${e}`),lb(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function lb(e){if(Uh.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function ub(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=>lr(a)),s=lr(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let i=lr(n);i&&ul(i,t)}function ul(e,t){let n=db(e);!n||!Jh.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function db(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 mb(e){return/^[A-Z]/.test(e)||e.includes(".")}function al(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function lr(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 pb(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 mt(e){return[...e].sort()}function qt(e,t,n={}){let r=ee(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 fb={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function se(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=gb(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function Xe(e){let t=se(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 gb(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||dl(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&&!dl(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=fb[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function dl(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function y(e){let t=se(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=hb(i);o&&r.push(o)}return r.join(":")}function hb(e){let t=e.suffix==="namespace"?bb(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function bb(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=se(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 ae(e){let t=se(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function pe(e){return e.endsWith("().")||ae(e)==="method"}function te(e){let t=ae(e);return t==="method"||t==="term"}function wt(e){return ae(e)==="namespace"}var yb=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function fi(e){return yb.test(e)}var Sb=new Set(["test","tests","_tests"]);function _n(e){let t=se(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&&Sb.has(r.name))return!0}return!1}function ml(e,t){let n=se(e),r=se(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 pl(e,t){let n=se(e),r=se(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 En(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
|
|
32
|
+
(relative_path, symbol, content_hash, deps_digest, version, payload) VALUES (?, ?, ?, ?, ?, ?)`),dropStaleCallees:n.prepare("DELETE FROM semantic_callees WHERE relative_path = ? AND content_hash != ?")}}catch(n){vl("disabled (open failed)",n)}return Sr.set(e,t),t}function bi(e,t,n){vl(`disabled (${t})`,n),Sr.set(e,null)}function Cr(e,t,n,i){let r=hi(e);if(!r)return null;try{return r.readFileEvidence.get(t,n,i,xr)?.payload??null}catch(o){return bi(e,"file_evidence read",o),null}}function vr(e,t,n,i,r){let o=hi(e);if(o)try{o.writeFileEvidence.run(t,n,i,xr,r)}catch(s){bi(e,"file_evidence write",s)}}function Rl(e){let t=hi(e);if(!t)return 0;try{return t.evidence.prepare("SELECT COUNT(*) AS count FROM semantic_callees").get()?.count??0}catch(n){return bi(e,"semantic_callees count",n),0}}function Ll(e,t,n,i,r){let o=hi(e);if(!o)return null;try{return o.readCallees.get(t,n,i,r,xr)?.payload??null}catch(s){return bi(e,"semantic_callees read",s),null}}function wl(e,t){if(t.length===0)return;let n=hi(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,xr,r.payload)}})()}catch(i){bi(e,"semantic_callees write",i)}}function yi(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var kb=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function Rr(e,t){let n=Ib(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:Il(n.functionNode),params:kl(n.functionNode),paramsEndLine:Dl(n.functionNode),isLiteralPassthrough:Nl(n.functionNode,t)};if(!Db(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:Il(e),params:kl(e),paramsEndLine:Dl(e),isLiteralPassthrough:Nl(e,t)}:null}function El(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function kl(e){let t=El(e);if(!t)return[];let n=[];for(let i of t.namedChildren){if(yi(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 Dl(e){let t=El(e);return t?t.endPosition.row:e.startPosition.row}function Db(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?kb.has(e):!1}function Ib(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 Il(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)yi(i)||(n+=1);return n}function Nl(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=>!yi(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=>!yi(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 Nb=new Set(["identifier","type_identifier","field_identifier"]),Eb=new Set(["identifier"]),Pb=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),_b=new Set(["rust","python"]),Tb=/\{([^{}]*)\}/g,Fb=/\b([A-Za-z_][\w]*)\b/g;function Pl(e,t){return $b(t).has(e.type)}function _l(e,t){return _b.has(t)&&e.type==="string_content"}function ms(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 $b(e){return e==="rust"?Nb:e==="python"?Eb:Pb}function Tl(e,t){let n=e.startPosition.row;for(let i of e.text.matchAll(Tb)){let r=i[1]??"";for(let o of r.matchAll(Fb))o[1]&&t(o[1],n)}}var Ab=[/\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],Mb=/^#!?\[\s*serde\s*\(/,Ob=/^#!?\[\s*schemars\s*\(/,jb=/^#!?\[\s*validate\s*\(/,Bb=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function Fl(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=Nn(i);if(!r||!Bb.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 $l(e,t){let n=Mb.test(e),i=Ob.test(e),r=jb.test(e);if(!(!n&&!i&&!r))for(let o of Ab){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 Al(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 Hb=Ut("source-facts",{clearGroups:["whole-project","source-file"]});function re(e,t){let n=A(e,t);if(!n)return null;let i=Vb(t,n);return i?Hb.get(e,t,n,()=>qb(e,t,i,n)):null}function Vb(e,t){return gt(e)?yr(t)?.language??null:W(e)}function qb(e,t,n,i){let r=Gt(e,t,i),o=Cr(e,"source-facts",t,r);if(o){let c=Wb(o);if(c&&c.language===n)return c}let s=le(e,t);if(!s)return null;let a=zb(s,n);return vr(e,"source-facts",t,r,Ub(a)),a}function Ub(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 Wb(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:ms(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function ps(e,t,n,i){let r=re(e,t);return r?Gb(r,n,i)?.isLiteralPassthrough??!0:!0}function Gb(e,t,n){return e.callables.find(i=>i.startLine===t&&i.endLine===n)??null}function zb(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=Rr(l,t);u&&n.push(u);let d=En(l,t);d&&i.push(d),Fl(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&$l(l.text,r),Pl(l,t)&&a(l.text,l.startPosition.row),_l(l,t)&&Tl(l,a);for(let m of l.children)c(m)};return c(e.rootNode),{language:t,callables:n,callSites:i,typeContainerMap:Al(e,t),identifierLineMap:s,identifiersByLine:ms(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:r,crossLanguageDispatchNames:o}}var Ml=new Set(["rust","typescript","tsx","javascript","python"]);function fs(e,t){let n=re(e,t);return!n||!Ml.has(n.language)?null:n.callables.map(i=>({name:i.name,startLine:i.startLine,endLine:i.endLine}))}function Pn(e,t){let n=re(e,t);return!n||!Ml.has(n.language)?null:n.callSites}function gs(e,t){return re(e,t)?.typeContainerMap??new Map}import{ElementTypes as Kb,NodeTypes as jl,parse as Jb}from"@vue/compiler-dom";import{parse as lO}from"@vue/compiler-sfc";function Lr(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var Qb=pr("vue-template-facts"),Xb=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),Yb=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"]),Zb=new Set(["div","span","template"]),ey=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 Bl(e,t){let n=t.replace(/\\/g,"/"),i=A(e,n);return Qb.get(e,n,i,()=>ty(n,br(e,n).template))}function ty(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=Jb(t.body,{comments:!1})}catch{return n}let r=new Set,o=s=>{s.trim()&&r.add(s)};return Hl(i.children,t.startLine,n,o),n.structuralTokens=[...r].sort(),n}function Hl(e,t,n,i){for(let r of e)r.type===jl.ELEMENT&&(ny(r,t,n,i),Hl(r.children,t,n,i))}function ny(e,t,n,i){let r=uy(e.tag),o={tag:e.tag,normalized:r,kind:ly(e),startLine:_n(t,e.loc.start.line),endLine:_n(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),Zb.has(e.tag)||i(`native:${e.tag}`));for(let s of e.props)iy(s,t,n,i)}function iy(e,t,n,i){if(e.type===jl.ATTRIBUTE){let a=e.value?.content??null,c=Ol("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),i(`prop:${e.name}`);return}let r=oy(e),o=Vl(e.exp),s=Ol(ry(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&&sy(o,t,e.loc.start.line,n,i)}function Ol(e,t,n,i,r,o){return{kind:e,name:t,value:n,startLine:_n(i,r),endLine:_n(i,o)}}function ry(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function oy(e){let t=Vl(e.arg);return t||e.name}function Vl(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function sy(e,t,n,i,r){for(let o of ay(e)){let s={name:o,startLine:_n(t,n),endLine:_n(t,n)};i.expressionIdentifiers.push(s),r(`id:${o}`)}}function ay(e){let t=new Set,n=cy(e),i=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,r;for(;r=i.exec(n);){let o=r[0];ey.has(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function cy(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 ly(e){let t=e.tag;return e.tagType===Kb.COMPONENT?"component":Xb.has(t)?"builtin":Yb.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function uy(e){return Lr(e,/[-_:]/)}function _n(e,t){return e+Math.max(0,t-1)}import{readdirSync as dy}from"fs";import{execFileSync as my}from"child_process";import{extname as hs,join as py}from"path";var fy=[".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"],ql=[".vue"],Ul=new Set(fy.map(e=>e.toLowerCase())),gy=[...Ul].sort().join(","),bs=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function we(e,t={}){let n=t.includeIndexed??!0,i=t.includeAuxiliary??!0,r=t.extensions?.map(c=>c.toLowerCase()),o=r?new Set(r):Ul,s=r?[...o].sort().join(","):gy,a=`${n?"1":"0"}|${i?"1":"0"}|${s}`;return hy.get(e,a,()=>{let c=new Set;if(n)for(let l of M(e,{includeIgnored:!1}))o.has(hs(l).toLowerCase())&&c.add(l);if(i)for(let l of by(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}var hy=U("source-files",{clearGroups:[]});function by(e,t){return yy(e,t)??Sy(e,t)}function yy(e,t){try{let n=my("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(`
|
|
33
|
+
`)){let o=r.trim();o&&t.has(hs(o).toLowerCase())&&i.add(o)}return i}catch{return null}}function Sy(e,t){let n=new Set,i=r=>{let o=r?py(e,r):e,s;try{s=dy(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!bs.has(a.name)){if(a.isDirectory()){i(r?`${r}/${a.name}`:a.name);continue}t.has(hs(a.name).toLowerCase())&&n.add(r?`${r}/${a.name}`:a.name)}};return i(""),n}var xy=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),Cy=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),vy=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),Ry=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),Ly=new Set(["catch","for","function","if","return","switch","while"]);function Wl(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+=Wt(n),n.external&&(t.externalLineCount+=Wt(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(...Iy(n));let i=fi(n.astLanguage,n.body);i?ky(n,i.rootNode,t):Dy(n,t)}return wy(t),t.externalScriptPaths=zl(t.externalScriptPaths),t}function wy(e){e.composables=Tn(e,"composable"),e.stores=Tn(e,"store"),e.reactivity=Tn(e,"reactivity"),e.lifecycle=Tn(e,"lifecycle"),e.requests=Tn(e,"request"),e.macros=Tn(e,"macro")}function Tn(e,t){return zl(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function ky(e,t,n){let i=new Set,r=new Set,o=s=>{let a=Rr(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=En(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:Gl(c.calleeLeaf),setup:e.setup}))}for(let l of s.children)o(l)};o(t)}function Dy(e,t){for(let n of e.body.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)){let i=n[1];!i||Ly.has(i)||t.calls.push({name:i,sourcePath:e.sourcePath,line:e.startLine+wr(e.body,n.index??0),categories:Gl(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+wr(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+wr(e.body,n.index??0);t.functions.push({name:i,sourcePath:e.sourcePath,startLine:r,endLine:r,setup:e.setup})}}function Iy(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+wr(e.body,n.index??0);for(let s of Ny(i))t.push({local:s,source:r,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function Ny(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 Gl(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),xy.has(e)&&t.push("reactivity"),Cy.has(e)&&t.push("lifecycle"),vy.has(e)&&t.push("request"),Ry.has(e)&&t.push("macro"),t}function wr(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 zl(e){return[...new Set(e)].sort()}var Ey=new Set(["in","key","of"]),Py=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]);function Fn(e,t={}){let n=we(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=>_y(e,r)).filter(r=>(t.minTemplateTokens===void 0||r.templateTokens.size>=t.minTemplateTokens)&&(t.minBehaviorTokens===void 0||r.behaviorTokens.size>=t.minBehaviorTokens))}function _y(e,t){let n=t.replace(/\\/g,"/"),i=br(e,n),r=Bl(e,n),o=Wl(i),s=Fy(r),a=r.expressionIdentifiers.map(h=>h.name).filter(h=>!s.includes(h)).filter((h,g,b)=>b.indexOf(h)===g).sort(),c=r.componentTags.map(h=>h.normalized).filter((h,g,b)=>b.indexOf(h)===g).sort(),l=Pe(e,n).length,u=Wt(i.template),d=o.lineCount,m=i.styles.reduce((h,g)=>h+Wt(g),0),p=i.customBlocks.reduce((h,g)=>h+Wt(g),0);return{file:n,sfc:i,templateFacts:r,scriptFacts:o,templateTokens:new Set(r.structuralTokens),behaviorTokens:Ty(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 Ty(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(Py.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 Fy(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let i of $y(n.value))t.add(i);for(let n of e.slots)if(n.value)for(let i of Kl(n.value))t.add(i);return[...t].sort()}function $y(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?Kl(t[1]??""):[]}function Kl(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let i=n[0];Ey.has(i)||t.push(i)}return t}import{extname as Ay}from"path";var My=[".tsx",".jsx"],Jl=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),Oy=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),jy=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),By=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),Hy=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),Vy=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),qy=new Set(["children","className","false","key","null","style","true","undefined"]),Uy=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]);function $n(e,t={}){let n=we(e,{extensions:My}).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=>Wy(e,r)).filter(r=>(t.minJsxTokens===void 0||r.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||r.behaviorTokens.size>=t.minBehaviorTokens))}function Wy(e,t){let n=t.replace(/\\/g,"/"),i=Gy(n);if(!i)return[];let r=le(e,n);if(!r)return[];let o=Pe(e,n).length;return zy(r.rootNode,i).filter(a=>a.kind==="hook"||eu(a.bodyNode)).map(a=>{let c=Yy(a.bodyNode),l=iS(a.bodyNode,i);return{file:n,name:a.name,kind:a.kind,startLine:a.node.startPosition.row,endLine:a.node.endPosition.row,loc:Math.max(1,a.node.endPosition.row-a.node.startPosition.row+1),fileLines:o,jsxTokens:c.tokens,behaviorTokens:l.tokens,componentNames:ht(c.componentNames),nativeTags:ht(c.nativeTags),propNames:ht(c.propNames),eventNames:ht(c.eventNames),hookNames:ht(l.hookNames),requestNames:ht(l.requestNames),stateNames:ht(l.stateNames),effectNames:ht(l.effectNames),handlerNames:ht(l.handlerNames)}})}function Gy(e){let t=Ay(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:W(e)}function zy(e,t){let n=[],i=new Set,r=o=>{let s=Ky(o);if(s&&!Qy(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 Ky(e){if(e.type==="function_declaration"){let o=Zl(e);return!o||!Ql(o)?null:{name:o,kind:Xl(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=Si(t);if(!i||!n||!Ql(i))return null;let r=Jy(n);return r?{name:i,kind:Xl(i),node:e,bodyNode:r}:null}function Ql(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function Xl(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function Jy(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=Xy(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 Qy(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 Zl(e){return Si(e.childForFieldName("name")??e.namedChild(0))}function Xy(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function eu(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(eu)}function Yy(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"?Zy(i,t):i.type==="jsx_expression"?eS(i,t):i.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let r of i.namedChildren)n(r)};return n(e),t}function Zy(e,t){let n=tS(e),i=!1;if(n){let r=Yl(n);i=cS(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=nS(r);if(!o)continue;let s=Yl(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 Uy.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 eS(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 lS(n))qy.has(i)||t.tokens.add(`binding:${i}`)}function tS(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 nS(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 iS(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=En(r,t);o&&rS(o.calleeLeaf,n)}else if(r.type==="variable_declarator")sS(r,n);else if(r.type==="function_declaration"){let o=Zl(r);o&&tu(o,n)}for(let o of r.namedChildren)i(o)};return i(e),n}function rS(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!Jl.has(e)&&!By.has(e)&&t.tokens.add(`hook:${e}`)),Jl.has(e)&&t.tokens.add(`react-hook:${e}`),Oy.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),jy.has(e)&&t.tokens.add(`state-hook:${e}`),oS(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function oS(e){if(Hy.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function sS(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=>Si(a)),s=Si(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let r=Si(n);r&&tu(r,t)}function tu(e,t){let n=aS(e);!n||!Vy.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function aS(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 cS(e){return/^[A-Z]/.test(e)||e.includes(".")}function Yl(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function Si(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 lS(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 ht(e){return[...e].sort()}function zt(e,t,n={}){let i=re(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 uS={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function ue(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=dS(r);return{scheme:n,manager:i,packageName:o,version:s,descriptors:c,raw:e}}function et(e){let t=ue(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 dS(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||nu(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&&!nu(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=uS[r];o&&t.push({name:i,suffix:o}),n+=1}}return t}function nu(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function y(e){let t=ue(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=mS(r);o&&i.push(o)}return i.join(":")}function mS(e){let t=e.suffix==="namespace"?pS(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function pS(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 F(e){let t=ue(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 Y(e){let t=ue(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function be(e){return e.endsWith("().")||Y(e)==="method"}function oe(e){let t=Y(e);return t==="method"||t==="term"}function Pt(e){return Y(e)==="namespace"}var fS=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function kr(e){return fS.test(e)}var gS=new Set(["test","tests","_tests"]);function An(e){let t=ue(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&&gS.has(i.name))return!0}return!1}function iu(e,t){let n=ue(e),i=ue(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 ru(e,t){let n=ue(e),i=ue(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 Mn(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
|
|
34
34
|
FROM global_symbols gs
|
|
35
35
|
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
36
36
|
JOIN documents d ON der.document_id = d.id
|
|
37
37
|
WHERE ${t.where}
|
|
38
38
|
${e.pathExclusionsFor("d")}
|
|
39
|
-
${
|
|
40
|
-
${
|
|
39
|
+
${su(t.orderBy)}
|
|
40
|
+
${au(t.limit)}`,...t.params??[])}function On(e,t){return e.all(`SELECT
|
|
41
41
|
gs.id,
|
|
42
42
|
gs.symbol,
|
|
43
43
|
c.document_id,
|
|
@@ -54,8 +54,8 @@ import{program as To}from"commander";import{realpathSync as zf}from"fs";import{f
|
|
|
54
54
|
AND ${t.where}
|
|
55
55
|
${e.pathExclusionsFor("d")}
|
|
56
56
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
|
|
57
|
-
${
|
|
58
|
-
${
|
|
57
|
+
${su(t.orderBy)}
|
|
58
|
+
${au(t.limit)}`,...t.params??[])}function su(e){return e?`ORDER BY ${e}`:""}function au(e){return typeof e=="number"?`LIMIT ${e}`:""}function Kt(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 Jt(e){if(!e)return null;let t=ou(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(ou(i)??i).replace(/\n/g," ")}function ou(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function hS(e){if(et(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 jn(e,t,n={}){let i=new Map;for(let o of t)e.length>0&&!hS(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 bS=U("file-definitions",{clearGroups:["definition-catalog"]}),cu=new WeakMap;function G(e,t){return bS.get(e,t,()=>{let n=jn(yS(e,t),SS(e,t),{sort:!0});return CS(e,t,n.map(xS))})}function yS(e,t){return e.all(`SELECT
|
|
59
59
|
gs.id,
|
|
60
60
|
gs.symbol,
|
|
61
61
|
der.document_id,
|
|
@@ -71,7 +71,7 @@ import{program as To}from"commander";import{realpathSync as zf}from"fs";import{f
|
|
|
71
71
|
JOIN documents d ON der.document_id = d.id
|
|
72
72
|
WHERE d.relative_path = ?
|
|
73
73
|
${e.symbolNoiseFor("gs")}
|
|
74
|
-
ORDER BY der.start_line, der.end_line`,t)}function
|
|
74
|
+
ORDER BY der.start_line, der.end_line`,t)}function SS(e,t){return e.all(`SELECT
|
|
75
75
|
gs.id,
|
|
76
76
|
gs.symbol,
|
|
77
77
|
c.document_id,
|
|
@@ -90,10 +90,10 @@ import{program as To}from"commander";import{realpathSync as zf}from"fs";import{f
|
|
|
90
90
|
AND m.role = 1
|
|
91
91
|
${e.symbolNoiseFor("gs")}
|
|
92
92
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
93
|
-
ORDER BY start_line, end_line`,t)}function
|
|
94
|
-
AND `),o=En(e,{where:i,params:r,limit:200}),s=Fn(e,{where:i,params:r,limit:200});return Tn(o,s)}function Gb(e,t,n,r){let i=t.trim(),o=n,s=o.replace(/\(\)$/,""),a=t.toLowerCase(),c=n.toLowerCase(),l=c.replace(/\(\)$/,""),u=e.symbol,d=y(e.symbol),m=$(e.symbol),f=e.display_name??"",g=e.symbol.toLowerCase(),h=d.toLowerCase(),b=m.toLowerCase(),L=f.toLowerCase(),F=e.relative_path.toLowerCase(),k=/[/:.]/.test(n),E=Xo(n),C=E?.leaf.toLowerCase(),w=0;return(u===i||u===o)&&(w+=1150),(d===i||d===o)&&(w+=1100),f===s&&(w+=1180),m===s&&(w+=1160),(`${m}()`===i||`${m}()`===o)&&(w+=955),(g===a||g===c)&&(w+=1e3),(h===a||h===c)&&(w+=950),(F===a||F===c)&&(w+=925),(F.endsWith(`/${c}`)||F.endsWith(`/${a}`))&&(w+=875),L===l&&(w+=850),b===l&&(w+=825),(`${b}()`===a||`${b}()`===c)&&(w+=820),(h.endsWith(`:${c}`)||h.endsWith(`:${l}`)||h.endsWith(`:${l}()`))&&(w+=800),g.includes(c)&&(w+=120),h.includes(c)&&(w+=140),F.includes(c)&&(w+=140),L.includes(c)&&(w+=110),r.every(M=>{let j=M.toLowerCase();return g.includes(j)||h.includes(j)||F.includes(j)||L.includes(j)})&&(w+=100+r.length*15),E&&F.includes(E.path.toLowerCase())&&(w+=360,C&&(b===C||`${b}()`===C||`${b}()`==`${C}()`)&&(w+=700),pe(e.symbol)&&(w+=180)),te(e.symbol)&&b===l&&(w+=60),!k&&wt(e.symbol)&&(w-=160),w-=Math.min(50,Math.max(0,e.end_line-e.start_line)),w}function Xo(e){let t=e.trim().replace(/\\/g,"/"),n=t.lastIndexOf("/");if(n<=0||n===t.length-1)return null;let r=t.slice(n+1).replace(/\(\)$/,"");return!r||r.includes(".")?null:{path:t.slice(0,n),leaf:r}}function Yo(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function zb(e){let t=Yo(e),n=t.split(/[^A-Za-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>0);return n.length>0?[...new Set(n)]:[t]}function Kb(e,t,n){let r=t.trim(),i=e.filter(o=>{let s=y(o.symbol),a=(o.display_name??"").trim();return o.symbol===r||s===r||s===n||a===r||a===n||`${a}()`===r||An(o,n)>1||o.relative_path===r});return i.length===0?null:(i.sort((o,s)=>An(s,n)-An(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)),i[0]??null)}function An(e,t){let n=Xo(t);if(!n)return 0;let r=e.relative_path.toLowerCase(),i=$(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return r.includes(o)?i!==s?1:pe(e.symbol)?Xe(e.symbol)===null?5:4:Xe(e.symbol)===null?3:2:0}function Ie(e,t){let n=xl(e,t,{allowMultiple:!1})[0]?.relativePath;return n||Zb(e,t)}function Mn(e,t){return xl(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function Zb(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=Xb(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=Yb(e.config.projectRoot,r);return Qb(i)?r:null}function xl(e,t,n){let r=Cl(t);if(!r)return[];let i=V(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:ey(a,r)})).filter(a=>a.score>0).sort((a,c)=>c.score-a.score||a.relativePath.localeCompare(c.relativePath));if(i.length===0){let a=B(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}let o=i.filter(a=>a.score>=1100);if(o.length>0)return n.allowMultiple?o:[o[0]];let s=i.filter(a=>a.score>=800);return s.length>0?n.allowMultiple?s:[s[0]]:n.allowMultiple?i:[i[0]]}function ey(e,t){let n=Cl(e),r=Sl(n),i=Sl(t),o=0;return n===t&&(o+=1200),n.endsWith(`/${t}`)&&(o+=1100),r===i&&(o+=900),n.startsWith(`${t}/`)&&(o+=850),n.includes(t)&&(o+=250),o}function Cl(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{basename as rC}from"path";import{existsSync as Si}from"fs";import{basename as ty,dirname as Nt,extname as pt,join as We,relative as dr,resolve as $e}from"path";var ny=ie("indexed-paths",{clearGroups:[]}),Gt=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],xi=[".py",".pyi"],Ne=[".java",".scala",".kt",".kts"],Ci=[".rs"],vi=[".rb"],Ri=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],Pt=[".cs",".vb"],Li=[".dart"],zt=[".php"],ry=new Set(Gt),Zo=new Set(xi),vl=new Set(Ne),es=new Set(Ci),ts=new Set(vi),Rl=new Set(Ri),Ll=new Set(Pt),ns=new Set(Li),Il=new Set(zt),iy=[{extensions:Gt,lookup:ry},{extensions:xi,lookup:Zo},{extensions:Ne,lookup:vl},{extensions:Ci,lookup:es},{extensions:vi,lookup:ts},{extensions:Ri,lookup:Rl},{extensions:Pt,lookup:Ll},{extensions:Li,lookup:ns},{extensions:zt,lookup:Il}];function _t(e,t){return t.has(pt(e).toLowerCase())}function oy(e){return _t(e,Zo)}function sy(e){return _t(e,vl)}function ay(e){return _t(e,es)}function cy(e){return _t(e,ts)}function ly(e){return _t(e,Rl)}function uy(e){return _t(e,Ll)}function Dl(e){return pt(e).toLowerCase()===".vb"}function dy(e){return _t(e,ns)}function my(e){return _t(e,Il)}function rs(e){let t=pt(e).toLowerCase();for(let n of iy)if(n.lookup.has(t))return n.extensions;return Gt}function py(e){return sy(e)||uy(e)||my(e)}function Je(e,t,n){return oy(t)?On(e,t,n):ay(t)?ft(e,t,n):cy(t)?Ii(e,t,n):ly(t)?Di(e,t,n):py(t)?Q(e,n.replace(/\\/g,"."),rs(t)):dy(t)?ki(e,t,n):fy(e,t,n)}function fy(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let r=Nt(We(e.config.projectRoot,t)),i=$e(r,n),o=mr(e);for(let s of Sy(i)){let a=Ue(dr(e.config.projectRoot,s));if(o.has(a)||Si(s))return a}return Ue(dr(e.config.projectRoot,i))}function On(e,t,n){let r=mr(e),i;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=Nt(We(e.config.projectRoot,t));for(let l=1;l<s;l++)c=Nt(c);i=a?$e(c,a.replace(/\./g,"/")):c}else i=$e(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of gy(i)){let s=Ue(dr(e.config.projectRoot,o));if(r.has(s)||Si(o))return s}return null}function ft(e,t,n){if(!n)return null;let r=n.replace(/\s+as\s+.+$/,"").trim();if(!r.startsWith("crate::")&&!r.startsWith("self::")&&!r.startsWith("super::"))return null;let i=Nt(We(e.config.projectRoot,t)),o;return r.startsWith("crate::")?o=$e(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?o=$e(i,r.slice(6).replace(/::/g,"/")):o=$e(Nt(i),r.slice(7).replace(/::/g,"/")),is(e,hy(o))}function Ii(e,t,n){let r=Nt(We(e.config.projectRoot,t)),i=$e(r,n);return is(e,by(i))}function Di(e,t,n){let r=Nt(We(e.config.projectRoot,t)),i=[$e(r,n),$e(e.config.projectRoot,n),$e(e.config.projectRoot,"include",n),$e(e.config.projectRoot,"src",n)];return is(e,i)}function Q(e,t,n){let r=mr(e),i=t.replace(/\\/g,".").replace(/::/g,".").replace(/^global::/,""),o=i.replace(/\./g,"/"),s=i.split(".").pop()??i;for(let c of n){let l=`${o}${c}`,u=[...r].find(d=>d.endsWith(l));if(u)return u}for(let c of n){let l=[...r].find(u=>ty(u)===`${s}${c}`);if(l)return l}let a=[...r].filter(c=>n.includes(pt(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function ki(e,t,n){let r=mr(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=Ue(c.startsWith("lib/")?c:`lib/${c}`);return r.has(l)?l:null}let i=Nt(We(e.config.projectRoot,t)),o=$e(i,n);for(let s of yy(o)){let a=Ue(dr(e.config.projectRoot,s));if(r.has(a)||Si(s))return a}return null}function gy(e){let t=pt(e);return Zo.has(t)?[e]:[`${e}.py`,`${e}.pyi`,We(e,"__init__.py"),We(e,"__init__.pyi")]}function is(e,t){let n=mr(e);for(let r of t){let i=Ue(dr(e.config.projectRoot,r));if(n.has(i)||Si(r))return i}return null}function hy(e){let t=pt(e);return es.has(t)?[e]:[`${e}.rs`,We(e,"mod.rs")]}function by(e){let t=pt(e);return ts.has(t)?[e]:[`${e}.rb`,We(e,"index.rb")]}function yy(e){let t=pt(e);return ns.has(t)?[e]:[`${e}.dart`,e]}function Sy(e){let t=pt(e),n=new Set;if(t){n.add(e);for(let r of Gt)n.add(e.slice(0,-t.length)+r)}else for(let r of Gt)n.add(`${e}${r}`),n.add(We(e,`index${r}`));return[...n]}function mr(e){return ny.get(e,()=>new Set(V(e,{includeIgnored:!1}).map(Ue)))}function Ue(e){return e.replace(/\\/g,"/")}import{basename as wl}from"path";function Kt(e){return e.replace(/'''[\s\S]*?'''/g,Et).replace(/"""[\s\S]*?"""/g,Et).replace(/#.*$/gm,Et).replace(/\/\/.*$/gm,Et).replace(/\/\*[\s\S]*?\*\//g,Et).replace(/`(?:\\[\s\S]|[^`])*`/g,Et).replace(/'(?:\\.|[^'\\\r\n])*'/g,Et).replace(/"(?:\\.|[^"\\\r\n])*"/g,Et)}function Et(e){return e.replace(/[^\r\n]/g," ")}var zT=Bt("stripped-lines",{clearGroups:["whole-project","source-file"]});kt({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{wi=null,pr=""},clearFile:()=>{wi=null,pr=""}});var wi=null,pr="";function xy(e){return wi===e||(wi=e,pr=Kt(e)),pr}function Ft(e,t,n){let r=xy(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function De(e,t){return new RegExp(`\\b${kl(t)}\\b`,"m").test(e)}function jn(e,t){let n=new Set,r=new RegExp(`\\b${kl(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 kl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fr(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var Cy=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function ke(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 Pe(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function X(e,t){let n=new Set,r=(i,o)=>{let s=o||t.has(i.type);!s&&Cy.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,s)};return r(e.rootNode,!1),n}function Ze(e,t,n,r,i,o,s){return{importedName:i,localName:o,sourcePath:s??Q(e,r,rs(t)),kind:"named",used:De(n,o),usedMembers:[]}}function K(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 Bn(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 Qt(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function Xt(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 Me(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=Ft(e,i.index,i.index+o.length);for(let a of n(i,s))r.push(a)}return r}function Oe(e,t,n,r){let i=oe(e,t);if(i){let o=n(i);if(o)return o}return r()}function Ni(e,t,n,r){let i=oe(e,t),o=U(t),s=o?n[o]:void 0;return i&&s?s(i):r()}function Nl(e,t,n){return Oe(e,t,r=>Ry(e,t,r),()=>vy(e,t,n))}function vy(e,t,n){return Me(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=wl(o).replace(/\.[^.]+$/,"");return[Bn(o,s,Di(e,t,o),De(i,s))]})}function Ry(e,t,n){let r=X(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=wl(s).replace(/\.[^.]+$/,"");i.push(K(s,a,Di(e,t,s),r))}return i}function Pl(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=Ft(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:ki(e,t,o),kind:s?"namespace":"side-effect",used:s?De(c,s):!0,usedMembers:s?jn(c,s):[]})}return r}function _l(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:ki(e,t,o)})}return r}function El(e,t,n){return Ni(e,t,{csharp:r=>Iy(e,t,r),vb:r=>Ly(e,t,r)},()=>{let r=Dl(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return Me(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[Ze(e,t,o,u,d,m,Q(e,u,Pt))]})})}function Ly(e,t,n){let r=X(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(K(u,d,Q(e,l,Pt),r,c?"namespace":"named"))}return i}function Iy(e,t,n){let r=X(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(K(u,d,Q(e,l,Pt),r,a?"namespace":"named"))}return i}var Dy=W("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function Fl(e,t){return Dy.get(e,t,()=>{let n=new Set,r=A(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 os(e,t,n){return Oe(e,t,r=>wy(e,t,r),()=>ky(e,t,n))}function ky(e,t,n){return jy(n).flatMap(r=>By(e,t,r.clause,r.specifier,r.start,r.end,n))}function wy(e,t,n){let r=Ny(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...Py(e,t,n,o,r));return i}function Ny(e,t,n){let r=X(n,new Set(["import_statement"]));if(ut(t))for(let i of Fl(e,t))r.add(i);return r}function Py(e,t,n,r,i){let o=Ay(r);if(!o)return[];let s=Je(e,t,o),a=Pe(r,"import_clause");return a?_y(n,a,s,i,$y(r.text)):[Qt("*",s)]}function _y(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(Ey(s.text,n,r,i));else if(s.type==="namespace_import"){let a=Fy(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...Ty(s,n,r,i));return o}function Ey(e,t,n,r){return K("default",e,t,n,"default",{isTypeOnly:r})}function Fy(e,t,n,r,i){let s=Pe(t,"identifier")?.text??"";if(!s)return null;let a=Oy(e,s);return Xt("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function Ty(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(K(c,l,t,n,"named",{isTypeOnly:r||My(o.text)}))}return i}function Ay(e){let t=Pe(e,"string");if(!t)return null;let n=Pe(t,"string_fragment");return n?n.text:null}function $y(e){return/^\s*import\s+type\b/.test(e)}function My(e){return/^\s*type\b/.test(e.trim())}function Oy(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 jy(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 By(e,t,n,r,i,o,s){let a=Je(e,t,r),c=Ft(s,i,o);return n?Vy(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=jn(c,u.localName);return Xt(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||De(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?Qt(u.importedName,u.sourcePath):Bn(u.importedName,u.localName??"",u.sourcePath,u.localName?De(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[Qt("*",a)]}function Vy(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=Hy(r),s=[];return i&&s.push(...Tl(i,n)),o&&s.push(...Tl(o,n)),s}function Tl(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?ke(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 Hy(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 ss(e,t,n){let r=oe(e,t);return r?zy(e,t,r):qy(e,t,n)}function qy(e,t,n){return[...Wy(e,t,n),...Uy(e,t,n),...Jy(e,t,n)]}function Wy(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=ke(s).map(d=>Gy(d.trim())).filter(d=>!!d),l=Vn(n,o.index),u=Vn(n,o.index+o[0].length-1);r.push({kind:"named",sourcePath:Je(e,t,a),names:c,startLine:l,endLine:u})}return r}function Uy(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=Vn(n,o.index),c=Vn(n,o.index+o[0].length-1);r.push({kind:"star-as",sourcePath:Je(e,t,s),names:[],startLine:a,endLine:c})}return r}function Jy(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=Vn(n,o.index),c=Vn(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:Je(e,t,s),names:[],startLine:a,endLine:c})}return r}function Gy(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 Vn(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function zy(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=Ky(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=Qy(i,o,s,a);r.push(c)}return r}function Ky(e,t,n){let r=Pe(n,"string");if(!r)return;let i=Pe(r,"string_fragment");if(i)return Je(e,t,i.text)}function Qy(e,t,n,r){let i=Pe(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 Pe(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function Al(e,t,n){return Ni(e,t,{java:r=>Xy(e,t,r),kotlin:r=>Yy(e,t,r),scala:r=>Zy(e,t,r)},()=>Me(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?eS(e,t,o,i):[]}))}function Xy(e,t,n){let r=X(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(Xt("*",Q(e,l,Ne)));continue}let u=l.split(".").pop()??l;i.push(K(u,u,Q(e,l,Ne),r))}return i}function Yy(e,t,n){let r=X(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(Xt("*",Q(e,s.text,Ne)));continue}let l=s.text,u=l.split(".").pop()??l,m=c?.namedChild(0)?.text??u;i.push(K(u,m,Q(e,l,Ne),r))}return i}function Zy(e,t,n){let r=X(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(Xt("*",Q(e,c,Ne)));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 g=m.text,h=f?.text??g;if(g==="_")continue;i.push(K(g,h,Q(e,`${c}.${g}`,Ne),r))}else if(d.type==="identifier"){let m=d.text;i.push(K(m,m,Q(e,`${c}.${m}`,Ne),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;i.push(K(l,l,Q(e,u&&a.length>1?`${u}.${l}`:c,Ne),r))}return i}function eS(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 ke(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[Ze(e,t,r,m,u,d)]})}return[Ze(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Ml(e,t,n){return Oe(e,t,r=>tS(e,t,r),()=>Me(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?ke(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[Ze(e,t,i,u,d,m,Q(e,u.replace(/\\/g,"."),zt))]}):[]}))}function tS(e,t,n){let r=X(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(K(a,c,Q(e,s.replace(/\\/g,"."),zt),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}=$l(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}=$l(c,"");l&&o(d,l,u)}}return i}function $l(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 jl(e,t,n){return Oe(e,t,r=>nS(e,t,r),()=>iS(n).flatMap(r=>sS(e,t,r,n)))}function nS(e,t,n){let r=X(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=Ol(s);if(!a)continue;let c=On(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=rS(s);if(a===null)continue;let c=On(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=Ol(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function Ol(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 rS(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=Pe(e,"import_prefix")?.text??"",n=Pe(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function iS(e){let t=e.split(`
|
|
95
|
-
`),n=[],
|
|
96
|
-
${m}`,l+=1+m.length,u+=
|
|
93
|
+
ORDER BY start_line, end_line`,t)}function xS(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:F(e.symbol),parentTypeName:et(e.symbol),isFunctionLike:oe(e.symbol),isTypeLike:Y(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function tt(e,t={}){return xi(e,t.scope)}function xi(e,t){return M(e,{scope:t,includeIgnored:!1}).flatMap(n=>G(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function Dr(e,t,n={}){if(t.length===0)return[];let i=t.flatMap(r=>G(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:y(r.symbol),signature:Kt(Jt(r.documentation)),relativePath:r.relativePath,enclosingSymbol:r.enclosingSymbol}))}function ys(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 Me(e,t){let n=cu.get(e);return n||(n=ys(e),cu.set(e,n)),n.get(t)??null}function Qt(e,t){let n=G(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 CS(e,t,n){let i=A(e,t),r=fs(e,t);return r?DS(n,r,i):i?vS(n,i):n}function vS(e,t){let n=t.split(/\r?\n/),i=RS(e,n),r=LS(e,i),o=wS(r,n);return kS(e,o)}function RS(e,t){let n=e.some(r=>Ir(r.symbol))?ES(t):null,i=new Map;for(let r of e)i.set(r.symbolId,NS(t,n,r));return i}function LS(e,t){return e.filter(n=>Ir(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 wS(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:PS(t,r.definition,r.startLine,s)})}return n}function kS(e,t){return e.map(n=>{let i=t.get(n.symbolId);return i?{...n,startLine:i.startLine,endLine:i.endLine}:n})}function DS(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(!IS(r)||!r.leaf)return lu(r,n);let o=i.get(r.leaf);if(!o||o.length===0)return lu(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 IS(e){return Ir(e.symbol)?!0:Y(e.symbol)==="term"&&et(e.symbol)===null}function lu(e,t){if(!t||!e.leaf||Y(e.symbol)!=="term"||et(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 NS(e,t,n){if(!Ir(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 ES(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 PS(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=_S(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 _S(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 Ir(e){return e.includes("().")}function Nr(e){let t=ue(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 GS}from"fs";import{basename as uu,isAbsolute as zS,join as KS}from"path";function j(e,t){let n=Hn(e,t.trim());if(n)return n;let i=OS(e,t);if(i)return i;let r=TS(e,t);return r||MS(e,t)}function TS(e,t){let n=xs(t),i=Ss(n);if(!i)return null;let r=`%${i.path}%`,o=i.leaf,a=FS(e,r,o,n)[0];return a?Qt(e,a):null}function FS(e,t,n,i){let r=jn([],[...$S(e,t,n),...AS(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>Bn(o,i)>1);return r.sort((o,s)=>Bn(s,i)-Bn(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 $S(e,t,n){return Mn(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function AS(e,t,n){return On(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function MS(e,t){let n=xs(t),i=US(t),r=VS(e,i),o=WS(r,t,n);if(o&&!e.isIgnored(o.relative_path))return Qt(e,o);let s=null;for(let a of r){if(e.isIgnored(a.relative_path))continue;let c=qS(a,t,n,i);c<=0||(!s||c>s.score)&&(s={row:a,score:c})}return s?Qt(e,s.row):null}function OS(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=jS(e,i,s,a)??BS(e,i,s,a);return c&&!e.isIgnored(c.relative_path)?Qt(e,c):null}function jS(e,t,n,i){return Mn(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 BS(e,t,n,i){return On(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 Hn(e,t){let i=Mn(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line",limit:1})[0]??On(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line",limit:1})[0];return!i||e.isIgnored(i.relative_path)?null:Qt(e,i)}function Er(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=HS(e,t.symbolId)[0];return n?Qt(e,n):null}function HS(e,t){let n=Mn(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),i=On(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return jn(n,i)}function VS(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(`
|
|
94
|
+
AND `),o=Mn(e,{where:r,params:i,limit:200}),s=On(e,{where:r,params:i,limit:200});return jn(o,s)}function qS(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=y(e.symbol),m=F(e.symbol),p=e.display_name??"",h=e.symbol.toLowerCase(),g=d.toLowerCase(),b=m.toLowerCase(),S=p.toLowerCase(),v=e.relative_path.toLowerCase(),_=/[/:.]/.test(n),w=Ss(n),C=w?.leaf.toLowerCase(),N=0;return(u===r||u===o)&&(N+=1150),(d===r||d===o)&&(N+=1100),p===s&&(N+=1180),m===s&&(N+=1160),(`${m}()`===r||`${m}()`===o)&&(N+=955),(h===a||h===c)&&(N+=1e3),(g===a||g===c)&&(N+=950),(v===a||v===c)&&(N+=925),(v.endsWith(`/${c}`)||v.endsWith(`/${a}`))&&(N+=875),S===l&&(N+=850),b===l&&(N+=825),(`${b}()`===a||`${b}()`===c)&&(N+=820),(g.endsWith(`:${c}`)||g.endsWith(`:${l}`)||g.endsWith(`:${l}()`))&&(N+=800),h.includes(c)&&(N+=120),g.includes(c)&&(N+=140),v.includes(c)&&(N+=140),S.includes(c)&&(N+=110),i.every(H=>{let B=H.toLowerCase();return h.includes(B)||g.includes(B)||v.includes(B)||S.includes(B)})&&(N+=100+i.length*15),w&&v.includes(w.path.toLowerCase())&&(N+=360,C&&(b===C||`${b}()`===C||`${b}()`==`${C}()`)&&(N+=700),be(e.symbol)&&(N+=180)),oe(e.symbol)&&b===l&&(N+=60),!_&&Pt(e.symbol)&&(N-=160),N-=Math.min(50,Math.max(0,e.end_line-e.start_line)),N}function Ss(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 xs(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function US(e){let t=xs(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 WS(e,t,n){let i=t.trim(),r=e.filter(o=>{let s=y(o.symbol),a=(o.display_name??"").trim();return o.symbol===i||s===i||s===n||a===i||a===n||`${a}()`===i||Bn(o,n)>1||o.relative_path===i});return r.length===0?null:(r.sort((o,s)=>Bn(s,n)-Bn(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 Bn(e,t){let n=Ss(t);if(!n)return 0;let i=e.relative_path.toLowerCase(),r=F(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return i.includes(o)?r!==s?1:be(e.symbol)?et(e.symbol)===null?5:4:et(e.symbol)===null?3:2:0}function ke(e,t){let n=du(e,t,{allowMultiple:!1})[0]?.relativePath;return n||JS(e,t)}function Vn(e,t){return du(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function JS(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),i=zS(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,r=KS(e.config.projectRoot,i);return GS(r)?i:null}function du(e,t,n){let i=mu(t);if(!i)return[];let r=M(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:QS(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=j(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 QS(e,t){let n=mu(e),i=uu(n),r=uu(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 mu(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{basename as pR}from"path";import{existsSync as Pr}from"fs";import{basename as XS,dirname as _t,extname as bt,join as Ge,relative as Ci,resolve as Oe}from"path";var YS=X("indexed-paths",{clearGroups:[]}),Xt=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],_r=[".py",".pyi"],_e=[".java",".scala",".kt",".kts"],Tr=[".rs"],Fr=[".rb"],$r=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],Tt=[".cs",".vb"],Ar=[".dart"],Yt=[".php"],ZS=new Set(Xt),Cs=new Set(_r),pu=new Set(_e),vs=new Set(Tr),Rs=new Set(Fr),fu=new Set($r),gu=new Set(Tt),Ls=new Set(Ar),hu=new Set(Yt),ex=[{extensions:Xt,lookup:ZS},{extensions:_r,lookup:Cs},{extensions:_e,lookup:pu},{extensions:Tr,lookup:vs},{extensions:Fr,lookup:Rs},{extensions:$r,lookup:fu},{extensions:Tt,lookup:gu},{extensions:Ar,lookup:Ls},{extensions:Yt,lookup:hu}];function Ft(e,t){return t.has(bt(e).toLowerCase())}function tx(e){return Ft(e,Cs)}function nx(e){return Ft(e,pu)}function ix(e){return Ft(e,vs)}function rx(e){return Ft(e,Rs)}function ox(e){return Ft(e,fu)}function sx(e){return Ft(e,gu)}function bu(e){return bt(e).toLowerCase()===".vb"}function ax(e){return Ft(e,Ls)}function cx(e){return Ft(e,hu)}function ws(e){let t=bt(e).toLowerCase();for(let n of ex)if(n.lookup.has(t))return n.extensions;return Xt}function lx(e){return nx(e)||sx(e)||cx(e)}function Ke(e,t,n){return tx(t)?qn(e,t,n):ix(t)?yt(e,t,n):rx(t)?Mr(e,t,n):ox(t)?Or(e,t,n):lx(t)?Z(e,n.replace(/\\/g,"."),ws(t)):ax(t)?jr(e,t,n):ux(e,t,n)}function ux(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let i=_t(Ge(e.config.projectRoot,t)),r=Oe(i,n),o=vi(e);for(let s of gx(r)){let a=ze(Ci(e.config.projectRoot,s));if(o.has(a)||Pr(s))return a}return ze(Ci(e.config.projectRoot,r))}function qn(e,t,n){let i=vi(e),r;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=_t(Ge(e.config.projectRoot,t));for(let l=1;l<s;l++)c=_t(c);r=a?Oe(c,a.replace(/\./g,"/")):c}else r=Oe(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of dx(r)){let s=ze(Ci(e.config.projectRoot,o));if(i.has(s)||Pr(o))return s}return null}function yt(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=_t(Ge(e.config.projectRoot,t)),o;return i.startsWith("crate::")?o=Oe(e.config.projectRoot,"src",i.slice(7).replace(/::/g,"/")):i.startsWith("self::")?o=Oe(r,i.slice(6).replace(/::/g,"/")):o=Oe(_t(r),i.slice(7).replace(/::/g,"/")),ks(e,mx(o))}function Mr(e,t,n){let i=_t(Ge(e.config.projectRoot,t)),r=Oe(i,n);return ks(e,px(r))}function Or(e,t,n){let i=_t(Ge(e.config.projectRoot,t)),r=[Oe(i,n),Oe(e.config.projectRoot,n),Oe(e.config.projectRoot,"include",n),Oe(e.config.projectRoot,"src",n)];return ks(e,r)}function Z(e,t,n){let i=vi(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=>XS(u)===`${s}${c}`);if(l)return l}let a=[...i].filter(c=>n.includes(bt(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function jr(e,t,n){let i=vi(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=ze(c.startsWith("lib/")?c:`lib/${c}`);return i.has(l)?l:null}let r=_t(Ge(e.config.projectRoot,t)),o=Oe(r,n);for(let s of fx(o)){let a=ze(Ci(e.config.projectRoot,s));if(i.has(a)||Pr(s))return a}return null}function dx(e){let t=bt(e);return Cs.has(t)?[e]:[`${e}.py`,`${e}.pyi`,Ge(e,"__init__.py"),Ge(e,"__init__.pyi")]}function ks(e,t){let n=vi(e);for(let i of t){let r=ze(Ci(e.config.projectRoot,i));if(n.has(r)||Pr(i))return r}return null}function mx(e){let t=bt(e);return vs.has(t)?[e]:[`${e}.rs`,Ge(e,"mod.rs")]}function px(e){let t=bt(e);return Rs.has(t)?[e]:[`${e}.rb`,Ge(e,"index.rb")]}function fx(e){let t=bt(e);return Ls.has(t)?[e]:[`${e}.dart`,e]}function gx(e){let t=bt(e),n=new Set;if(t){n.add(e);for(let i of Xt)n.add(e.slice(0,-t.length)+i)}else for(let i of Xt)n.add(`${e}${i}`),n.add(Ge(e,`index${i}`));return[...n]}function vi(e){return YS.get(e,()=>new Set(M(e,{includeIgnored:!1}).map(ze)))}function ze(e){return e.replace(/\\/g,"/")}import{basename as Su}from"path";function Zt(e){return e.replace(/'''[\s\S]*?'''/g,$t).replace(/"""[\s\S]*?"""/g,$t).replace(/#.*$/gm,$t).replace(/\/\/.*$/gm,$t).replace(/\/\*[\s\S]*?\*\//g,$t).replace(/`(?:\\[\s\S]|[^`])*`/g,$t).replace(/'(?:\\.|[^'\\\r\n])*'/g,$t).replace(/"(?:\\.|[^"\\\r\n])*"/g,$t)}function $t(e){return e.replace(/[^\r\n]/g," ")}var kj=Ut("stripped-lines",{clearGroups:["whole-project","source-file"]});Et({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{Br=null,Ri=""},clearFile:()=>{Br=null,Ri=""}});var Br=null,Ri="";function hx(e){return Br===e||(Br=e,Ri=Zt(e)),Ri}function At(e,t,n){let i=hx(e);return`${i.slice(0,t)}${" ".repeat(n-t)}${i.slice(n)}`}function De(e,t){return new RegExp(`\\b${yu(t)}\\b`,"m").test(e)}function Un(e,t){let n=new Set,i=new RegExp(`\\b${yu(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 yu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Li(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var bx=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function Ie(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 Te(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function ee(e,t){let n=new Set,i=(r,o)=>{let s=o||t.has(r.type);!s&&bx.has(r.type)&&n.add(r.text);for(let a of r.children)i(a,s)};return i(e.rootNode,!1),n}function nt(e,t,n,i,r,o,s){return{importedName:r,localName:o,sourcePath:s??Z(e,i,ws(t)),kind:"named",used:De(n,o),usedMembers:[]}}function J(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 Wn(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 en(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function tn(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 je(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=At(e,r.index,r.index+o.length);for(let a of n(r,s))i.push(a)}return i}function Be(e,t,n,i){let r=le(e,t);if(r){let o=n(r);if(o)return o}return i()}function Hr(e,t,n,i){let r=le(e,t),o=W(t),s=o?n[o]:void 0;return r&&s?s(r):i()}function xu(e,t,n){return Be(e,t,i=>Sx(e,t,i),()=>yx(e,t,n))}function yx(e,t,n){return je(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(i,r)=>{let o=i[1]?.trim();if(!o)return[];let s=Su(o).replace(/\.[^.]+$/,"");return[Wn(o,s,Or(e,t,o),De(r,s))]})}function Sx(e,t,n){let i=ee(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=Su(s).replace(/\.[^.]+$/,"");r.push(J(s,a,Or(e,t,s),i))}return r}function Cu(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=At(n,r.index,r.index+a.length);i.push({importedName:o,localName:s,sourcePath:jr(e,t,o),kind:s?"namespace":"side-effect",used:s?De(c,s):!0,usedMembers:s?Un(c,s):[]})}return i}function vu(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:jr(e,t,o)})}return i}function Ru(e,t,n){return Hr(e,t,{csharp:i=>Cx(e,t,i),vb:i=>xx(e,t,i)},()=>{let i=bu(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return je(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[nt(e,t,o,u,d,m,Z(e,u,Tt))]})})}function xx(e,t,n){let i=ee(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(J(u,d,Z(e,l,Tt),i,c?"namespace":"named"))}return r}function Cx(e,t,n){let i=ee(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(J(u,d,Z(e,l,Tt),i,a?"namespace":"named"))}return r}var vx=U("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function Lu(e,t){return vx.get(e,t,()=>{let n=new Set,i=A(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 Ds(e,t,n){return Be(e,t,i=>Lx(e,t,i),()=>Rx(e,t,n))}function Rx(e,t,n){return $x(n).flatMap(i=>Ax(e,t,i.clause,i.specifier,i.start,i.end,n))}function Lx(e,t,n){let i=wx(e,t,n),r=[];for(let o of n.rootNode.descendantsOfType("import_statement"))r.push(...kx(e,t,n,o,i));return r}function wx(e,t,n){let i=ee(n,new Set(["import_statement"]));if(gt(t))for(let r of Lu(e,t))i.add(r);return i}function kx(e,t,n,i,r){let o=Px(i);if(!o)return[];let s=Ke(e,t,o),a=Te(i,"import_clause");return a?Dx(n,a,s,r,_x(i.text)):[en("*",s)]}function Dx(e,t,n,i,r){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(Ix(s.text,n,i,r));else if(s.type==="namespace_import"){let a=Nx(e,s,n,i,r);a&&o.push(a)}else s.type==="named_imports"&&o.push(...Ex(s,n,i,r));return o}function Ix(e,t,n,i){return J("default",e,t,n,"default",{isTypeOnly:i})}function Nx(e,t,n,i,r){let s=Te(t,"identifier")?.text??"";if(!s)return null;let a=Fx(e,s);return tn("*",n,{localName:s,usedMembers:a,isTypeOnly:r,used:a.length>0||i.has(s)})}function Ex(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(J(c,l,t,n,"named",{isTypeOnly:i||Tx(o.text)}))}return r}function Px(e){let t=Te(e,"string");if(!t)return null;let n=Te(t,"string_fragment");return n?n.text:null}function _x(e){return/^\s*import\s+type\b/.test(e)}function Tx(e){return/^\s*type\b/.test(e.trim())}function Fx(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 $x(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 Ax(e,t,n,i,r,o,s){let a=Ke(e,t,i),c=At(s,r,o);return n?Mx(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=Un(c,u.localName);return tn(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||De(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?en(u.importedName,u.sourcePath):Wn(u.importedName,u.localName??"",u.sourcePath,u.localName?De(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[en("*",a)]}function Mx(e){let t=e.trim(),n=/^type\b/.test(t),i=t.replace(/^type\s+/,""),[r,o]=Ox(i),s=[];return r&&s.push(...wu(r,n)),o&&s.push(...wu(o,n)),s}function wu(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let i=n.slice(1,-1).trim();return i?Ie(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 Ox(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 Is(e,t,n){let i=le(e,t);return i?Ux(e,t,i):jx(e,t,n)}function jx(e,t,n){return[...Bx(e,t,n),...Hx(e,t,n),...Vx(e,t,n)]}function Bx(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=Ie(s).map(d=>qx(d.trim())).filter(d=>!!d),l=Gn(n,o.index),u=Gn(n,o.index+o[0].length-1);i.push({kind:"named",sourcePath:Ke(e,t,a),names:c,startLine:l,endLine:u})}return i}function Hx(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=Gn(n,o.index),c=Gn(n,o.index+o[0].length-1);i.push({kind:"star-as",sourcePath:Ke(e,t,s),names:[],startLine:a,endLine:c})}return i}function Vx(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=Gn(n,o.index),c=Gn(n,o.index+o[0].length-1);i.push({kind:"star",sourcePath:Ke(e,t,s),names:[],startLine:a,endLine:c})}return i}function qx(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 Gn(e,t){let n=0;for(let i=0;i<t&&i<e.length;i++)e.charCodeAt(i)===10&&n++;return n}function Ux(e,t,n){let i=[];for(let r of n.rootNode.descendantsOfType("export_statement")){let o=Wx(e,t,r);if(o===void 0)continue;let s=r.startPosition.row,a=r.endPosition.row,c=Gx(r,o,s,a);i.push(c)}return i}function Wx(e,t,n){let i=Te(n,"string");if(!i)return;let r=Te(i,"string_fragment");if(r)return Ke(e,t,r.text)}function Gx(e,t,n,i){let r=Te(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 Te(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:i}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:i}}function ku(e,t,n){return Hr(e,t,{java:i=>zx(e,t,i),kotlin:i=>Kx(e,t,i),scala:i=>Jx(e,t,i)},()=>je(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(i,r)=>{let o=i[1]?.trim();return o?Qx(e,t,o,r):[]}))}function zx(e,t,n){let i=ee(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(tn("*",Z(e,l,_e)));continue}let u=l.split(".").pop()??l;r.push(J(u,u,Z(e,l,_e),i))}return r}function Kx(e,t,n){let i=ee(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(tn("*",Z(e,s.text,_e)));continue}let l=s.text,u=l.split(".").pop()??l,m=c?.namedChild(0)?.text??u;r.push(J(u,m,Z(e,l,_e),i))}return r}function Jx(e,t,n){let i=ee(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(tn("*",Z(e,c,_e)));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 h=m.text,g=p?.text??h;if(h==="_")continue;r.push(J(h,g,Z(e,`${c}.${h}`,_e),i))}else if(d.type==="identifier"){let m=d.text;r.push(J(m,m,Z(e,`${c}.${m}`,_e),i))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;r.push(J(l,l,Z(e,u&&a.length>1?`${u}.${l}`:c,_e),i))}return r}function Qx(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 Ie(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[nt(e,t,i,m,u,d)]})}return[nt(e,t,i,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Iu(e,t,n){return Be(e,t,i=>Xx(e,t,i),()=>je(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,r)=>{let o=i[1]?.trim();return o?Ie(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[nt(e,t,r,u,d,m,Z(e,u.replace(/\\/g,"."),Yt))]}):[]}))}function Xx(e,t,n){let i=ee(n,new Set(["namespace_use_declaration"])),r=[],o=(s,a,c)=>{r.push(J(a,c,Z(e,s.replace(/\\/g,"."),Yt),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}=Du(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}=Du(c,"");l&&o(d,l,u)}}return r}function Du(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 Eu(e,t,n){return Be(e,t,i=>Yx(e,t,i),()=>eC(n).flatMap(i=>nC(e,t,i,n)))}function Yx(e,t,n){let i=ee(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=Nu(s);if(!a)continue;let c=qn(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=Zx(s);if(a===null)continue;let c=qn(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=Nu(u);d&&r.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:i.has(d.localName),usedMembers:[]})}}return r}function Nu(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 Zx(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=Te(e,"import_prefix")?.text??"",n=Te(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function eC(e){let t=e.split(`
|
|
95
|
+
`),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=Li(o);for(;r+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){r++;let m=t[r];c+=`
|
|
96
|
+
${m}`,l+=1+m.length,u+=Li(m),i+=m.length+1}let d=tC(c);d&&n.push({...d,start:a,end:l})}return n}function tC(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 nC(e,t,n,i){let r=At(i,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return Ie(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(),h=qn(e,t,m),g=Un(r,p);return[{importedName:m,localName:p,sourcePath:h,kind:"namespace",used:De(r,p)||g.length>0,usedMembers:g}]});let s=n.module?qn(e,t,n.module):null,a=[];for(let c of Ie(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:De(r,m),usedMembers:[]})}return a}import{basename as iC}from"path";function Pu(e,t,n){return Be(e,t,i=>oC(e,t,i),()=>rC(e,t,n))}function rC(e,t,n){return je(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"?Mr(e,t,s):null;if(a){let c=_u(s);return[Wn(c,c,a,De(r,c))]}return[en(s,a)]})}function oC(e,t,n){let i=ee(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"?Mr(e,t,d):null;if(m){let p=_u(d);r.push(J(p,p,m,i))}else r.push(en(d,m))}return r}function _u(e){return Lr(iC(e).replace(/\.[^.]+$/,""),/_/)}function Tu(e,t,n){return Be(e,t,i=>sC(e,t,i),()=>je(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,r)=>{let o=i[1]?.trim();return o?aC(e,t,o,r):[]}))}function sC(e,t,n){let i=ee(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 wi(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=yt(e,t,a.qualifiedName)??yt(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));r.push(J(a.importedName,a.localName,c,i))}}return r}function wi(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:Vr(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,i=n.split("::").pop()??n;return[{qualifiedName:Vr(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=Vr(t,n.text),o=[];for(let s of i.namedChildren)o.push(...wi(s,r));return o}case"use_list":{let n=[];for(let i of e.namedChildren)n.push(...wi(i,t));return n}case"use_as_clause":{let n=e.namedChild(0),i=e.namedChild(1);if(!n||!i)return[];let r=wi(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:Vr(t,`${i}::*`),importedName:"*",localName:"*"}]}default:return[]}}function Vr(e,t){return e?t?`${e}::${t}`:e:t}function aC(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 Ie(d).flatMap(m=>{let p=m.trim();if(!p||p==="self")return[];let[h,g]=p.split(/\s+as\s+/),b=h?.trim();if(!b)return[];let S=(g??b.split("::").pop()??b).trim(),v=`${u}::${b}`.replace(/::::/g,"::");return[nt(e,t,i,v,b.split("::").pop()??b,S,yt(e,t,u))]})}let[o,s]=r.split(/\s+as\s+/),a=o?.trim()??r,c=(s??a.split("::").pop()??a).trim(),l=yt(e,t,a)??yt(e,t,a.split("::").slice(0,-1).join("::"));return[nt(e,t,i,a,a.split("::").pop()??a,c,l)]}function Fu(e,t,n){let i=le(e,t);if(i)return cC(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(...uC(e,t,s))}return r}function cC(e,t,n){let i=[];for(let r of n.rootNode.descendantsOfType("use_declaration")){if(!lC(r))continue;let o=r.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of wi(o,""))s.importedName&&i.push(Ns(e,t,s.qualifiedName))}return i}function lC(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function uC(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 Ie(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[Ns(e,t,l)]})}return[Ns(e,t,i)]}function Ns(e,t,n){return{specifier:n,sourcePath:yt(e,t,n)??yt(e,t,n.split("::").slice(0,-1).join("::"))}}function nn({language:e,extensions:t,imports:n,parseImports:i}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:i}}function $u(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 dC={language:"javascript",extensions:Xt,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:Ds,parseReExports:Is},mC=nn({language:"python",extensions:_r,imports:"ast-with-regex-fallback",parseImports:Eu}),pC=nn({language:"jvm",extensions:_e,imports:"ast-dispatch-with-regex-fallback",parseImports:ku}),fC={language:"rust",extensions:Tr,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:Tu,parseExports:Fu},gC=nn({language:"ruby",extensions:Fr,imports:"ast-with-regex-fallback",parseImports:Pu}),hC=nn({language:"c/cpp",extensions:$r,imports:"ast-with-regex-fallback",parseImports:xu}),bC=nn({language:"dotnet",extensions:Tt,imports:"ast-dispatch-with-regex-fallback",parseImports:Ru}),yC={language:"dart",extensions:Ar,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:Cu,parseExports:vu},SC=nn({language:"php",extensions:Yt,imports:"ast-with-regex-fallback",parseImports:Iu}),xC=[dC,mC,pC,fC,gC,hC,bC,yC,SC];function qr(e){return $u(xC,e)}var Es={clearGroups:["whole-project","source-file"]},CC=U("source-imports",Es),vC=U("source-exports",Es),RC=U("source-reexports",Es);function ki(e,t){let n=ze(t);return RC.get(e,n,()=>{let i=qr(n);if(!i?.parseReExports)return[];let r=A(e,n);return r?i.parseReExports(e,n,r):[]})}function de(e,t){let n=ze(t);return CC.get(e,n,()=>{let i=qr(n);if(!i)return[];let r=A(e,n);return r?i.parseImports(e,n,r):[]})}function Ur(e,t){let n=ze(t);return vC.get(e,n,()=>{let i=qr(n);if(!i?.parseExports)return[];let r=A(e,n);return r?i.parseExports(e,n,r):[]})}var LC=U("file-dep-graph",{clearGroups:["whole-project"]});function te(e,t){return LC.get(e,t??"",()=>{let n=new Map,i=new Set(M(e,{includeIgnored:!1})),r=(o,s)=>kC(e,n,i,o,s);for(let o of wC(e,t))r(o.from_file,o.to_file);for(let o of i)if(!(t&&!o.includes(t)))for(let s of de(e,o))s.sourcePath&&r(o,s.sourcePath);return n})}function wC(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
|
|
97
97
|
d1.relative_path AS from_file,
|
|
98
98
|
d2.relative_path AS to_file
|
|
99
99
|
FROM mentions m
|
|
@@ -111,11 +111,11 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
111
111
|
WHERE d1.id != d2.id
|
|
112
112
|
AND m.role != 1
|
|
113
113
|
${e.pathExclusionsFor("d1","d2")}
|
|
114
|
-
${n}`)}function
|
|
114
|
+
${n}`)}function kC(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 Wr,readFileSync as DC,readdirSync as Mu}from"fs";import{join as Di}from"path";var IC={files:new Set,pathPrefixes:[]},Ps=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,NC=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,Ou=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],EC=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),PC=4,_C=X("package-surface",{clearGroups:["whole-project"]});function TC(e){return _C.get(e,()=>FC(e.config.projectRoot))}function Kn(e,t){let n=TC(e);return n.files.has(t)?!0:n.pathPrefixes.some(i=>t.startsWith(i))}function FC(e){let t=new Set,n=[];for(let{manifest:i,packageRoot:r}of $C(e))for(let o of AC(i))MC(e,r,o,t,n);return t.size===0&&n.length===0?IC:{files:t,pathPrefixes:n}}function $C(e){let t=[],n=Bu(e,"");return n&&t.push({manifest:n,packageRoot:""}),ju(e,"",t,0),t}function ju(e,t,n,i){if(i>=PC)return;let r=Di(e,t);if(Wr(r))for(let o of Mu(r,{withFileTypes:!0})){if(!o.isDirectory()||EC.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=Bu(e,s);a&&n.push({manifest:a,packageRoot:s}),ju(e,s,n,i+1)}}function Bu(e,t){try{let n=DC(Di(e,t,"package.json"),"utf-8"),i=JSON.parse(n);return i&&typeof i=="object"?i:null}catch{return null}}function AC(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 Hu(e.exports,t),t}function Hu(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))Hu(n,t)}function MC(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 Au(c))l!==""&&r.push(zn(t,l));return}let a=o.replace(NC,"");for(let c of Au(a)){c===a&&c===o&&i.add(zn(t,o));for(let l of Ou)OC(e,i,t,c+l)}i.add(zn(t,o))}function Au(e){let t=[e];return Ps.test(e)&&(t.push(e.replace(Ps,"src/")),t.push(e.replace(Ps,""))),t}function OC(e,t,n,i){let r=zn(n,i);if(t.add(r),!i.startsWith("src/")||Wr(Di(e,r)))return;let o=Ou.find(u=>i.endsWith(u));if(!o)return;let s=i.slice(0,-o.length);jC(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 Vu(e,n,c,`${l}${o}`))t.add(u)}function jC(e,t,n,i,r){let o=zn(n,`${i}/index${r}`);Wr(Di(e,o))&&t.add(o)}function Vu(e,t,n,i){let r=Di(e,t,n);if(!Wr(r))return[];let o=[];for(let s of Mu(r,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...Vu(e,t,a,i)):s.isFile()&&s.name===i&&o.push(zn(t,a))}return o}function zn(e,t){return e?`${e}/${t}`:t}function K(e){let t=Jn(e);return ev(t)?"test":tv(t)?"worker":nv(t)?"entry":iv(t)?"barrel":"source"}function Gr(e){return K(e)==="barrel"}function Uu(e){return BC.get(e,()=>{let t=te(e),n=we(e).filter(o=>{let s=K(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),K(o)==="barrel"&&r.add(o);for(let s of t.get(o)??[])i.has(s)||n.push(s)}}return r})}var BC=X("live-barrels",{clearGroups:["whole-project"]});function _s(e,t){return Uu(e).has(Jn(t))}function Wu(e){let t=Uu(e);return we(e).filter(n=>Gr(n)&&!t.has(n)&&!HC(e,n))}function HC(e,t){let n=Jn(t),i=re(e,n)?.callables;return i&&i.length>0?!0:(e.get(`SELECT COUNT(*) AS n
|
|
115
115
|
FROM defn_enclosing_ranges der
|
|
116
116
|
JOIN documents d ON d.id = der.document_id
|
|
117
117
|
WHERE d.relative_path = ?
|
|
118
|
-
AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function
|
|
118
|
+
AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Re(e,t){let n=K(t);return n==="entry"||n==="worker"||_s(e,t)}function ne(e,t,n){let i=Jn(n);if(Kn(e,i)||zC(t,i))return!0;let r=e.config.entryRoots;return r?!!(r.files?.some(o=>Jn(o)===i)||r.pathPrefixes?.some(o=>i.startsWith(Jn(o)))||r.qualifiedVars?.some(o=>rv(t,o))||r.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}var Gu=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),VC=new Set(["default","generateMetadata","generateStaticParams"]),qC=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),UC=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),WC=new Set(["load","actions","entries",...Gu]),GC=new Set(["default"]);function zC(e,t){let n=F(e);return n===""?!1:KC(t)?Gu.has(n):JC(t)?VC.has(n):QC(t)?qC.has(n):XC(t)?UC.has(n):YC(t)?WC.has(n):ZC(t)?GC.has(n):!1}function KC(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function JC(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function QC(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function XC(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function YC(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function ZC(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function ev(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 tv(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function nv(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 iv(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 Jn(e){return e.replace(/\\/g,"/")}function rv(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(qu(i)+"/")&&e.includes(qu(r)+".")}function qu(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function zr(e,t,n,i={}){if(!n)return[];let r=A(e,t);return r?r.indexOf(n)===-1?[]:(St(e,t).get(n)??[]).filter(s=>!ov(s,i)):[]}function ov(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var sv=U("file-identifiers",{clearGroups:["whole-project","source-file"]});function zu(e,t){let n=re(e,t);return n?n.fileIdentifiers:sv.get(e,t,()=>new Set(St(e,t).keys()))}var av=U("file-ident-lines",{clearGroups:["whole-project","source-file"]});function St(e,t){let n=re(e,t);return n?n.identifierLineMap:av.get(e,t,()=>lv(e,t))}var cv=U("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function Ku(e,t){let n=re(e,t);return n?n.identifiersByLine:cv.get(e,t,()=>{let i=St(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 lv(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=A(e,t);if(!r)return n;let o=Zt(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 Ju(e,t){return Ts(e,t,n=>{let i=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
|
|
119
119
|
m.symbol_id,
|
|
120
120
|
d.relative_path,
|
|
121
121
|
COUNT(*) AS ref_count
|
|
@@ -123,23 +123,23 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
123
123
|
JOIN chunks c ON m.chunk_id = c.id
|
|
124
124
|
JOIN documents d ON c.document_id = d.id
|
|
125
125
|
WHERE m.role != 1
|
|
126
|
-
${
|
|
126
|
+
${i}
|
|
127
127
|
${e.pathExclusionsFor("d")}
|
|
128
|
-
GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function
|
|
128
|
+
GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function Qu(e,t){return Ts(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
|
|
129
129
|
FROM mentions m
|
|
130
130
|
JOIN chunks c ON m.chunk_id = c.id
|
|
131
131
|
JOIN documents d ON c.document_id = d.id
|
|
132
132
|
WHERE m.role != 1
|
|
133
|
-
${
|
|
134
|
-
${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function
|
|
133
|
+
${i}
|
|
134
|
+
${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function Kr(e,t){return Ts(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,
|
|
135
135
|
c.start_line AS chunk_start, c.end_line AS chunk_end
|
|
136
136
|
FROM mentions m
|
|
137
137
|
JOIN chunks c ON m.chunk_id = c.id
|
|
138
138
|
JOIN documents d ON c.document_id = d.id
|
|
139
139
|
WHERE m.role != 1
|
|
140
|
-
${
|
|
140
|
+
${i}
|
|
141
141
|
${e.pathExclusionsFor("d")}
|
|
142
|
-
ORDER BY d.relative_path, c.start_line`,...n??[])})}function
|
|
142
|
+
ORDER BY d.relative_path, c.start_line`,...n??[])})}function Ts(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 Xu(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Mt(e,t){return Xu(e)===Xu(t)}function Jr(e,t){let n=Yu(e);return n?t.filter(i=>Yu(i.file)===n):t}function Qr(e,t,n,i){let r=n.find(o=>o.file===t);if(r)return r;if(i){let o=new Set(de(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(Mt(a,s.file))return s;return null}return n.length===1?n[0]:null}function Yu(e){let t=W(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var uv=X("global-leaf-index",{clearGroups:["whole-project"]});function rn(e){return uv.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
|
|
143
143
|
COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
|
|
144
144
|
FROM global_symbols gs
|
|
145
145
|
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
@@ -153,8 +153,8 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
153
153
|
GROUP BY m.symbol_id
|
|
154
154
|
) mention_doc ON mention_doc.symbol_id = gs.id
|
|
155
155
|
WHERE 1 = 1
|
|
156
|
-
${e.symbolNoiseFor("gs")}`),n=new Map;for(let
|
|
157
|
-
`),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 Mi(c.filter(l=>hr(n,au.join(n,l.file))===t))}function fs(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 qn(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Mi(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 hr(e,t){let n=au.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function rx(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mu(e,t,n,r){let i=ix(t,r);return i.size===0?new Map:ox(e,n,i)}function ix(e,t){let n=new Map;for(let r of J(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 ox(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of sx(e,o)){let a=n.get(s);if(!a)continue;let c=qn(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 sx(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 ax=W("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function fu(e,t,n,r){let i=hu(e,t),o=pu(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 pu(s,n)}function gu(e,t){let n=new Map;for(let[r,i]of hu(e,t)){let o=i[0];o&&n.set(r,o)}return n}function hu(e,t){return ax.get(e,t,()=>{let n=new Map;for(let r of J(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 pu(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 cx from"path";var br=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function Wn(e){let t=e.toLowerCase();return br.some(n=>t.endsWith(n))}function bu(e,t){let n=new Map,r=i=>Wn(i)?Ge(n,i,()=>{let o=cx.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:()=>V(e,{extensions:br})}}import At from"path";import{existsSync as Oi,readdirSync as lx,readFileSync as yu}from"fs";function Su(e){let t=At.join(e,"package.json");if(!Oi(t))return[];let n;try{n=JSON.parse(yu(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>ux(e,i)).flatMap(i=>dx(e,i))}function ux(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=At.join(e,t);return Oi(At.join(s,"package.json"))?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=At.join(e,r||".");if(!Oi(o))return[];try{return lx(o).map(s=>At.join(o,s,i)).filter(s=>Oi(At.join(s,"package.json")))}catch{return[]}}function dx(e,t){try{let n=JSON.parse(yu(At.join(t,"package.json"),"utf8"));if(!n.name)return[];let r=At.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:r,sourceRootRelative:`${r}/src`}]}catch{return[]}}function xu(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Cu(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as yr,readFileSync as mx,readdirSync as px,statSync as fx}from"fs";import Y from"path";var hs=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function bs(e,t){let r=t?Y.dirname(Y.join(e,t)):e,i=Y.resolve(e);for(;r.startsWith(i);){for(let s of hs){let a=Y.join(r,s);if(yr(a))return a}let o=Y.dirname(r);if(o===r)break;r=o}for(let o of hs){let s=Y.join(e,o);if(yr(s))return s}return null}function vu(e){let t=e.config.projectRoot,n=new Set(ys(t,e.config.semantic?.typescript?.tsconfigs)),r=V(e,{includeIgnored:!1,extensions:br});for(let i of r){let o=bs(t,i);o&&n.add(Y.resolve(o))}if(n.size===0){let i=bs(t);i&&n.add(Y.resolve(i))}return[...n].filter(i=>!Ru(t,i)).sort((i,o)=>i.localeCompare(o))}function ys(e,t=[]){let n=new Set;for(let r of t){let i=Y.isAbsolute(r)?r:Y.join(e,r);yr(i)&&n.add(Y.resolve(i))}for(let r of gx(e))for(let i of hs){let o=Y.join(r,i);yr(o)&&n.add(Y.resolve(o))}if(n.size===0){let r=bs(e);r&&n.add(Y.resolve(r))}return[...n].filter(r=>!Ru(e,r)).sort((r,i)=>r.localeCompare(i))}function gx(e){let t=Y.join(e,"package.json");if(!yr(t))return[];let n;try{n=JSON.parse(mx(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>hx(e,i))}function hx(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=Y.join(e,t);return gs(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=Y.join(e,r||".");return gs(o)?px(o).map(s=>Y.join(o,s,i)).filter(gs):[]}function gs(e){try{return fx(e).isDirectory()}catch{return!1}}function Ru(e,t){let n=Y.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 bx}from"module";var yx=bx(import.meta.url),Sr;function Lu(){if(Sr!==void 0)return Sr;try{Sr=yx("ts-morph")}catch{Sr=null}return Sr}function Iu(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!1})}))}function ji(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function wu(e,t){let n=Lu();if(!n)return ji("ts-morph is not installed");let r=vu(e);if(r.length===0)return ji("no tsconfig found");try{let i=Iu(n,r);return new Ss(e,n,i)}catch(i){return ji(i instanceof Error?i.message:String(i),r[0],r)}}var Ss=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Su(t.config.projectRoot),this.sourceFiles=bu(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 Ge(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 Ge(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),r=this.packageImportReferencesForDefinition(t);return n?cu(n,t,r,this.db.config.projectRoot):r})}calleesFor(t){return Ge(this.calleesCache,t.symbolId,()=>Ge(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return Ge(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 ku(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${ku(o)}`})}importUsageForDeclaration(t,n){let r=Je(this.db,t,n.getModuleSpecifierValue()),i=Du(n);return n.getImportClause()?.isTypeOnly()?i.map(o=>Sx(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 lu(l,t,r.identifier,this.db.config.projectRoot))o.push(u);let s=o.some(l=>!fs(l.node)),a=o.some(l=>fs(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,Mi(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=xu(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of Du(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=du(a.identifier,r,this.db.config.projectRoot);l.length>0&&vx(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 Cu(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?Je(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 g=r.get(m);g||(g=new Set,r.set(m,g)),g.add(f.symbolId)}}}indexedDefinitionByLeaf(t,n){return Ge(this.indexedDefinitionLeafCache,t,()=>gu(this.db,t)).get(n)??null}nodeForDefinition(t){return Ge(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Ge(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?mu(this.tsMorph,this.db,n,t):new Map})}definitionFromSymbol(t){let n=t.getDeclarations();for(let r of n){let i=r.getSourceFile(),o=hr(this.db.config.projectRoot,i.getFilePath());if(!o||this.db.isIgnored(o))continue;let s=qn(i,r),a=fu(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=J(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&&xx(i,s.callerId,s.target)});for(let[o,s]of i)i.set(o,Rx(s));return i}semanticCalleeForCallNode(t,n,r){let i=Cx(n,qn(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 Du(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 Sx(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 xx(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function Cx(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 vx(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function Rx(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 ku(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var xs=new WeakMap;kt({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>xs.delete(e)});function en(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,r=xs.get(e);r||(r=new Map,xs.set(e,r));let i=r.get(n);if(i)return i;let o=wu(e,t);return r.set(n,o),o}function xr(e,t){let n=Vi(e,t);return n?n.importUsage(t):[]}function tn(e,t){let n=Vi(e,t.relativePath);return n?n.referencesFor(t):[]}function Un(e,t){let n=new Map;for(let r of t)for(let i of tn(e,r)){if(i.file===r.relativePath||e.isIgnored(i.file))continue;let o=n.get(r.symbolId);o||(o=new Set,n.set(r.symbolId,o)),o.add(i.file)}return n}function Bi(e,t){let n=new Map;for(let r of t){let i=Vi(e,r.relativePath);if(!i)continue;let o=i.calleesFor(r);o.length>0&&n.set(r.symbolId,o)}return n}function Nu(e,t){let n=Vi(e,t.relativePath);return n?n.signatureFor(t):null}function Vi(e,t){if(!Wn(t))return null;let n=en(e,t);return n.availability().available?n:null}function Hi(e,t){let n=new Map;for(let r of ce(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i&&Pu(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)Pu(n,o,r.sourcePath)}return n}function Pu(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Jn(e,t,n){let r=Zt(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[Cr(r[0])];let i=r.filter(c=>c.file===t);if(i.length>0)return i.map(Cr);let o=Hi(e,t),s=o.get(n);if(s)for(let c of s){let l=r.filter(u=>Tt(c,u.file));if(l.length>0)return l.map(Cr)}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=>Tt(c,u.file));if(l.length>0&&l.length===r.length)return l.map(Cr)}return[]}function Eu(e,t,n){let r=Jn(e,t,n);if(r.length>0)return r;let i=Zt(e).get(n);return!i||i.length===0?[]:i.map(Cr)}function Fu(e,t,n={}){let r=yi(e,t);if(!r)return[];let i=$(r.symbol);if(!i)return[];if(n.semantic!==!1){let s=tn(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 _u(e,a)}}let o=new Map;for(let s of Le(e)){let a=A(e,s);if(!a||a.indexOf(i)===-1||s!==r.relativePath&&!Jn(e,s,i).some(u=>u.symbolId===r.symbolId))continue;let c=Fi(e,s,i,s===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});c.length>0&&o.set(s,c)}return _u(e,o)}function Tu(e,t){let n=new Map;for(let o of t){if(!o.leaf)continue;let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}if(n.size===0)return new Map;let r=new Set(t.map(o=>o.symbolId)),i=new Map;for(let o of Le(e)){let s=tu(e,o);if(s.size!==0){for(let a of s)if(n.has(a))for(let c of Jn(e,o,a)){if(!r.has(c.symbolId)||o===c.relativePath)continue;let l=i.get(c.symbolId);l||(l=new Set,i.set(c.symbolId,l)),l.add(o)}}}return i}function Cr(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function _u(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=J(e,i);for(let a of o){let c=Ae(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 nn(e,t){let n=Nx(e,t);return n?Px(e,Ix(e,n.match,n.identifier)):[]}function $t(e,t,n={}){return Lx(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function Lx(e,t,n={}){let r=Fu(e,t,{semantic:n.semantic}),i=r.length>0?Au(r,"source-attribution"):Au(nn(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function Au(e,t){return e.map(n=>({...n,provenance:t}))}function Ix(e,t,n){let r=new Map;for(let[i,o]of Dx(e,t.symbolId))r.set(i,kx(e,i,o,t,n));return r}function Dx(e,t){let n=new Map;for(let r of Ti(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 kx(e,t,n,r,i){let o=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},s=i?Fi(e,t,i,o):[];return n.flatMap(a=>wx(s,a))}function wx(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function Nx(e,t){let n=yi(e,t);return n?{match:n,identifier:$(n.symbol)||null}:null}function Px(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=J(e,i);for(let a of o){let c=Ae(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 _e(e,t,n={}){let r=qi(e,[t],{additive:n.additive,semantic:n.semantic}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>pe(o.symbol)):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function Mu(e,t,n={}){let r=Fx(e)?Ax(e,t,{semantic:n.semantic!==!1}):Tx(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var _x=ie("caller-rows",{clearGroups:["whole-project"]}),Ex=2e4;function Fx(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>Ex}function Tx(e){return _x.get(e,()=>{let t=Ye(e),n=qi(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 Ax(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 nn(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?$x(e,t):null;if(s)for(let a of tn(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=Ae(J(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return r}function $x(e,t){return e.get(`SELECT
|
|
156
|
+
${e.symbolNoiseFor("gs")}`),n=new Map;for(let i of t){if(!i.relative_path||e.isIgnored(i.relative_path))continue;let r=F(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})}function Je(e,t,n){if(e.has(t))return e.get(t);let i=n();return e.set(t,i),i}import Zu from"path";function dv(e,t){return e.getReferences().map(n=>{let i=n.getNode();return nd(i,t)})}function mv(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function ed(e,t,n,i){let r=[];for(let o of mv(e))for(let s of dv(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 Xr(r)}function td(e,t,n,i){let r=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();Ii(i,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||r.push({location:nd(a,i),node:a}))}return r}function nd(e,t){let n=e.getSourceFile(),i=n.getLineAndColumnAtPos(e.getStart());return{file:Ii(t,n.getFilePath())??n.getBaseName(),line:i.line-1,column:i.column-1}}function id(e,t,n){let i=e.getSourceFile(),r=Qn(i,e),o=e.getText(),s=new RegExp(`\\b${pv(o)}\\b`,"g"),a=i.getFullText().split(`
|
|
157
|
+
`),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 Xr(c.filter(l=>Ii(n,Zu.join(n,l.file))===t))}function Fs(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 Qn(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Xr(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 Ii(e,t){let n=Zu.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function pv(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rd(e,t,n,i){let r=fv(t,i);return r.size===0?new Map:gv(e,n,r)}function fv(e,t){let n=new Map;for(let i of G(e,t)){let r=F(i.symbol)??i.leaf;if(!r)continue;let o=n.get(r);o||(o=[],n.set(r,o)),o.push(i)}return n}function gv(e,t,n){let i=new Map,r=new Map;return t.forEachDescendant(o=>{for(let s of hv(e,o)){let a=n.get(s);if(!a)continue;let c=Qn(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 hv(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 bv=U("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function sd(e,t,n,i){let r=cd(e,t),o=od(r.get(i)??[],n);if(o)return o;let s=[];for(let a of r.values())for(let c of a)((c.leaf||F(c.symbol)||"").includes(i)||c.symbol.includes(i))&&s.push(c);return od(s,n)}function ad(e,t){let n=new Map;for(let[i,r]of cd(e,t)){let o=r[0];o&&n.set(i,o)}return n}function cd(e,t){return bv.get(e,t,()=>{let n=new Map;for(let i of G(e,t)){let r=i.leaf||F(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 od(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 yv from"path";var Ni=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function Xn(e){let t=e.toLowerCase();return Ni.some(n=>t.endsWith(n))}function ld(e,t){let n=new Map,i=r=>Xn(r)?Je(n,r,()=>{let o=yv.join(e.config.projectRoot,r);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:r=>i(r)?.sourceFile??null,sourceFileMatch:i,indexedTypeScriptLikeDocuments:()=>M(e,{extensions:Ni})}}import Ot from"path";import{existsSync as Yr,readdirSync as Sv,readFileSync as ud}from"fs";function dd(e){let t=Ot.join(e,"package.json");if(!Yr(t))return[];let n;try{n=JSON.parse(ud(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(r=>xv(e,r)).flatMap(r=>Cv(e,r))}function xv(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=Ot.join(e,t);return Yr(Ot.join(s,"package.json"))?[s]:[]}let n=t.indexOf("*"),i=t.slice(0,n).replace(/\/$/,""),r=t.slice(n+1).replace(/^\//,""),o=Ot.join(e,i||".");if(!Yr(o))return[];try{return Sv(o).map(s=>Ot.join(o,s,r)).filter(s=>Yr(Ot.join(s,"package.json")))}catch{return[]}}function Cv(e,t){try{let n=JSON.parse(ud(Ot.join(t,"package.json"),"utf8"));if(!n.name)return[];let i=Ot.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:i,sourceRootRelative:`${i}/src`}]}catch{return[]}}function md(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function pd(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as Ei,readFileSync as vv,readdirSync as Rv,statSync as Lv}from"fs";import ie from"path";var As=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Ms(e,t){let i=t?ie.dirname(ie.join(e,t)):e,r=ie.resolve(e);for(;i.startsWith(r);){for(let s of As){let a=ie.join(i,s);if(Ei(a))return a}let o=ie.dirname(i);if(o===i)break;i=o}for(let o of As){let s=ie.join(e,o);if(Ei(s))return s}return null}function fd(e){let t=e.config.projectRoot,n=new Set(Os(t,e.config.semantic?.typescript?.tsconfigs)),i=M(e,{includeIgnored:!1,extensions:Ni});for(let r of i){let o=Ms(t,r);o&&n.add(ie.resolve(o))}if(n.size===0){let r=Ms(t);r&&n.add(ie.resolve(r))}return[...n].filter(r=>!gd(t,r)).sort((r,o)=>r.localeCompare(o))}function Os(e,t=[]){let n=new Set;for(let i of t){let r=ie.isAbsolute(i)?i:ie.join(e,i);Ei(r)&&n.add(ie.resolve(r))}for(let i of wv(e))for(let r of As){let o=ie.join(i,r);Ei(o)&&n.add(ie.resolve(o))}if(n.size===0){let i=Ms(e);i&&n.add(ie.resolve(i))}return[...n].filter(i=>!gd(e,i)).sort((i,r)=>i.localeCompare(r))}function wv(e){let t=ie.join(e,"package.json");if(!Ei(t))return[];let n;try{n=JSON.parse(vv(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(r=>kv(e,r))}function kv(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=ie.join(e,t);return $s(s)?[s]:[]}let n=t.indexOf("*"),i=t.slice(0,n).replace(/\/$/,""),r=t.slice(n+1).replace(/^\//,""),o=ie.join(e,i||".");return $s(o)?Rv(o).map(s=>ie.join(o,s,r)).filter($s):[]}function $s(e){try{return Lv(e).isDirectory()}catch{return!1}}function gd(e,t){let n=ie.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 Dv}from"module";var Iv=Dv(import.meta.url),Pi;function hd(){if(Pi!==void 0)return Pi;try{Pi=Iv("ts-morph")}catch{Pi=null}return Pi}function bd(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!1})}))}function Zr(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function xd(e,t){let n=hd();if(!n)return Zr("ts-morph is not installed");let i=fd(e);if(i.length===0)return Zr("no tsconfig found");try{let r=bd(n,i);return new js(e,n,r)}catch(r){return Zr(r instanceof Error?r.message:String(r),i[0],i)}}var js=class{constructor(t,n,i){this.db=t;this.tsMorph=n;this.projects=i;this.workspacePackages=dd(t.config.projectRoot),this.sourceFiles=ld(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;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 Je(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let i=[];for(let r of n.getImportDeclarations())for(let o of this.importUsageForDeclaration(t,r))i.push(o);return i})}referencesFor(t){return Je(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),i=this.packageImportReferencesForDefinition(t);return n?ed(n,t,i,this.db.config.projectRoot):i})}calleesFor(t){return Je(this.calleesCache,t.symbolId,()=>Je(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return Je(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 Sd(c)}),o=i.getReturnType().getText(n);return`(${r.join(",")})=>${Sd(o)}`})}importUsageForDeclaration(t,n){let i=Ke(this.db,t,n.getModuleSpecifierValue()),r=yd(n);return n.getImportClause()?.isTypeOnly()?r.map(o=>Nv(t,i,o)):r.map(o=>this.valueImportUsageForEntry(t,i,o))}valueImportUsageForEntry(t,n,i){let r=i.identifier?i.identifier.findReferences():[],o=[];for(let l of r)for(let u of td(l,t,i.identifier,this.db.config.projectRoot))o.push(u);let s=o.some(l=>!Fs(l.node)),a=o.some(l=>Fs(l.node)),c=i.isTypeOnly;return{importer:t,sourcePath:n,importedName:i.importedName,localName:i.localName,kind:i.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 i of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,i);for(let[i,r]of t)t.set(i,Xr(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=md(this.workspacePackages,r.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of yd(r)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=id(a.identifier,i,this.db.config.projectRoot);l.length>0&&_v(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 pd(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?Ke(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 h=i.get(m);h||(h=new Set,i.set(m,h)),h.add(p.symbolId)}}}indexedDefinitionByLeaf(t,n){return Je(this.indexedDefinitionLeafCache,t,()=>ad(this.db,t)).get(n)??null}nodeForDefinition(t){return Je(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Je(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?rd(this.tsMorph,this.db,n,t):new Map})}definitionFromSymbol(t){let n=t.getDeclarations();for(let i of n){let r=i.getSourceFile(),o=Ii(this.db.config.projectRoot,r.getFilePath());if(!o||this.db.isIgnored(o))continue;let s=Qn(r,i),a=sd(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 i=G(this.db,t).sort((o,s)=>o.startLine-s.startLine||s.endLine-o.endLine);if(i.length===0)return new Map;let r=new Map;n.forEachDescendant(o=>{if(!this.tsMorph.Node.isCallExpression(o)&&!this.tsMorph.Node.isNewExpression(o))return;let s=this.semanticCalleeForCallNode(n,i,o);s&&Ev(r,s.callerId,s.target)});for(let[o,s]of r)r.set(o,Tv(s));return r}semanticCalleeForCallNode(t,n,i){let r=Pv(n,Qn(t,i));if(!r)return null;let o=i.getExpression(),s=o.getSymbol()??o.getType().getSymbol(),a=s?this.definitionFromSymbol(s):null;return a?{callerId:r.symbolId,target:{symbol:a.symbol,file:a.file,line:a.line}}:null}};function yd(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 Nv(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 Ev(e,t,n){let i=e.get(t);i||(i=[],e.set(t,i)),i.push(n)}function Pv(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 _v(e,t,n){for(let i of t){let r=e.get(i)??[];r.push(...n),e.set(i,r)}}function Tv(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 Sd(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Bs=new WeakMap;Et({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>Bs.delete(e)});function on(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,i=Bs.get(e);i||(i=new Map,Bs.set(e,i));let r=i.get(n);if(r)return r;let o=xd(e,t);return i.set(n,o),o}function _i(e,t){let n=to(e,t);return n?n.importUsage(t):[]}function sn(e,t){let n=to(e,t.relativePath);return n?n.referencesFor(t):[]}function Yn(e,t){let n=new Map;for(let i of t)for(let r of sn(e,i)){if(r.file===i.relativePath||e.isIgnored(r.file))continue;let o=n.get(i.symbolId);o||(o=new Set,n.set(i.symbolId,o)),o.add(r.file)}return n}function eo(e,t){let n=new Map;for(let i of t){let r=to(e,i.relativePath);if(!r)continue;let o=r.calleesFor(i);o.length>0&&n.set(i.symbolId,o)}return n}function Cd(e,t){let n=to(e,t.relativePath);return n?n.signatureFor(t):null}function to(e,t){if(!Xn(t))return null;let n=on(e,t);return n.availability().available?n:null}function no(e,t){let n=new Map;for(let i of de(e,t)){if(!i.sourcePath)continue;let r=i.localName??i.importedName;if(r&&vd(n,r,i.sourcePath),i.kind==="namespace")for(let o of i.usedMembers)vd(n,o,i.sourcePath)}return n}function vd(e,t,n){let i=e.get(t);i||(i=new Set,e.set(t,i)),i.add(n)}function Zn(e,t,n){let i=rn(e).get(n);if(!i||i.length===0)return[];if(i.length===1)return[Ti(i[0])];let r=i.filter(c=>c.file===t);if(r.length>0)return r.map(Ti);let o=no(e,t),s=o.get(n);if(s)for(let c of s){let l=i.filter(u=>Mt(c,u.file));if(l.length>0)return l.map(Ti)}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=>Mt(c,u.file));if(l.length>0&&l.length===i.length)return l.map(Ti)}return[]}function Ld(e,t,n){let i=Zn(e,t,n);if(i.length>0)return i;let r=rn(e).get(n);return!r||r.length===0?[]:r.map(Ti)}function wd(e,t,n={}){let i=Er(e,t);if(!i)return[];let r=F(i.symbol);if(!r)return[];if(n.semantic!==!1){let s=sn(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 Rd(e,a)}}let o=new Map;for(let s of we(e)){let a=A(e,s);if(!a||a.indexOf(r)===-1||s!==i.relativePath&&!Zn(e,s,r).some(u=>u.symbolId===i.symbolId))continue;let c=zr(e,s,r,s===i.relativePath?{excludeStartLine:i.startLine,excludeEndLine:i.endLine}:{});c.length>0&&o.set(s,c)}return Rd(e,o)}function kd(e,t){let n=new Map;for(let o of t){if(!o.leaf)continue;let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}if(n.size===0)return new Map;let i=new Set(t.map(o=>o.symbolId)),r=new Map;for(let o of we(e)){let s=zu(e,o);if(s.size!==0){for(let a of s)if(n.has(a))for(let c of Zn(e,o,a)){if(!i.has(c.symbolId)||o===c.relativePath)continue;let l=r.get(c.symbolId);l||(l=new Set,r.set(c.symbolId,l)),l.add(o)}}}return r}function Ti(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function Rd(e,t){let n=[],i=new Set;for(let[r,o]of t){let s=G(e,r);for(let a of o){let c=Me(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 an(e,t){let n=jv(e,t);return n?Bv(e,$v(e,n.match,n.identifier)):[]}function jt(e,t,n={}){return Fv(e,t,n).map(i=>({file:i.file,line:i.line,enclosingSymbol:i.enclosingSymbol}))}function Fv(e,t,n={}){let i=wd(e,t,{semantic:n.semantic}),r=i.length>0?Dd(i,"source-attribution"):Dd(an(e,t),"scip-reference-chunk");return n.includeIgnored===!0?r:r.filter(o=>!e.isIgnored(o.file))}function Dd(e,t){return e.map(n=>({...n,provenance:t}))}function $v(e,t,n){let i=new Map;for(let[r,o]of Av(e,t.symbolId))i.set(r,Mv(e,r,o,t,n));return i}function Av(e,t){let n=new Map;for(let i of Kr(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 Mv(e,t,n,i,r){let o=t===i.relativePath?{excludeStartLine:i.startLine,excludeEndLine:i.endLine}:{},s=r?zr(e,t,r,o):[];return n.flatMap(a=>Ov(s,a))}function Ov(e,t){let n=e.filter(i=>i>=t.start_line&&i<=t.end_line);return n.length>0?n:[t.start_line]}function jv(e,t){let n=Er(e,t);return n?{match:n,identifier:F(n.symbol)||null}:null}function Bv(e,t){let n=[],i=new Set;for(let[r,o]of t){let s=G(e,r);for(let a of o){let c=Me(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 Fe(e,t,n={}){let i=io(e,[t],{additive:n.additive,semantic:n.semantic}),r=n.callableOnly?(i.get(t.symbolId)??[]).filter(o=>be(o.symbol)):i.get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}function Nd(e,t,n={}){let i=qv(e)?Wv(e,t,{semantic:n.semantic!==!1}):Uv(e).get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}var Hv=X("caller-rows",{clearGroups:["whole-project"]}),Vv=2e4;function qv(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>Vv}function Uv(e){return Hv.get(e,()=>{let t=tt(e),n=io(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 Wv(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 an(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?Gv(e,t):null;if(s)for(let a of sn(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=Me(G(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return i}function Gv(e,t){return e.get(`SELECT
|
|
158
158
|
d.id AS documentId,
|
|
159
159
|
gs.id AS symbolId,
|
|
160
160
|
gs.symbol,
|
|
@@ -173,11 +173,11 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
173
173
|
LEFT JOIN chunks c ON c.document_id = der.document_id
|
|
174
174
|
JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
|
|
175
175
|
WHERE gs.id = ?
|
|
176
|
-
LIMIT 1`,t.symbolId)??null}function
|
|
176
|
+
LIMIT 1`,t.symbolId)??null}function io(e,t,n={}){if(t.length===0)return new Map;let i=n.additive??!1,r=[],o=[];for(let u of t)W(u.relativePath)&&Pn(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 h=a.get(d);h||(h=new Set,a.set(d,h));for(let g of m){let b=`${g.symbol}|${g.chunkId}`;h.has(b)||(h.add(b),p.push(g))}}};r.length>0&&c(Xv(e,r)),n.semantic!==!1&&c(tR(zv(e,t)));let l=i?t:o;return l.length>0&&c(eR(e,l)),s}function zv(e,t){let n=new Map,i=[],r=[];for(let s of t){if(!Xn(s.relativePath))continue;let a=A(e,s.relativePath);if(!a){r.push(s);continue}let c=Gt(e,s.relativePath,a),l=Qv(e,s.relativePath),u=Ll(e,s.relativePath,s.symbol,c,l);if(u!==null){let d=Kv(u);if(d){d.length>0&&n.set(s.symbolId,d);continue}}i.push({def:s,contentHash:c,depsDigest:l})}if(i.length===0&&r.length===0)return n;let o=eo(e,[...r,...i.map(s=>s.def)]);for(let[s,a]of o)n.set(s,a);return on(e).availability().available&&wl(e,i.map(s=>({relativePath:s.def.relativePath,symbol:s.def.symbol,contentHash:s.contentHash,depsDigest:s.depsDigest,payload:JSON.stringify(o.get(s.def.symbolId)??[])}))),n}function Kv(e){try{return JSON.parse(e)}catch{return null}}var Jv=U("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function Qv(e,t){return Jv.get(e,t,()=>{let i=[...te(e).get(t)??[]].sort().map(r=>`${r}:${Gt(e,r,A(e,r))}`);return ds(i.join("|"))})}function Xv(e,t){let n=new Map,i=Yv(t,n),r=rn(e);for(let[o,s]of i){let a=Pn(e,o);if(!a)continue;let c=ys(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=Zv(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 Yv(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 Zv(e,t,n,i,r){let o=Jr(t,n.get(i)??[]);return o.length===0?null:Qr(e,t,o,r)}function eR(e,t){if(t.length===0)return new Map;let i=Hs(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
|
|
177
177
|
FROM mentions m
|
|
178
178
|
JOIN chunks c ON m.chunk_id = c.id
|
|
179
179
|
WHERE m.role != 1
|
|
180
|
-
AND c.document_id IN (${m.map(()=>"?").join(",")})`,...m)),
|
|
180
|
+
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=Hs(i.map(m=>m.symbol_id)).flatMap(m=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
|
|
181
181
|
COALESCE(der.document_id, def_chunk.document_id) AS document_id
|
|
182
182
|
FROM global_symbols gs
|
|
183
183
|
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
@@ -189,11 +189,11 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
189
189
|
AND m.symbol_id IN (${m.map(()=>"?").join(",")})
|
|
190
190
|
GROUP BY m.symbol_id
|
|
191
191
|
) def_chunk ON def_chunk.symbol_id = gs.id
|
|
192
|
-
WHERE gs.id IN (${m.map(()=>"?").join(",")})`,...m,...m)),a=
|
|
193
|
-
WHERE id IN (${m.map(()=>"?").join(",")})`,...m).map(
|
|
194
|
-
`);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&
|
|
195
|
-
`).slice(n,
|
|
196
|
-
`).trimEnd();return s.length>0?s:null}function
|
|
192
|
+
WHERE gs.id IN (${m.map(()=>"?").join(",")})`,...m,...m)),a=Hs([...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
|
|
193
|
+
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)??[],h=new Set,g=[],b=null,S=()=>{if(b)return b;let v=d.get(m.documentId)??"",_=new Set;if(v){let w=Ku(e,v),C=Math.max(0,m.startLine),N=Math.min(w.length-1,m.endLine);for(let H=C;H<=N;H+=1)for(let B of w[H])_.add(B)}return b=_,_};for(let v of p){if(v.symbol_id===m.symbolId)continue;let _=l.get(v.symbol_id);if(!_)continue;if(!(v.start_line>=m.startLine&&v.end_line<=m.endLine)){if(!(v.start_line<=m.endLine&&v.end_line>=m.startLine))continue;let H=F(_.symbol);if(!H||!S().has(H))continue}let C=`${_.symbol}|${v.chunk_id}`;h.has(C)||(h.add(C),g.push({..._,chunkId:v.chunk_id,source:"scip-chunk"}))}u.set(m.symbolId,g)}return u}var Id=500;function Hs(e){let t=[...new Set(e)],n=[];for(let i=0;i<t.length;i+=Id)n.push(t.slice(i,i+Id));return n}function tR(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 Ed(e,t,n={}){let i=new Map;if(t&&t.length===0)return i;let r=M(e,{includeIgnored:!1}),o=rn(e),s=t??tt(e),a=new Set(s.map(c=>c.symbolId));return nR(e,i,r,o,a),iR(e,i,s,a),aR(e,i,r,o,a),n.semantic!==!1&&lR(i,Yn(e,cR(s))),i}function nR(e,t,n,i,r){for(let o of n){if(!W(o))continue;let s=Pn(e,o);if(s)for(let a of s){let c=Jr(o,i.get(a.calleeLeaf)??[]);if(!c||c.length===0)continue;let l=Qr(e,o,c,a.memberAccess);l&&r.has(l.symbolId)&&l.file!==o&&Vs(t,l.symbolId,o)}}}function iR(e,t,n,i){let r=oR(n);for(let o of rR(e,i))e.isIgnored(o.relative_path)||sR(o,r.get(o.symbol_id))||Vs(t,o.symbol_id,o.relative_path)}function rR(e,t){return Kr(e,t?[...t]:void 0)}function oR(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 sR(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function aR(e,t,n,i,r){for(let o of n){if(W(o)!=="rust")continue;let s=zt(e,o,{includeRustAttributeNames:!0});if(s.length!==0)for(let{name:a}of s){let c=i.get(a);if(c)for(let l of c)r.has(l.symbolId)&&l.file!==o&&Vs(t,l.symbolId,o)}}}function Vs(e,t,n){let i=e.get(t);i||(i=new Set,e.set(t,i)),i.add(n)}function cR(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function lR(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 He(e,t,n={}){return Nd(e,t,n)}function qs(e,t,n={}){return Ed(e,t,n)}function Us(e,t){return kd(e,t)}function Pd(e,t,n={}){let i=qs(e,t,{semantic:n.semantic});return n.sourceFallback===!1?i:uR(i,Us(e,t))}function uR(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 _d(e,t,n){let i=t.identifierResolution==="strict"?Zn:Ld;for(let r of t.paths)if(!(!W(r)&&!(t.includeVueSfc&>(r)))&&!e.isIgnored(r)&&!t.skipPath?.(r))try{let s=(c,l,u,d)=>{if(t.candidateNames&&!t.candidateNames.has(c))return;let m=t.resolveTargets?t.resolveTargets({sourceFile:r,name:c,kind:l,defaultTargets:d}):d();for(let p of m)n({sourceFile:r,name:c,target:p,occurrences:u,kind:l})},a=St(e,r);for(let[c,l]of a)s(c,"identifier",l.length,()=>i(e,r,c));for(let c of zt(e,r,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let l=c.kind==="cross-language-dispatch"?()=>Zn(e,r,c.name):()=>i(e,r,c.name);s(c.name,c.kind,c.occurrences,l)}}finally{t.afterPath?.(r)}}function q(e){return e.endLine-e.startLine+1}function Td(e,t={}){let{scope:n,minLoc:i=1,maxLoc:r=Number.POSITIVE_INFINITY,excludeSymbol:o,excludeEntrySurfaces:s=!1,excludeTypesFiles:a=!1,excludeRootedSymbols:c=!1,requireFunctionLikeSymbol:l=!1,requireCallableSymbol:u=!1,excludeRustTraitImplMembers:d=!1,includeSuppressed:m=!1,sortByLocDesc:p=!1}=t,h=[];for(let g of xi(e,n)){let b=g.relativePath;if(e.isIgnored(b)||s&&Re(e,b)||!dR(g,{requireFunctionLikeSymbol:l,requireCallableSymbol:u})||o!==void 0&&g.symbol===o)continue;let S=q(g);S<i||S>r||a&&mR(b)||c&&ne(e,g.symbol,b)||d&&kr(g.symbol)||K(b)!=="test"&&(An(g.symbol)||!m&&gr(e,b,g.startLine)||h.push(g))}return p?h.sort((g,b)=>q(b)-q(g)):h}function dR(e,t){return t.requireCallableSymbol?be(e.symbol):t.requireFunctionLikeSymbol?oe(e.symbol):e.isFunctionLike}function mR(e){return(e.split("/").pop()??"").includes("types")}var E=class{constructor(t){this.db=t}db;scopedDefinitions(t){return xi(this.db,t)}definitionsForFile(t){return G(this.db,t)}productionCallableDefinitions(t={}){return Td(this.db,t)}calleeMap(t,n={}){return io(this.db,t,n)}crossFileCallerMap(t,n={}){return qs(this.db,t,n)}sourceFallbackCallerFiles(t){return Us(this.db,t)}callerFileMap(t,n={}){return Pd(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 M(this.db,{includeIgnored:!1}))if(W(r)==="rust")for(let{name:o}of zt(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 te(this.db,t)}fileKind(t){return K(t)}hasSuppressionComment(t){return gr(this.db,t.relativePath,t.startLine)}sourceFiles(){return we(this.db)}scanSourceReferences(t,n){_d(this.db,t,n)}callableSignature(t){let n=re(this.db,t.relativePath)?.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};function Ws(e,t){let n=j(e,t);if(!n)return[];let i=F(n.symbol),o=new E(e).definitionsForFile(n.relativePath).filter(c=>be(c.symbol)),s=o.filter(c=>c.parentTypeName===i||c.symbol.includes(i));return(s.length>0?s:fR(pR(n.relativePath))===i?o.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:F(c.symbol)}))}function fR(e){return e.replace(/\.[^.]+$/,"")}function Gs(e,t,n={}){let i=j(e,t);if(!i)return[];let o=!oe(i.symbol)&&!e.isIgnored(i.relativePath)?[{relativePath:i.relativePath,line:i.startLine}]:[],s=jt(e,i,{semantic:n.semantic}).map(u=>({relativePath:u.file,line:u.line})),a=gR(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 gR(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=hR(t.symbol);if(n.length===0)return[];let i=[];for(let r of M(e,{extensions:[".rb"],includeIgnored:!1})){let o=A(e,r);if(!o)continue;let s=o.split(`
|
|
194
|
+
`);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 hR(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 Fi(e,t,n={}){let i=j(e,t);if(!i)return{definitions:[],referencedBy:[]};let r=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",i.symbolId),o=Jt(r?.documentation??null),s=e.isIgnored(i.relativePath)?[]:[{relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,signature:yR(o,r?.display_name??null,i.symbol),source:bR(e,i.relativePath,i.startLine,i.endLine)}],a=jt(e,i,{semantic:n.semantic}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?y(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function bR(e,t,n,i){let r=A(e,t);if(!r)return null;let s=r.split(`
|
|
195
|
+
`).slice(n,i+1).join(`
|
|
196
|
+
`).trimEnd();return s.length>0?s:null}function yR(e,t,n){let i=Kt(e);if(i&&!SR(i))return i;let r=(t??"").trim();return r?oe(n)&&!r.endsWith("()")?`${r}()`:r:y(n)}function SR(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function $i(e,t){let n=ke(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
|
|
197
197
|
FROM mentions m
|
|
198
198
|
JOIN chunks c ON m.chunk_id = c.id
|
|
199
199
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -209,7 +209,7 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
209
209
|
WHERE d1.relative_path = ?
|
|
210
210
|
AND d2.relative_path <> d1.relative_path
|
|
211
211
|
AND ${e.localSymbolPredicate}
|
|
212
|
-
ORDER BY d2.relative_path`,n).filter(
|
|
212
|
+
ORDER BY d2.relative_path`,n).filter(r=>!e.isIgnored(r.relative_path)).map(r=>({relativePath:r.relative_path})):[]}function Ai(e,t){let n=ke(e,t);return n?e.all(`SELECT DISTINCT d1.relative_path
|
|
213
213
|
FROM mentions m
|
|
214
214
|
JOIN chunks c ON m.chunk_id = c.id
|
|
215
215
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -224,9 +224,9 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
224
224
|
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
225
225
|
WHERE d2.relative_path = ?
|
|
226
226
|
AND d1.relative_path != ?
|
|
227
|
-
ORDER BY d1.relative_path`,n,n).filter(
|
|
228
|
-
WHERE relative_path IN (${
|
|
229
|
-
ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),s=
|
|
227
|
+
ORDER BY d1.relative_path`,n,n).filter(r=>!e.isIgnored(r.relative_path)).map(r=>({relativePath:r.relative_path})):[]}function Mi(e,t){let n=Vn(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let i=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
|
|
228
|
+
WHERE relative_path IN (${i})
|
|
229
|
+
ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),s=Dr(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:d,...m})=>m),c=e.all(`SELECT DISTINCT d2.relative_path
|
|
230
230
|
FROM mentions m
|
|
231
231
|
JOIN chunks c ON m.chunk_id = c.id
|
|
232
232
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -239,8 +239,8 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
239
239
|
GROUP BY m2.symbol_id
|
|
240
240
|
) sym_def ON sym_def.symbol_id = gs.id
|
|
241
241
|
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
242
|
-
WHERE d1.relative_path IN (${
|
|
243
|
-
AND d2.relative_path NOT IN (${
|
|
242
|
+
WHERE d1.relative_path IN (${i})
|
|
243
|
+
AND d2.relative_path NOT IN (${i})
|
|
244
244
|
AND ${e.localSymbolPredicate}
|
|
245
245
|
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
|
|
246
246
|
FROM mentions m
|
|
@@ -255,9 +255,9 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
255
255
|
GROUP BY m2.symbol_id
|
|
256
256
|
) sym_def ON sym_def.symbol_id = gs.id
|
|
257
257
|
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
258
|
-
WHERE d2.relative_path IN (${
|
|
259
|
-
AND d1.relative_path NOT IN (${
|
|
260
|
-
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
|
|
258
|
+
WHERE d2.relative_path IN (${i})
|
|
259
|
+
AND d1.relative_path NOT IN (${i})
|
|
260
|
+
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 Oi(e,t){let n=Vn(e,t);return n.length===0?[]:vR([...xR(e,n),...CR(e,n)]).filter(i=>!e.isIgnored(i.relative_path)).map(RR)}function xR(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
|
|
261
261
|
FROM mentions m
|
|
262
262
|
JOIN chunks c ON m.chunk_id = c.id
|
|
263
263
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -284,7 +284,7 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
284
284
|
AND m.role != 1
|
|
285
285
|
AND ${e.localSymbolPredicate}
|
|
286
286
|
${e.pathExclusionsFor("d1")}
|
|
287
|
-
ORDER BY d1.relative_path`,...t,...t,...t)}function dC(e,t){let n=new N(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>pe(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function mC(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 pC(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:y(e.symbol)}}var kr=new WeakMap;function qu(e,t){let n=U(t);return n==="rust"?yC(e,t):n==="typescript"||n==="tsx"||n==="javascript"?gC(e,t):[]}var fC=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]);function gC(e,t){let n=oe(e,t);if(!n)return[];let r=kr.get(n);if(r)return r;let i=/(^|\/)(pages|app)\/.+\.(tsx?|jsx?)$/.test(t)||/(^|\/)(layout|page|loading|error|not-found|head|template|default)\.(tsx?|jsx?)$/.test(t),o=/(^|\/)src\/(pages|views|routes)\/.+\.(tsx?|jsx?|vue)$/.test(t),s=!1,a=n.rootNode;for(let l of a.namedChildren){if(l.type!=="expression_statement")continue;let u=l.namedChild(0);if(!u||u.type!=="call_expression")continue;let d=u.namedChild(0);if(!d)continue;let m=d.type==="member_expression"?d.namedChild(d.namedChildCount-1)?.text:d.text;if(m&&fC.has(m)){s=!0;break}}let c=[];s&&c.push({startLine:0,endLine:a.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"}),(i||o)&&c.push({startLine:0,endLine:a.endPosition.row,reason:i?"Next.js / Remix route file":"Vite/Vue route component"});for(let l of a.namedChildren){let u=null,d=null;if(l.type==="function_declaration")u=l.namedChild(0)?.text??null,d=l;else if(l.type==="export_statement"){let m=l.namedChild(0);m?.type==="function_declaration"&&(u=m.namedChild(0)?.text??null,d=m)}else if(l.type==="lexical_declaration"){let m=l.namedChild(0);if(m?.type==="variable_declarator"){let f=m.namedChild(0)?.text,g=m.namedChild(1);f&&(g?.type==="arrow_function"||g?.type==="function_expression")&&(u=f,d=m)}}u&&/^use[A-Z]/.test(u)&&d&&c.push({startLine:d.startPosition.row,endLine:d.endPosition.row,reason:"React custom hook (use*)"})}return c.push(...Wu(n,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),kr.set(n,c),c}var hC=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function bC(e){return hC.test(e)}function Wu(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(bC(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 yC(e,t){let n=oe(e,t);if(!n)return[];let r=kr.get(n);if(r)return r;let i=[],o=SC(n);return o?(kr.set(n,o),o):(Uu(n.rootNode,i,!1,!1),i.push(...Wu(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(...kC(n.rootNode)),kr.set(n,i),i)}function SC(e){return wC(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function Uu(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"?xC(e,t,n,r):r&&DC(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"?CC(e,t,n):e.type==="mod_item"&&ks(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)Uu(s,t,i,o)}function xC(e,t,n,r){let i=ks(e),o=null;r?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of i){let a=RC(s);if(a){o=a;break}if(Ju(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function CC(e,t,n){let r=ks(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(IC)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:i}),r.some(Ju)&&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 ks(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 vC=[{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 RC(e){return vC.find(({re:t})=>t.test(e))?.reason??null}var LC=[/\bSerialize\b/,/\bDeserialize\b/,/\bFromRow\b/,/\bsqlx::FromRow\b/,/\bDeriveEntityModel\b/,/\bIntoSchema\b/,/\bToSchema\b/,/\bDeriveValueType\b/,/\bError\b/,/\bthiserror::Error\b/];function IC(e){return/#\[\s*derive\s*\(/.test(e)?LC.some(t=>t.test(e)):!1}function Ju(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function DC(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function kC(e){let t=PC(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 wC(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 NC=/^#!?\[\s*serde\s*\(/,Hu=/\bwith\s*=\s*"([^"]+)"/g;function PC(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!NC.test(n.text))continue;Hu.lastIndex=0;let r;for(;(r=Hu.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function Gu(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=qu(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 bi(o))if(a.containers.has(c))return!0;return!1}}function ws(e,t={}){Oo(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function Ns(e,t,n={}){Oo(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function Ku(e,t){return t.isIgnoredPath(e.relativePath)?et("ignored-file"):wt(e.symbol)?et("module-like-symbol"):zu(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&zu(e.enclosingSymbol)?et("nested-non-callable-value"):!t.includeTests&&!Ps(e.relativePath)?et("test-file"):!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName)?et("excluded-file-region"):fi(e.symbol)?et("rust-trait-impl-member"):_n(e.symbol)?et("rust-test-module"):!t.includeMembers&&!_C(e)?et("member"):e.endLine-e.startLine+1<t.minLoc?et("below-min-loc"):{accepted:!0}:et("non-value-symbol")}function Ps(e){return z(e)!=="test"}function et(e){return{accepted:!1,rejectionReason:e}}function zu(e){return te(e)||e.endsWith("().")||e.endsWith(".")}function _C(e){return pe(e.symbol)||bi(e.symbol).length===0}function Wi(e,t){return q(e)-q(t)||e.relativePath.localeCompare(t.relativePath)}function Be(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Gn(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 Qu(){return new Map}function Xu(e,t,n){let r=new Map;for(let i of ru(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Ui(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function Yu(e,t,n){let r=new Set;for(let i of iu(e,t))e.isIgnored(i.relative_path)||n.has(i.relative_path)||r.add(i.symbol_id);return r}function _s(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 Zu(e){return e?.occurrences??0}function Ui(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=td(e,t,n);o.occurrences+=r,o.sources.add(i)}function ed(e,t,n,r,i){if(r<=0)return;let o=td(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function td(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}function ht(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=Be(EC(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c),d=o?new Set(eu(e)):new Set,m=a?Qu():Xu(e,d,u.map(L=>L.symbolId)),f=a?Yu(e,u.map(L=>L.symbolId),d):new Set,g=a?u.filter(L=>!f.has(L.symbolId)):u;a?MC(e,g,m,d):$C(e,g,m,d);let h=a?g.filter(L=>!_s(m,L.symbolId)):u;HC(e,h,m,{includeTests:i,inactiveBarrelPaths:d,includeSemantic:!a&&l});let b=a?g.filter(L=>!_s(m,L.symbolId)):u;return AC(e,FC(b,m))}function EC(e,t){let n=Gu(e),r=[];for(let i of V(e,{scope:t.scope}))try{for(let o of J(e,i))Ku(o,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:a=>e.isIgnored(a),isExcludedRegion:n}).accepted&&r.push(o)}finally{Ns(e,i,{definitions:!0})}return r}function FC(e,t){return e.map(n=>TC(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 TC(e,t){let n=t.get(e.symbolId)??new Map,r=Zu(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 AC(e,t){let n=[],r=0,i=0,o=0;for(let s of t){if(e.isIgnored(s.relative_path)||xe(e,s.relative_path)||le(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:y(s.symbol),sameFileRefs:s.same_file_refs,kind:a})}return{symbols:n,totalCount:n.length,deadCodeCount:r,fileInternalCount:i,totalLoc:o}}function $C(e,t,n,r){if(t.length===0)return;let i=new N(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 V(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)&&(BC(e,c)||Ui(n,c.target.symbolId,c.sourceFile,VC(c),"source-fallback"))})}function MC(e,t,n,r){if(t.length===0)return;let i=new N(e),o=OC(t),s=new Set(i.sourceFiles());for(let u of V(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=Hi(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?jC(u,d,f,l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),Ns(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&nd(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||Ui(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function OC(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 jC(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=>Tt(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=>Tt(c,u.relativePath));if(l.length>0&&l.length===n.length)return l}return i.permissive?[...n]:[]}function BC(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&nd(e,t)}function VC(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function nd(e,t){return t.occurrences>1?!1:ce(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function HC(e,t,n,r){for(let i of t){let o=je(e,i,{semantic:r.includeSemantic!==!1});if(o.length!==0)for(let s of o){let a=s.file;a===i.relativePath||e.isIgnored(a)||r.inactiveBarrelPaths.has(a)||!r.includeTests&&!Ps(a)||ed(n,i.symbolId,a,1,"caller-map")}}}function Es(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"",s=e.all(`SELECT
|
|
287
|
+
ORDER BY d1.relative_path`,...t,...t,...t)}function CR(e,t){let n=new E(e);return t.flatMap(i=>n.definitionsForFile(i).filter(r=>be(r.symbol)).map(r=>({relative_path:i,symbol:r.symbol})))}function vR(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 RR(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:y(e.symbol)}}var ji=new WeakMap;function $d(e,t){let n=W(t);return n==="rust"?IR(e,t):n==="typescript"||n==="tsx"||n==="javascript"?wR(e,t):[]}var LR=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]);function wR(e,t){let n=le(e,t);if(!n)return[];let i=ji.get(n);if(i)return i;let r=!1,o=n.rootNode;for(let a of o.namedChildren){if(a.type!=="expression_statement")continue;let c=a.namedChild(0);if(!c||c.type!=="call_expression")continue;let l=c.namedChild(0);if(!l)continue;let u=l.type==="member_expression"?l.namedChild(l.namedChildCount-1)?.text:l.text;if(u&&LR.has(u)){r=!0;break}}let s=[];r&&s.push({startLine:0,endLine:o.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"});for(let a of o.namedChildren){let c=null,l=null;if(a.type==="function_declaration")c=a.namedChild(0)?.text??null,l=a;else if(a.type==="export_statement"){let u=a.namedChild(0);u?.type==="function_declaration"&&(c=u.namedChild(0)?.text??null,l=u)}else if(a.type==="lexical_declaration"){let u=a.namedChild(0);if(u?.type==="variable_declarator"){let d=u.namedChild(0)?.text,m=u.namedChild(1);d&&(m?.type==="arrow_function"||m?.type==="function_expression")&&(c=d,l=u)}}c&&/^use[A-Z]/.test(c)&&l&&s.push({startLine:l.startPosition.row,endLine:l.endPosition.row,reason:"React custom hook (use*)"})}return s.push(...Ad(n,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),ji.set(n,s),s}var kR=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function DR(e){return kR.test(e)}function Ad(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(DR(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 IR(e,t){let n=le(e,t);if(!n)return[];let i=ji.get(n);if(i)return i;let r=[],o=NR(n);return o?(ji.set(n,o),o):(Md(n.rootNode,r,!1,!1),r.push(...Ad(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(...MR(n.rootNode)),ji.set(n,r),r)}function NR(e){return OR(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function Md(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"?ER(e,t,n,i):i&&AR(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"?PR(e,t,n):e.type==="mod_item"&&zs(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(r=!0);for(let s of e.namedChildren)Md(s,t,r,o)}function ER(e,t,n,i){let r=zs(e),o=null;i?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of r){let a=TR(s);if(a){o=a;break}if(Od(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function PR(e,t,n){let i=zs(e),r=e.namedChildren.find(o=>o.type==="type_identifier")?.text;i.some($R)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:r}),i.some(Od)&&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 zs(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 _R=[{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 TR(e){return _R.find(({re:t})=>t.test(e))?.reason??null}var FR=[/\bSerialize\b/,/\bDeserialize\b/,/\bFromRow\b/,/\bsqlx::FromRow\b/,/\bDeriveEntityModel\b/,/\bIntoSchema\b/,/\bToSchema\b/,/\bDeriveValueType\b/,/\bError\b/,/\bthiserror::Error\b/];function $R(e){return/#\[\s*derive\s*\(/.test(e)?FR.some(t=>t.test(e)):!1}function Od(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function AR(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function MR(e){let t=BR(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 OR(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 jR=/^#!?\[\s*serde\s*\(/,Fd=/\bwith\s*=\s*"([^"]+)"/g;function BR(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!jR.test(n.text))continue;Fd.lastIndex=0;let i;for(;(i=Fd.exec(n.text))!==null;){let r=i[1],o=r.split("::").pop()??r;o&&t.add(o)}}return t}function jd(e){let t=new Map,n=i=>{let r=t.get(i);if(r)return r;let o=$d(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 Nr(o))if(a.containers.has(c))return!0;return!1}}function Ks(e,t={}){as(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function Js(e,t,n={}){as(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function Hd(e,t){return t.isIgnoredPath(e.relativePath)?it("ignored-file"):Pt(e.symbol)?it("module-like-symbol"):Bd(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&Bd(e.enclosingSymbol)?it("nested-non-callable-value"):!t.includeTests&&!Qs(e.relativePath)?it("test-file"):!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName)?it("excluded-file-region"):kr(e.symbol)?it("rust-trait-impl-member"):An(e.symbol)?it("rust-test-module"):!t.includeMembers&&!HR(e)?it("member"):e.endLine-e.startLine+1<t.minLoc?it("below-min-loc"):{accepted:!0}:it("non-value-symbol")}function Qs(e){return K(e)!=="test"}function it(e){return{accepted:!1,rejectionReason:e}}function Bd(e){return oe(e)||e.endsWith("().")||e.endsWith(".")}function HR(e){return be(e.symbol)||Nr(e.symbol).length===0}function ro(e,t){return q(e)-q(t)||e.relativePath.localeCompare(t.relativePath)}function Ve(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function ei(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 Vd(){return new Map}function qd(e,t,n){let i=new Map;for(let r of Ju(e,n))e.isIgnored(r.relative_path)||t.has(r.relative_path)||oo(i,r.symbol_id,r.relative_path,r.ref_count,"scip-mention");return i}function Ud(e,t,n){let i=new Set;for(let r of Qu(e,t))e.isIgnored(r.relative_path)||n.has(r.relative_path)||i.add(r.symbol_id);return i}function Xs(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 Wd(e){return e?.occurrences??0}function oo(e,t,n,i,r="source-fallback"){if(i<=0)return;let o=zd(e,t,n);o.occurrences+=i,o.sources.add(r)}function Gd(e,t,n,i,r){if(i<=0)return;let o=zd(e,t,n);o.occurrences=Math.max(i,o.occurrences),o.sources.add(r)}function zd(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}function xt(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=Ve(VR(e,{scope:n,minLoc:i,includeTests:r,includeMembers:s}),c),d=o?new Set(Wu(e)):new Set,m=a?Vd():qd(e,d,u.map(S=>S.symbolId)),p=a?Ud(e,u.map(S=>S.symbolId),d):new Set,h=a?u.filter(S=>!p.has(S.symbolId)):u;a?zR(e,h,m,d):GR(e,h,m,d);let g=a?h.filter(S=>!Xs(m,S.symbolId)):u;YR(e,g,m,{includeTests:r,inactiveBarrelPaths:d,includeSemantic:!a&&l});let b=a?h.filter(S=>!Xs(m,S.symbolId)):u;return WR(e,qR(b,m))}function VR(e,t){let n=jd(e),i=[];for(let r of M(e,{scope:t.scope}))try{for(let o of G(e,r))Hd(o,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:a=>e.isIgnored(a),isExcludedRegion:n}).accepted&&i.push(o)}finally{Js(e,r,{definitions:!0})}return i}function qR(e,t){return e.map(n=>UR(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 UR(e,t){let n=t.get(e.symbolId)??new Map,i=Wd(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 WR(e,t){let n=[],i=0,r=0,o=0;for(let s of t){if(e.isIgnored(s.relative_path)||Re(e,s.relative_path)||ne(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:y(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 GR(e,t,n,i){if(t.length===0)return;let r=new E(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 M(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)&&(QR(e,c)||oo(n,c.target.symbolId,c.sourceFile,XR(c),"source-fallback"))})}function zR(e,t,n,i){if(t.length===0)return;let r=new E(e),o=KR(t),s=new Set(r.sourceFiles());for(let u of M(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=no(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?JR(u,d,p,l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),Js(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&Kd(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||oo(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function KR(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 JR(e,t,n,i,r){let o=n.filter(c=>c.relativePath===e);if(o.length>0)return o;if(!r.permissive&&n.length===1)return[...n];let s=i.get(t);if(s)for(let c of s){let l=n.filter(u=>Mt(c,u.relativePath));if(l.length>0)return l}let a=new Set;for(let c of i.values())for(let l of c)a.add(l);for(let c of a){let l=n.filter(u=>Mt(c,u.relativePath));if(l.length>0&&l.length===n.length)return l}return r.permissive?[...n]:[]}function QR(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&Kd(e,t)}function XR(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function Kd(e,t){return t.occurrences>1?!1:de(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function YR(e,t,n,i){for(let r of t){let o=He(e,r,{semantic:i.includeSemantic!==!1});if(o.length!==0)for(let s of o){let a=s.file;a===r.relativePath||e.isIgnored(a)||i.inactiveBarrelPaths.has(a)||!i.includeTests&&!Qs(a)||Gd(n,r.symbolId,a,1,"caller-map")}}}function Ys(e,t={}){let{limit:n=30,scope:i}=t,r=i?`AND def_d.relative_path LIKE '%${i}%'`:"",s=e.all(`SELECT
|
|
288
288
|
gs.symbol,
|
|
289
289
|
COUNT(*) AS ref_count,
|
|
290
290
|
COUNT(DISTINCT ref_d.id) AS file_count,
|
|
@@ -304,17 +304,17 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
304
304
|
WHERE m.role != 1
|
|
305
305
|
${e.pathExclusionsFor("def_d")}
|
|
306
306
|
${e.symbolNoiseFor("gs")}
|
|
307
|
-
${
|
|
307
|
+
${r}
|
|
308
308
|
GROUP BY gs.id
|
|
309
309
|
ORDER BY ref_count DESC
|
|
310
|
-
LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:y(a.symbol),refCount:a.ref_count,fileCount:a.file_count,definedIn:a.defined_in}));return s.length>0?s:
|
|
310
|
+
LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:y(a.symbol),refCount:a.ref_count,fileCount:a.file_count,definedIn:a.defined_in}));return s.length>0?s:ZR(e,i,n)}function ZR(e,t,n){return tt(e,{scope:t}).filter(i=>!e.isIgnored(i.relativePath)).map(i=>eL(e,i)).filter(i=>i.refCount>0).sort((i,r)=>r.refCount-i.refCount||r.fileCount-i.fileCount).slice(0,n)}function eL(e,t){let n=He(e,t,{limit:500});return{symbol:t.symbol,shortName:y(t.symbol),refCount:n.length,fileCount:new Set(n.map(i=>i.file)).size,definedIn:t.relativePath}}function Zs(e,t,n={}){return Qd(e,t,n)?.map(i=>({symbol:i.symbol,shortName:i.shortName,fromFile:i.fromFile}))??[]}function ea(e,t){let n=tL(e,t);return n.length>0?n:nL(e,t)}function ta(e,t,n={}){return Qd(e,t,n)?.filter(i=>!i.used).map(i=>({symbol:i.symbol,shortName:i.shortName,importedIn:i.importer}))??[]}function tL(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
|
|
311
311
|
FROM mentions m
|
|
312
312
|
JOIN chunks c ON m.chunk_id = c.id
|
|
313
313
|
JOIN documents d ON c.document_id = d.id
|
|
314
314
|
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
315
315
|
WHERE gs.symbol LIKE ?
|
|
316
316
|
AND m.role = 2
|
|
317
|
-
ORDER BY d.relative_path`,`%${t}%`).filter(
|
|
317
|
+
ORDER BY d.relative_path`,`%${t}%`).filter(i=>!e.isIgnored(i.importer)).map(i=>({symbol:i.symbol,shortName:y(i.symbol),fromFile:i.importer}))}function nL(e,t){let n=j(e,t),i=n?.relativePath??null,r=n?F(n.symbol):t.replace(/\(\)$/,""),o=n?Pt(n.symbol):!1,s=new Set;for(let a of M(e,{includeIgnored:!1}))for(let c of de(e,a))iL(c,a,{targetFile:i,targetLeaf:r,targetIsModule:o})&&s.add(a);return[...s].sort().map(a=>({symbol:n?.symbol??r,shortName:n?y(n.symbol):r,fromFile:a}))}function iL(e,t,n){return!e.sourcePath||n.targetFile&&Jd(e.sourcePath)!==Jd(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&aL(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function Qd(e,t,n={}){let i=ke(e,t);return i?rL(e,i,n)??(n.semantic===!1?null:oL(e,i))??sL(e,i):null}function rL(e,t,n){let r=e.all(`SELECT DISTINCT
|
|
318
318
|
gs.symbol,
|
|
319
319
|
def_d.relative_path AS from_file,
|
|
320
320
|
imp_d.relative_path AS importer,
|
|
@@ -340,11 +340,11 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
340
340
|
LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
341
341
|
WHERE imp_d.relative_path = ?
|
|
342
342
|
AND m.role = 2
|
|
343
|
-
ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(
|
|
343
|
+
ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(r.length>0){let o=n.semantic===!1?[]:_i(e,t);return r.map(s=>({symbol:s.symbol,shortName:y(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 oL(e,t){let n=_i(e,t);return n.length>0?n.map(i=>{let r=Xd(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 sL(e,t){return de(e,t).map(n=>{let i=Xd(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 Xd(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 Jd(e){return e.replace(/\\/g,"/")}function aL(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function na(e,t){let n=Vn(e,t),i=Dr(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&&!ru(m.symbol,l.symbol))continue;let h=m.endLine-m.startLine;h<d&&(d=h,u=m)}u?u.children.push(l):s.push(l)}return s}function ia(e,t){let n=j(e,t);return n?new E(e).definitionsForFile(n.relativePath).filter(r=>r.symbol!==n.symbol).filter(r=>iu(n.symbol,r.symbol)).sort((r,o)=>r.startLine-o.startLine||r.endLine-o.endLine).map(r=>({symbol:r.symbol,shortName:y(r.symbol),startLine:r.startLine,endLine:r.endLine,kind:Y(r.symbol)??"unknown"})):[]}function ra(e,t){let n=j(e,t);if(!n)return[];let i=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
|
|
344
344
|
FROM mentions m
|
|
345
345
|
JOIN chunks c ON m.chunk_id = c.id
|
|
346
346
|
WHERE m.symbol_id = ?
|
|
347
|
-
AND m.role != 1`,n.symbolId);return[{name:y(n.symbol),count:
|
|
347
|
+
AND m.role != 1`,n.symbolId);return[{name:y(n.symbol),count:i?.file_count??0}]}function oa(e,t){let n=ke(e,t);if(!n)return[];let r=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
348
348
|
FROM mentions m
|
|
349
349
|
JOIN chunks c ON m.chunk_id = c.id
|
|
350
350
|
JOIN documents d ON c.document_id = d.id
|
|
@@ -361,7 +361,7 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
361
361
|
AND m.role != 1
|
|
362
362
|
AND def_d.id != d.id
|
|
363
363
|
GROUP BY d.id
|
|
364
|
-
ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(
|
|
364
|
+
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=te(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function sa(e,t={}){return cL(e,t).map(n=>({name:y(n.symbol),count:n.file_count}))}function cL(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
|
|
365
365
|
FROM mentions m
|
|
366
366
|
JOIN chunks c ON m.chunk_id = c.id
|
|
367
367
|
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
@@ -376,11 +376,11 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
376
376
|
WHERE m.role != 1
|
|
377
377
|
${e.pathExclusionsFor("def_d")}
|
|
378
378
|
${e.symbolNoiseFor("gs")}
|
|
379
|
-
${
|
|
379
|
+
${r}
|
|
380
380
|
GROUP BY gs.id
|
|
381
381
|
HAVING file_count > 1
|
|
382
382
|
ORDER BY file_count DESC
|
|
383
|
-
LIMIT ?`,n)}function
|
|
383
|
+
LIMIT ?`,n)}function aa(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
|
|
384
384
|
FROM mentions m
|
|
385
385
|
JOIN chunks c ON m.chunk_id = c.id
|
|
386
386
|
JOIN documents d ON c.document_id = d.id
|
|
@@ -397,10 +397,10 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
397
397
|
AND def_d.id != d.id
|
|
398
398
|
${e.pathExclusionsFor("d")}
|
|
399
399
|
${e.symbolNoiseFor("gs")}
|
|
400
|
-
${
|
|
400
|
+
${r}
|
|
401
401
|
GROUP BY d.id
|
|
402
402
|
ORDER BY symbol_count DESC
|
|
403
|
-
LIMIT ?`,n).filter(s=>!e.isIgnored(s.relative_path)).map(s=>({name:s.relative_path,count:s.symbol_count}))}function
|
|
403
|
+
LIMIT ?`,n).filter(s=>!e.isIgnored(s.relative_path)).map(s=>({name:s.relative_path,count:s.symbol_count}))}function ca(e,t,n){let i=ke(e,t)??t,r=ke(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
|
|
404
404
|
FROM global_symbols gs
|
|
405
405
|
WHERE (
|
|
406
406
|
-- Defined in file1, referenced in file2
|
|
@@ -432,7 +432,7 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
432
432
|
JOIN documents d ON c.document_id = d.id
|
|
433
433
|
WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
|
|
434
434
|
)
|
|
435
|
-
)`,r,
|
|
435
|
+
)`,i,r,r,i);return{...Yd(i,r,o?.shared??0)}}function la(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
|
|
436
436
|
def_d.relative_path AS file1,
|
|
437
437
|
ref_d.relative_path AS file2,
|
|
438
438
|
COUNT(DISTINCT gs.id) AS shared
|
|
@@ -451,14 +451,14 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
451
451
|
WHERE m.role != 1
|
|
452
452
|
AND def_d.id != ref_d.id
|
|
453
453
|
${e.pathExclusionsFor("def_d","ref_d")}
|
|
454
|
-
${
|
|
454
|
+
${r}
|
|
455
455
|
GROUP BY def_d.id, ref_d.id
|
|
456
456
|
ORDER BY shared DESC
|
|
457
|
-
LIMIT ?`,n).filter(s=>!e.isIgnored(s.file1)&&!e.isIgnored(s.file2)).map(s=>(
|
|
458
|
-
WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:y(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:y(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=se(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 g=l.slice(0,d+1).map(h=>h.suffix==="method"?`${h.name}()`:h.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:g,shortName:g,depth:m})}return u}function wr(e,t,n={}){let r=B(e,t);if(!r)return null;let i=n.semantic!==!1,o=je(e,r,{limit:50,semantic:i}),s=Gn(_e(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i}));return{symbol:r.symbol,shortName:y(r.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:y(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:y(a.symbol),file:a.file}))}}function Ce(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function ue(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function tt(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 ud(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 Xs(e){let t=e.length;if(t===0)return new Map;let n=new Map;for(let i of e)for(let o of i)n.set(o,(n.get(o)??0)+1);let r=new Map;for(let[i,o]of n)r.set(i,Math.log(t/o));return r}function ov(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 dd(e,t,n){let r=Ce(e,t);if(r.size===0)return{similarity:0,significantShared:[],trivialShared:[]};let i=0,o=0,s=0,a=new Set([...e,...t]);for(let f of a){let g=n.get(f)??0,h=e.has(f)?g:0,b=t.has(f)?g:0;i+=h*b,o+=h*h,s+=b*b}let c=Math.sqrt(o)*Math.sqrt(s),l=c>0?i/c:0,u=ov(n),d=[],m=[];for(let f of r)(n.get(f)??0)>=u?d.push(f):m.push(f);return d.sort((f,g)=>(n.get(g)??0)-(n.get(f)??0)),{similarity:l,significantShared:d,trivialShared:m}}function Pr(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=lv(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!te(o.symbol))return[];let s=sv(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):pv(e,t,{minSimilarity:r,limit:i})}function sv(e,t,n,r){let i=Ji(e,{minCallees:3,excludeSymbol:t.symbol,scanLimit:r.scanLimit,semantic:r.semantic}),o=Xs([t,...i].map(a=>a.callees)),s=[];for(let a of i){if(a.callees.size<3)continue;let c=md(t,a,o,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0});c&&s.push(c)}return s.sort((a,c)=>c.similarity-a.similarity),s}function md(e,t,n,r){let{similarity:i,significantShared:o}=dd(e.callees,t.callees,n);if(i<r.minSimilarity)return null;let s=Ce(e.callees,t.callees).size;if(o.length<r.requireSignificantShared&&s<r.requireSharedCount)return null;let a=o.length>0?o:[...Ce(e.callees,t.callees)];return{symbolA:e.symbol,shortNameA:y(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:y(t.symbol),fileB:t.file,similarity:i,similarityBasis:"callees",sharedCallees:a.map(y),uniqueToA:[...ue(e.callees,t.callees)].map(y),uniqueToB:[...ue(t.callees,e.callees)].map(y)}}function bt(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=Ji(e,{minCallees:o,scope:i,scanLimit:a,semantic:t.semantic!==!1}),l=Xs(c.map(b=>b.callees)),u=new Map;for(let b of c)for(let L of b.callees)u.set(L,(u.get(L)??0)+1);let d=Math.max(8,Math.ceil(Math.sqrt(c.length))),m=new Map;for(let b=0;b<c.length;b+=1)for(let L of c[b].callees){if((u.get(L)??0)>d)continue;let F=m.get(L);F||(F=[],m.set(L,F)),F.push(b)}let f=[],g=0,h=new Set;for(let b=0;b<c.length;b+=1){let L=c[b],F=new Set;for(let k of L.callees){let E=m.get(k);if(E)for(let C of E)C>b&&F.add(C)}for(let k of F){let E=`${b}|${k}`;if(h.has(E))continue;h.add(E);let C=c[k];if(s&&L.file===C.file)continue;if(L.paramCount>=0&&C.paramCount>=0){let M=Math.abs(L.paramCount-C.paramCount),j=Math.max(2,Math.ceil(Math.max(L.paramCount,C.paramCount)*.5));if(M>j)continue}let w=md(L,C,l,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4});w&&(av(f,w,r,g),g+=1)}}return f.sort((b,L)=>L.result.similarity-b.result.similarity||b.order-L.order),f.map(b=>b.result)}function av(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 cv=["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 lv(e,t,n){let r=B(e,t),i=new N(e);if(!r)return null;let o=_e(e,r,{semantic:n.semantic});return{symbol:r.symbol,file:r.relativePath,callees:Gi(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var uv=ie("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]});function Ji(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=uv.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=a.get(c);return l||(l=dv(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,l)),i===void 0?l:l.filter(u=>u.symbol!==i)}function dv(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=new N(e),a=Be(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:Gi((c.get(l.symbolId)??[]).map(u=>u.symbol)),paramCount:s.callableSignature(l)?.paramCount??-1})).filter(l=>l.callees.size>=n)}function Gi(e){return new Set([...e].filter(t=>!mv(t)))}function mv(e){return cv.some(t=>e.includes(t))}function pv(e,t,n){let r=fv(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=new Set,a=yv(bv(e));for(let c of r.tokens)for(let l of a.get(c)??[])s.add(l);for(let c of s){if(c.symbol===r.symbol||c.tokens.size<3)continue;let l=Ce(r.tokens,c.tokens);if(l.size<2)continue;let u=new Set([...r.tokens,...c.tokens]),d=u.size>0?l.size/u.size:0;d<i||o.push({symbolA:r.symbol,shortNameA:y(r.symbol),fileA:r.file,symbolB:c.symbol,shortNameB:y(c.symbol),fileB:c.file,similarity:d,similarityBasis:"source-tokens",sharedCallees:[...l].sort(),uniqueToA:[...ue(r.tokens,c.tokens)].sort(),uniqueToB:[...ue(c.tokens,r.tokens)].sort()})}return o.sort((c,l)=>l.similarity-c.similarity||c.shortNameB.localeCompare(l.shortNameB)),o.slice(0,n.limit)}function fv(e,t){let n=B(e,t);if(!n||!te(n.symbol))return null;let r=gv(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function gv(e,t){let n=$(t.symbol),r=pd(e,t.relativePath,t.startLine,t.endLine,n),i=fd(r,n);return i.size>0?i:null}var hv=ie("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]});function bv(e){return hv.get(e,()=>Sv(e))}function yv(e){let t=new Map;for(let n of e)for(let r of n.tokens){let i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function Sv(e){return new N(e).productionCallableDefinitions().map(n=>({symbol:n.symbol,file:n.relativePath,tokens:fd(pd(e,n.relativePath,n.startLine,n.endLine,n.leaf),n.leaf)})).filter(n=>n.tokens.size>0)}function pd(e,t,n,r,i){let o=dt(e,t);if(o.length===0)return"";if(r>=n&&r-n<=12)return o.slice(n,r+1).join(`
|
|
459
|
-
`);let s=[new RegExp(`\\bdef\\s+${
|
|
457
|
+
LIMIT ?`,n).filter(s=>!e.isIgnored(s.file1)&&!e.isIgnored(s.file2)).map(s=>Yd(s.file1,s.file2,s.shared))}function Yd(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 cn(e,t={}){let{scope:n,maxDepth:i=10}=t,r=te(e,n),o=[],s=new Set,a=new Set,c=[];function l(d,m){if(m>i)return;if(a.has(d)){let h=c.indexOf(d);if(h!==-1){let g=c.slice(h).concat(d),b=g.indexOf(g.reduce((_,w)=>_<w?_:w)),S=[...g.slice(b,-1),...g.slice(0,b),g[b]],v=S.join(" -> ");u.has(v)||(u.add(v),o.push({path:S,kind:lL(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 h of p)l(h,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 lL(e){for(let i of e){let r=K(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":Gr(t)||Gr(n)||Zd(t,n)||Zd(n,t)||em(t,n)||em(n,t)||K(t)==="entry"||K(n)==="entry"?"module-hierarchy":"real"}function Zd(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 em(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 ua(e,t={}){let{limit:n=20,scope:i,minFanIn:r=2,minFanOut:o=2,scanLimit:s}=t,a=new E(e);return Ve(a.productionCallableDefinitions({scope:i,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>uL(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 uL(e,t,n){let i=new Set(He(e,t,{limit:500,semantic:n}).map(s=>s.file)).size,r=new Set(Fe(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:y(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 ln(e,t={}){let{scope:n,minLoc:i=3,scanLimit:r}=t,o=new E(e),s=t.semantic!==!1,a=Ve(o.productionCallableDefinitions({scope:n,minLoc:i,excludeEntrySurfaces:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,sortByLocDesc:typeof r=="number"&&r>0}),r),c=o.crossFileCallerMap(a,{semantic:s}),l=new Set(c.keys());for(let g of o.frameworkReferencedSymbolIds(a))l.add(g);let u=o.symbolsWithNonSelfCallees(a,{additive:!1,semantic:s}),d=a.filter(g=>!l.has(g.symbolId)).filter(g=>!u.has(g.symbolId)),m=o.sourceFallbackCallerFiles(d);for(let g of m.keys())l.add(g);let p=d.filter(g=>!l.has(g.symbolId)),h=o.symbolsWithNonSelfCallees(p,{additive:!0,semantic:s});for(let g of h)u.add(g);return p.filter(g=>!u.has(g.symbolId)).sort((g,b)=>q(b)-q(g)||g.relativePath.localeCompare(b.relativePath)||g.startLine-b.startLine).map(g=>({symbol:g.symbol,shortName:y(g.symbol),relativePath:g.relativePath,startLine:g.startLine,endLine:g.endLine,loc:q(g)}))}var ma={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"},da=new Map;for(let[e,t]of Object.entries(ma))da.set(t.toLowerCase(),Number(e));function dL(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),i=da.get(n);if(i!==void 0)return i;for(let[r,o]of da)if(r.includes(n))return o;return null}function pa(e,t,n={}){let{scope:i,limit:r=100}=n,o=dL(t);return o===null?[]:tm(e,i).map(a=>({row:a,resolvedKind:nm(a)})).filter(a=>a.resolvedKind===o).slice(0,r).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:y(a.symbol),kind:c,kindName:ma[c]??"Unknown",relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function fa(e,t={}){let n=new Map;for(let i of tm(e,t.scope)){let r=nm(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:ma[i]??"Unknown",count:r}))}function tm(e,t){return tt(e,{scope:t}).map(mL)}function mL(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 nm(e){return e.kind!==null&&e.kind!==0?pL(e.kind,e.symbol,e.documentation):fL(e.symbol,e.documentation,e.enclosing_symbol)}function pL(e,t,n){let i=(n??"").toLowerCase();if(Y(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 fL(e,t,n){let i=ue(e);if("kind"in i)return null;let r=i.descriptors,o=r[r.length-2]??null,s=Y(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?Y(n):o?.suffix??null)==="type"?21:83}function ga(e,t={}){let{limit:n=10,scope:i,minDepth:r=3}=t,o=te(e,i),s=new Map,a=[],c=new Map,l=new Map,u=new Set,d=[],m=0;for(let C of o.keys()){if(c.has(C))continue;let N=[],H=(o.get(C)??new Set).values();for(c.set(C,m),l.set(C,m),m+=1,d.push(C),u.add(C),N.push({node:C,iter:H,pendingChild:null});N.length>0;){let B=N[N.length-1];if(B.pendingChild!==null){let Ee=B.pendingChild;B.pendingChild=null,l.set(B.node,Math.min(l.get(B.node),l.get(Ee)))}let he=B.iter.next();if(he.done){if(l.get(B.node)===c.get(B.node)){let Ee=[];for(;;){let ft=d.pop();if(u.delete(ft),Ee.push(ft),s.set(ft,a.length),ft===B.node)break}a.push(Ee)}N.pop();continue}let ce=he.value;if(c.has(ce))u.has(ce)&&l.set(B.node,Math.min(l.get(B.node),c.get(ce)));else{c.set(ce,m),l.set(ce,m),m+=1,d.push(ce),u.add(ce);let Ee=(o.get(ce)??new Set).values();B.pendingChild=ce,N.push({node:ce,iter:Ee,pendingChild:null})}}}let p=new Map,h=new Array(a.length);for(let C=0;C<a.length;C++)h[C]=a[C].length,p.set(C,new Set);for(let[C,N]of o){let H=s.get(C);for(let B of N){let he=s.get(B);he!==H&&p.get(H).add(he)}}let g=new Array(a.length),b=new Array(a.length);for(let C=0;C<a.length;C++){let N=[],H=0;for(let B of p.get(C)){let he=b[B];he>H&&(H=he,N=g[B])}g[C]=[C,...N],b[C]=h[C]+H}function S(C){return g[C]}let v=a.map(C=>[...C].sort()),_=new Set,w=[];for(let C=0;C<a.length;C++){let N=S(C),H=[];for(let he of N)H.push(...v[he]);if(H.length<r)continue;let B=H.join(" ");_.has(B)||(_.add(B),w.push(gL(H)))}return w.sort((C,N)=>N.depth-C.depth),hL(w).slice(0,n)}function gL(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 hL(e){let t=[];for(let n of e)t.some(i=>bL(n.chain,i.chain))||t.push(n);return t}function bL(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 ha(e,t){let n=j(e,t);if(!n)return[];let i=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
|
|
458
|
+
WHERE id = ? LIMIT 1`,n.symbolId);if(!i)return[];let r=[{symbol:i.symbol,shortName:y(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:y(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(r.length>1)return r;let c=ue(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 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 Bi(e,t,n={}){let i=j(e,t);if(!i)return null;let r=n.semantic!==!1,o=He(e,i,{limit:50,semantic:r}),s=ei(Fe(e,i,{limit:50,additive:!0,callableOnly:!0,semantic:r}));return{symbol:i.symbol,shortName:y(i.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:y(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:y(a.symbol),file:a.file}))}}function Le(e,t){let n=new Set;for(let i of e)t.has(i)&&n.add(i);return n}function me(e,t){let n=new Set;for(let i of e)t.has(i)||n.add(i);return n}function rt(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 im(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 ba(e){let t=e.length;if(t===0)return new Map;let n=new Map;for(let r of e)for(let o of r)n.set(o,(n.get(o)??0)+1);let i=new Map;for(let[r,o]of n)i.set(r,Math.log(t/o));return i}function yL(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 rm(e,t,n){let i=Le(e,t);if(i.size===0)return{similarity:0,significantShared:[],trivialShared:[]};let r=0,o=0,s=0,a=new Set([...e,...t]);for(let p of a){let h=n.get(p)??0,g=e.has(p)?h:0,b=t.has(p)?h:0;r+=g*b,o+=g*g,s+=b*b}let c=Math.sqrt(o)*Math.sqrt(s),l=c>0?r/c:0,u=yL(n),d=[],m=[];for(let p of i)(n.get(p)??0)>=u?d.push(p):m.push(p);return d.sort((p,h)=>(n.get(h)??0)-(n.get(p)??0)),{similarity:l,significantShared:d,trivialShared:m}}function Vi(e,t,n={}){let{minSimilarity:i=.4,limit:r=20}=n,o=vL(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!oe(o.symbol))return[];let s=SL(e,o,i,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,r):EL(e,t,{minSimilarity:i,limit:r})}function SL(e,t,n,i){let r=wL(e,{minCallees:3,scanLimit:i.scanLimit,semantic:i.semantic}),o=DL(t,r),s=ba([t,...r.corpus].map(c=>c.callees)),a=[];for(let c of o){if(c.callees.size<3)continue;let l=am(t,c,s,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0});l&&a.push(l)}return a.sort((c,l)=>l.similarity-c.similarity),a}function am(e,t,n,i){let{similarity:r,significantShared:o}=rm(e.callees,t.callees,n);if(r<i.minSimilarity)return null;let s=Le(e.callees,t.callees).size;if(o.length<i.requireSignificantShared&&s<i.requireSharedCount)return null;let a=o.length>0?o:[...Le(e.callees,t.callees)],c=cm(a,"callees");return{symbolA:e.symbol,shortNameA:y(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:y(t.symbol),fileB:t.file,similarity:r,similarityBasis:"callees",sharedCallees:a.map(y),uniqueToA:[...me(e.callees,t.callees)].map(y),uniqueToB:[...me(t.callees,e.callees)].map(y),...c}}function Ct(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=so(e,{minCallees:o,scope:r,scanLimit:a,semantic:t.semantic!==!1}),l=ba(c.map(b=>b.callees)),u=new Map;for(let b of c)for(let S of b.callees)u.set(S,(u.get(S)??0)+1);let d=Math.max(8,Math.ceil(Math.sqrt(c.length))),m=new Map;for(let b=0;b<c.length;b+=1)for(let S of c[b].callees){if((u.get(S)??0)>d)continue;let v=m.get(S);v||(v=[],m.set(S,v)),v.push(b)}let p=[],h=0,g=new Set;for(let b=0;b<c.length;b+=1){let S=c[b],v=new Set;for(let _ of S.callees){let w=m.get(_);if(w)for(let C of w)C>b&&v.add(C)}for(let _ of v){let w=`${b}|${_}`;if(g.has(w))continue;g.add(w);let C=c[_];if(s&&S.file===C.file)continue;if(S.paramCount>=0&&C.paramCount>=0){let H=Math.abs(S.paramCount-C.paramCount),B=Math.max(2,Math.ceil(Math.max(S.paramCount,C.paramCount)*.5));if(H>B)continue}let N=am(S,C,l,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4});N&&(xL(p,N,i,h),h+=1)}}return p.sort((b,S)=>S.result.similarity-b.result.similarity||b.order-S.order),p.map(b=>b.result)}function xL(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 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 i=j(e,t),r=new E(e);if(!i)return null;let o=Fe(e,i,{semantic:n.semantic});return{symbol:i.symbol,file:i.relativePath,callees:ao(o.map(s=>s.symbol)),paramCount:r.callableSignature(i)?.paramCount??-1}}var RL=X("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),LL=X("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function so(e,t){let{minCallees:n,scope:i,excludeSymbol:r,scanLimit:o}=t,s=t.semantic!==!1,a=RL.get(e,()=>new Map),c=`${n}|${i??""}|${o??""}|${s}`,l=a.get(c);return l||(l=IL(e,{minCallees:n,scope:i,scanLimit:o,semantic:s}),a.set(c,l)),r===void 0?l:l.filter(u=>u.symbol!==r)}function wL(e,t){let{minCallees:n,scope:i,scanLimit:r}=t,o=t.semantic!==!1,s=LL.get(e,()=>new Map),a=`${n}|${i??""}|${r??""}|${o}`,c=s.get(a);return c||(c=kL(so(e,{minCallees:n,scope:i,scanLimit:r,semantic:o})),s.set(a,c)),c}function kL(e){let t=new Map;for(let r of e)for(let o of r.callees)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.callees){if((t.get(o)??0)>n)continue;let s=i.get(o);s||(s=[],i.set(o,s)),s.push(r)}return{corpus:e,candidateByCallee:i,docFreq:t,ubiquityThreshold:n}}function DL(e,t){let n=new Map;for(let i of e.callees)for(let r of t.candidateByCallee.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 IL(e,t){let{minCallees:n,scope:i,scanLimit:r,semantic:o}=t,s=new E(e),a=Ve(s.productionCallableDefinitions({scope:i,minLoc:5,sortByLocDesc:typeof r=="number"&&r>0}),r),c=s.calleeMap(a,{semantic:o});return a.map(l=>({symbol:l.symbol,file:l.relativePath,callees:ao((c.get(l.symbolId)??[]).map(u=>u.symbol)),paramCount:s.callableSignature(l)?.paramCount??-1})).filter(l=>l.callees.size>=n)}function ao(e){return new Set([...e].filter(t=>!NL(t)))}function NL(e){return CL.some(t=>e.includes(t))}function EL(e,t,n){let i=FL(e,t);if(!i||i.tokens.size<3)return[];let r=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=HL(i,jL(e));for(let a of s){if(a.symbol===i.symbol||a.tokens.size<3)continue;let c=Le(i.tokens,a.tokens);if(c.size<2)continue;let l=new Set([...i.tokens,...a.tokens]),u=l.size>0?c.size/l.size:0;u<r||o.push({symbolA:i.symbol,shortNameA:y(i.symbol),fileA:i.file,symbolB:a.symbol,shortNameB:y(a.symbol),fileB:a.file,similarity:u,similarityBasis:"source-tokens",sharedCallees:[...c].sort(),uniqueToA:[...me(i.tokens,a.tokens)].sort(),uniqueToB:[...me(a.tokens,i.tokens)].sort(),...cm([...c],"source-tokens")})}return o.sort((a,c)=>c.similarity-a.similarity||a.shortNameB.localeCompare(c.shortNameB)),o.slice(0,n.limit)}function cm(e,t){let n=e.flatMap(Sa),i=e.flatMap(b=>om(b,t)),r=ya(n,lm),o=ya(n,um),s=ya(i,xa),a=[...new Set(i.filter(sm))],c=e.filter(b=>{let S=om(b,t);return S.some(v=>xa.has(v))&&S.some(sm)}).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(b=>dm.has(b));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,h=p?"domain-behavior":d?m?"mixed":"domain-behavior":r.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||p)?"direct":"signal";return{evidenceClass:h,actionTier:g,evidenceClassReasons:l,recommendation:PL(h,g)}}function PL(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 ya(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function Sa(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function om(e,t){if(t==="source-tokens")return Sa(e);let n=F(e);return Sa(n.length>0?n:_L(e))}function _L(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 sm(e){return e.length>3&&!xa.has(e)&&!lm.has(e)&&!um.has(e)&&!dm.has(e)&&!TL.has(e)}var xa=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),lm=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),um=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"]),dm=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),TL=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=j(e,t);if(!n||!oe(n.symbol))return null;let i=$L(e,n);return i?{symbol:n.symbol,file:n.relativePath,tokens:i}:null}function $L(e,t){let n=F(t.symbol),i=mm(e,t.relativePath,t.startLine,t.endLine,n),r=pm(i,n);return r.size>0?r:null}var AL=X("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),ML=X("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function OL(e){return AL.get(e,()=>VL(e))}function jL(e){return ML.get(e,()=>BL(OL(e)))}function BL(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 HL(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 VL(e){return new E(e).productionCallableDefinitions().map(n=>({symbol:n.symbol,file:n.relativePath,tokens:pm(mm(e,n.relativePath,n.startLine,n.endLine,n.leaf),n.leaf)})).filter(n=>n.tokens.size>0)}function mm(e,t,n,i,r){let o=Pe(e,t);if(o.length===0)return"";if(i>=n&&i-n<=12)return o.slice(n,i+1).join(`
|
|
459
|
+
`);let s=[new RegExp(`\\bdef\\s+${Hi(r)}\\b`),new RegExp(`\\bfun\\s+${Hi(r)}\\b`),new RegExp(`\\bfn\\s+${Hi(r)}\\b`),new RegExp(`\\bfunction\\s+${Hi(r)}\\b`),new RegExp(`\\b${Hi(r)}\\s*\\(`)],a=o.findIndex(c=>s.some(l=>l.test(c)));if(a>=0){let c=a;for(let l=a+1;l<o.length&&l<=a+8;l++){let u=o[l]??"";if(l>a&&UL(u)||(c=l,u.trim()===""&&l>a+1))break}return o.slice(a,c+1).join(`
|
|
460
460
|
`)}return o.slice(n,Math.min(o.length,n+8)).join(`
|
|
461
|
-
`)}function fd(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=xv(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 xv(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 Cv(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Nr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nt(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 Ys(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=vv(e,{scope:i,minDeps:s});return nt({profiles:a,limit:r,filePattern:o,overrunFactor:5,compare:(l,u)=>Lv(l,u,n,c)})}function vv(e,t){let{scope:n,minDeps:r}=t,i=ne(e,n),{universalDeps:o,distinctiveDeps:s}=Rv(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 Rv(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 Lv(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=tt(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 sn(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=Pn(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 nt({profiles:c,limit:i,filePattern:a,compare:(l,u)=>Iv(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 Iv(e,t,n){let r=Ce(e.tokens,t.tokens);if(r.size<6||!Dv(r))return null;let i=tt(e.tokens,t.tokens);return i<n?null:{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:i,sharedTokens:Zs(r),sharedComponents:_r(r,"component:"),sharedNativeTags:_r(r,"native:"),sharedProps:_r(r,"prop:"),sharedEvents:_r(r,"event:"),sharedBindings:_r(r,"binding:"),uniqueToA:Zs(ue(e.tokens,t.tokens)).slice(0,25),uniqueToB:Zs(ue(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function Dv(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 _r(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function Zs(e){return[...e].sort()}function cn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=Pn(e,{scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(l=>({file:l.file,component:l.name,tokens:l.behaviorTokens,profile:l}));return nt({profiles:c,limit:i,filePattern:a,compare:(l,u)=>kv(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 kv(e,t,n,r){let i=Ce(e.tokens,t.tokens);if(i.size<r||!Nv(i))return null;let o=wv(e.tokens,t.tokens);if(o<n)return null;let s=an(i,"hook:"),a=an(i,"react-hook:"),c=an(i,"effect:"),l=an(i,"state:"),u=an(i,"request:"),d=an(i,"handler:"),m=an(i,"handler-verb:");return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,sharedTokens:ea(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,uniqueToA:ea(ue(e.tokens,t.tokens)).slice(0,25),uniqueToB:ea(ue(t.tokens,e.tokens)).slice(0,25),reason:Pv({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function wv(e,t){if(e.size===0||t.size===0)return 0;let r=Ce(e,t).size/Math.min(e.size,t.size);return Math.max(tt(e,t),r)}function Nv(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 Pv(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"}function an(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function ea(e){return[...e].sort()}function Er(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 Pn(e,{scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>_v(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 _v(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));return 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?null:{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:Ev(e),reasons:n,loc:e.loc}}function Ev(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 ln(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=Fv(e,{scope:o,minTokens:r,scanLimit:s});return nt({profiles:c,limit:i,filePattern:a,compare:(l,u)=>Av(l,u,n),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.fileB.localeCompare(u.fileB)})}function Fv(e,t){return Nn(e,{scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:Tv(n)}))}function Tv(e){return e.totalLines}function Av(e,t,n){let r=Ce(e.tokens,t.tokens);if(r.size<6||!$v(r))return null;let i=tt(e.tokens,t.tokens);return i<n?null:{fileA:e.file,fileB:t.file,similarity:i,sharedTokens:ta(r),sharedComponents:zn(r,"component:"),sharedProps:zn(r,"prop:"),sharedEvents:zn(r,"event:"),sharedDirectives:zn(r,"directive:"),sharedSlots:zn(r,"slot:"),sharedIdentifiers:zn(r,"id:"),uniqueToA:ta(ue(e.tokens,t.tokens)).slice(0,25),uniqueToB:ta(ue(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function $v(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 zn(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function ta(e){return[...e].sort()}function un(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a}=t,c=Nn(e,{scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(l=>({file:l.file,tokens:l.behaviorTokens,profile:l}));return nt({profiles:c,limit:i,filePattern:a,compare:(l,u)=>Mv(l,u,n,r),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.fileB.localeCompare(u.fileB)})}function Mv(e,t,n,r){let i=Ce(e.tokens,t.tokens);if(i.size<r||!jv(i))return null;let o=Ov(e.tokens,t.tokens);if(o<n)return null;let s=yt(i,"composable:"),a=yt(i,"store:"),c=yt(i,"reactivity:"),l=yt(i,"lifecycle:"),u=yt(i,"request:"),d=yt(i,"function:"),m=yt(i,"function-verb:"),f=yt(i,"template-binding:"),g=yt(i,"template-event:");return{fileA:e.file,fileB:t.file,similarity:o,sharedTokens:na(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:g,uniqueToA:na(ue(e.tokens,t.tokens)).slice(0,25),uniqueToB:na(ue(t.tokens,e.tokens)).slice(0,25),reason:Bv({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function Ov(e,t){if(e.size===0||t.size===0)return 0;let r=Ce(e,t).size/Math.min(e.size,t.size);return Math.max(tt(e,t),r)}function jv(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 Bv(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"}function yt(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function na(e){return[...e].sort()}function Fr(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 Nn(e,{scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>Vv(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 Vv(e,t){let n=[];return 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?null:{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:Hv(e),reasons:n,loc:e.totalLines}}function Hv(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 ra(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=ne(e,i),c=Qv(a,o,s);if(c.length===0)return[];let l=qv(c);return l.length<2?[]:Kv(Jv(l,n,r),r)}function qv(e){let t=Wv(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 Wv(e){let{nodeFreq:t,tailFreq:n}=Uv(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 Uv(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 Jv(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=Gv(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 Gv(e,t,n){if(!zv(e.filtered,t.filtered))return null;let{distance:r,ops:i}=Xv(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:Yv(e.original,t.original),commonSuffix:Zv(e.original,t.original)}}function zv(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function Kv(e,t){let n=[];for(let r of e)if(n.some(o=>gd(r.chainA,o.chainA)&&gd(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function Qv(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;hd(e,o,[o],new Set([o]),t,n,r,500)}return r}function hd(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),hd(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 Xv(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 Yv(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 Zv(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 gd(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function Ve(e){let t=e.orderCandidates?[...e.candidates()].sort(e.orderCandidates):e.candidates(),n=Be(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 dn(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new N(e);return Ve({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)=>eR(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function eR(e,t,n){let r=new Set(t.map(a=>a.symbol));if(r.size<n)return null;let i=tR(r,t),o=nR(r,i);if(o.length<2)return null;let s=rR(o,i);return s.length===0?null:{symbol:e.symbol,shortName:y(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:q(e),totalCallees:r.size,clusters:s}}function tR(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 nR(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 rR(e,t){return e.filter(n=>n.size>=3).map(n=>iR(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function iR(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(y),isolation:s}}function Tr(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 oR(e,m,i)){let g=`${f.file}|${f.shortName}`;if(f.symbolId!==null){if(a.has(f.symbolId))continue;a.add(f.symbolId)}else if(c.has(g))continue;c.add(g),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 oR(e,t,n){let r=je(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 sR(e,t,n)){if(i.has(l))continue;let u=J(e,l),d=u.length>0?Ae(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=$n(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:y(l.symbol),file:l.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!aR(u.symbol))continue;let d=`${u.symbolId}|${u.relativePath}`;c.has(d)||(c.add(d),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:y(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function sR(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
|
|
461
|
+
`)}function pm(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=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=>!i.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 Hi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ot(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)continue;let r=e.compare(n,i);r&&t.push(r)}}else{let n=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let i=0;i<e.profiles.length;i+=1){for(let r=i+1;r<e.profiles.length;r+=1){let o=e.compare(e.profiles[i],e.profiles[r]);o&&t.push(o)}if(t.length>n)break}}return t.sort(e.sort??((n,i)=>i.similarity-n.similarity)),t.slice(0,e.limit)}function Ca(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=WL(e,{scope:r,minDeps:s});return ot({profiles:a,limit:i,filePattern:o,overrunFactor:5,compare:(l,u)=>zL(l,u,n,c)})}function WL(e,t){let{scope:n,minDeps:i}=t,r=te(e,n),{universalDeps:o,distinctiveDeps:s}=GL(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 GL(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 zL(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=rt(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 un(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a}=t,c=$n(e,{scope:o,minJsxTokens:i,scanLimit:s}).filter(l=>l.kind==="component").map(l=>({file:l.file,component:l.name,tokens:l.jsxTokens,profile:l}));return ot({profiles:c,limit:r,filePattern:a,compare:(l,u)=>KL(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 KL(e,t,n){let i=Le(e.tokens,t.tokens);if(i.size<6||!JL(i))return null;let r=rt(e.tokens,t.tokens);return r<n?null:{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:r,sharedTokens:va(i),sharedComponents:qi(i,"component:"),sharedNativeTags:qi(i,"native:"),sharedProps:qi(i,"prop:"),sharedEvents:qi(i,"event:"),sharedBindings:qi(i,"binding:"),uniqueToA:va(me(e.tokens,t.tokens)).slice(0,25),uniqueToB:va(me(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function JL(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 qi(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function va(e){return[...e].sort()}function mn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a}=t,c=$n(e,{scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(l=>({file:l.file,component:l.name,tokens:l.behaviorTokens,profile:l}));return ot({profiles:c,limit:r,filePattern:a,compare:(l,u)=>QL(l,u,n,i),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 QL(e,t,n,i){let r=Le(e.tokens,t.tokens);if(r.size<i||!nw(r))return null;let o=tw(e.tokens,t.tokens);if(o<n)return null;let s=dn(r,"hook:"),a=dn(r,"react-hook:"),c=dn(r,"effect:"),l=dn(r,"state:"),u=dn(r,"request:"),d=dn(r,"handler:"),m=dn(r,"handler-verb:"),p=XL({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:Ra(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:Ra(me(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ra(me(t.tokens,e.tokens)).slice(0,25),reason:iw({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function XL(e){let t=[],n=[],i=[];e.sharedReactHooks.length&&n.push(`shared React primitives: ${e.sharedReactHooks.join(", ")}`),e.sharedEffects.length&&n.push(`shared lifecycle primitive: ${e.sharedEffects.join(", ")}`),Ui(e.sharedHooks,"shared hook",t,i),Ui(e.sharedRequests,"shared request",t,n),Ui(e.sharedState,"shared state",t,n),Ui(e.sharedHandlers,"shared handler",t,n),Ui(e.sharedHandlerVerbs,"shared action verb",t,n);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",c=a==="domain-behavior"||a==="mixed"?"signal":"support",l=[...t,...i,...n].slice(0,6);return{actionTier:c,evidenceClass:a,reasons:l,recommendation:ew(a)}}function Ui(e,t,n,i){let r=[],o=[];for(let s of e)YL(s)?r.push(s):o.push(s);r.length&&n.push(`${t} has domain term(s): ${r.slice(0,6).join(", ")}`),o.length&&i.push(`${t} is generic workflow: ${o.slice(0,6).join(", ")}`)}function YL(e){return ZL(e).filter(n=>!rw.has(n)).length>0}function ZL(e){return e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/^use(?=[A-Z])/,"").replace(/^handle(?=[A-Z])/,"").replace(/^is(?=[A-Z])/,"").replace(/^has(?=[A-Z])/,"").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function ew(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 tw(e,t){if(e.size===0||t.size===0)return 0;let i=Le(e,t).size/Math.min(e.size,t.size);return Math.max(rt(e,t),i)}function nw(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 iw(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"}function dn(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function Ra(e){return[...e].sort()}var rw=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"]);function Wi(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 $n(e,{scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>ow(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 ow(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=sw(e),o=aw(e,t,r),s=cw(e),a=lw(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:uw(a,s),reasons:n,loc:e.loc}}function sw(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 aw(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 cw(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=>mw.has(l)),s=o>=0&&n.slice(o+1).some(l=>dw.has(l)),a=fm(i)||fm(e.name);return/(?:Page|Route|Screen|View)$/.test(i)||/(?:Page|Route|Screen|View)$/.test(e.name)||r.some(l=>pw.has(l))||o>=0&&!s&&!a?"route-page":"component"}function fm(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&gm.has(t.at(-1))?!0:[...gm].some(n=>e.endsWith(fw(n)))}function lw(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 uw(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 dw=new Set(["component","components","panel","panels","partial","partials"]),gm=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"]),mw=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),pw=new Set(["landing","page","route","screen","view"]);function fw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function pn(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a}=t,c=gw(e,{scope:o,minTokens:i,scanLimit:s});return ot({profiles:c,limit:r,filePattern:a,compare:(l,u)=>bw(l,u,n),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.fileB.localeCompare(u.fileB)})}function gw(e,t){return Fn(e,{scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:hw(n)}))}function hw(e){return e.totalLines}function bw(e,t,n){let i=Le(e.tokens,t.tokens);if(i.size<6||!yw(i))return null;let r=rt(e.tokens,t.tokens);return r<n?null:{fileA:e.file,fileB:t.file,similarity:r,sharedTokens:La(i),sharedComponents:ti(i,"component:"),sharedProps:ti(i,"prop:"),sharedEvents:ti(i,"event:"),sharedDirectives:ti(i,"directive:"),sharedSlots:ti(i,"slot:"),sharedIdentifiers:ti(i,"id:"),uniqueToA:La(me(e.tokens,t.tokens)).slice(0,25),uniqueToB:La(me(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function yw(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 ti(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function La(e){return[...e].sort()}function gn(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a}=t,c=Fn(e,{scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(l=>({file:l.file,tokens:l.behaviorTokens,profile:l}));return ot({profiles:c,limit:r,filePattern:a,compare:(l,u)=>Sw(l,u,n,i),sort:(l,u)=>u.similarity-l.similarity||l.fileA.localeCompare(u.fileA)||l.fileB.localeCompare(u.fileB)})}function Sw(e,t,n,i){let r=Le(e.tokens,t.tokens);if(r.size<i||!ww(r))return null;let o=Lw(e.tokens,t.tokens);if(o<n)return null;let s=vt(r,"composable:"),a=vt(r,"store:"),c=vt(r,"reactivity:"),l=vt(r,"lifecycle:"),u=vt(r,"request:"),d=vt(r,"function:"),m=vt(r,"function-verb:"),p=vt(r,"template-binding:"),h=vt(r,"template-event:"),g=xw({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:h});return{fileA:e.file,fileB:t.file,similarity:o,sharedTokens:wa(r),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:h,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:wa(me(e.tokens,t.tokens)).slice(0,25),uniqueToB:wa(me(t.tokens,e.tokens)).slice(0,25),reason:kw({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function xw(e){let t=[],n=[],i=[];e.sharedReactivity.length&&n.push(`shared reactivity primitive: ${e.sharedReactivity.join(", ")}`),e.sharedLifecycle.length&&n.push(`shared lifecycle primitive: ${e.sharedLifecycle.join(", ")}`),fn(e.sharedComposables,"shared composable",t,i),fn(e.sharedStores,"shared store",t,i),fn(e.sharedRequests,"shared request",t,n),fn(e.sharedFunctions,"shared function",t,n),fn(e.sharedFunctionVerbs,"shared action verb",t,n),fn(e.sharedBindings,"shared binding",t,n),fn(e.sharedTemplateEvents,"shared template event",t,n);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:Rw(a)}}function fn(e,t,n,i){let r=[],o=[];for(let s of e)Cw(s)?r.push(s):o.push(s);r.length&&n.push(`${t} has domain term(s): ${r.slice(0,6).join(", ")}`),o.length&&i.push(`${t} is generic workflow: ${o.slice(0,6).join(", ")}`)}function Cw(e){return vw(e).filter(n=>!Dw.has(n)).length>0}function vw(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 Rw(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 Lw(e,t){if(e.size===0||t.size===0)return 0;let i=Le(e,t).size/Math.min(e.size,t.size);return Math.max(rt(e,t),i)}function ww(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 kw(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"}function vt(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function wa(e){return[...e].sort()}var Dw=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 Gi(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 Fn(e,{scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>Iw(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 Iw(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=Nw(e),r=Ew(e,t,i),o=Pw(e.file),s=_w(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:Tw(s,o),reasons:n,loc:e.totalLines}}function Nw(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 Ew(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 Pw(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(i=>Fw.has(i))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function _w(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 Tw(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 Fw=new Set(["landing","page","pages","route","routes","view","views"]);function ka(e,t={}){let{minSimilarity:n=.5,limit:i=15,scope:r,minChainLength:o=3,maxChainLength:s=8}=t,a=te(e,r),c=Vw(a,o,s);if(c.length===0)return[];let l=$w(c);return l.length<2?[]:Hw(Ow(l,n,i),i)}function $w(e){let t=Aw(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 Aw(e){let{nodeFreq:t,tailFreq:n}=Mw(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 Mw(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 Ow(e,t,n){let i=[];for(let r=0;r<e.length;r++){for(let o=r+1;o<e.length;o++){let s=jw(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 jw(e,t,n){if(!Bw(e.filtered,t.filtered))return null;let{distance:i,ops:r}=qw(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:Uw(e.original,t.original),commonSuffix:Ww(e.original,t.original)}}function Bw(e,t){let n=new Set(e);return t.some(i=>n.has(i))}function Hw(e,t){let n=[];for(let i of e)if(n.some(o=>hm(i.chainA,o.chainA)&&hm(i.chainB,o.chainB))||n.push(i),n.length>=t)break;return n}function Vw(e,t,n){let i=[];for(let o of e.keys()){if(i.length>=500)break;bm(e,o,[o],new Set([o]),t,n,i,500)}return i}function bm(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),bm(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 qw(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 Uw(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 Ww(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 hm(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),i=e.join("\u2192");return n.includes(i)}function qe(e){let t=e.orderCandidates?[...e.candidates()].sort(e.orderCandidates):e.candidates(),n=Ve(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 hn(e,t={}){let{scope:n,minLoc:i=10,minCallees:r=6,limit:o=20,scanLimit:s}=t,a=new E(e);return qe({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)=>Gw(c,l.get(c.symbolId)??[],r),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function Gw(e,t,n){let i=new Set(t.map(l=>l.symbol));if(i.size<n)return null;let r=Xw(i,t),o=Yw(i,r);if(o.length<2)return null;let s=Zw(o,r);if(s.length===0)return null;let a=y(e.symbol),c=zw(a,i.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:q(e),totalCallees:i.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function zw(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=Kw(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 Kw(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=Jw(e);return Qw.has(i)?`caller verb suggests orchestration: ${i}`:null}function Jw(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 Qw=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function Xw(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 Yw(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 Zw(e,t){return e.filter(n=>n.size>=3).map(n=>ek(n,e,t)).filter(n=>n.isolation>.5).sort((n,i)=>i.isolation-n.isolation)}function ek(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(y),isolation:s}}import{posix as ni}from"path";var tk=U("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]});function bn(e,t,n){return e.callerFileMap(t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function co(e,t,n){let i=[],r=0,o=0,s=F(t.symbol);for(let a of n)ik(e,a,t.relativePath,s)?r++:Da(e,a,s)?o++:i.push(a);return{realConsumers:i,barrelConsumers:r,importOnlyConsumers:o}}function Da(e,t,n){if(!n)return!1;let i=W(t);if(!i)return!1;let r=tk.get(e,t,()=>nk(e,t,i));return r.importedLeaves.has(n)&&!r.usedLeaves.has(n)}function nk(e,t,n){let i=new Set,r=new Set,o=le(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 ik(e,t,n,i){if(!i)return!1;let r=Pe(e,t);if(r.length===0)return!1;let o=ki(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 rk=20,ok=1,sk=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"]]),ak=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),ck=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 Pa(e,t={}){let n=Ea(t.limit,rk),i=Ea(t.minConsumers,ok),r=new E(e),o=r.fileDependencyGraph(t.scope),s=Ik(M(e,{includeIgnored:!1})),a=Pk(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?lk(e,r,t.target):uk(e,t.scope,t.scanLimit)).map(u=>dk(r,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=i||t.target).sort(Dk).slice(0,n)}function lk(e,t,n){let i=fk(e,n);if(i)return[vm(i)];let r=j(e,n);if(!r)return[];let o=t.definitionsForFile(r.relativePath).find(s=>s.symbolId===r.symbolId);return o?[gk(o)]:[{unit:{kind:"symbol",file:r.relativePath,shortName:y(r.symbol),symbol:r.symbol,startLine:r.startLine,endLine:r.endLine}}]}function uk(e,t,n){let i=M(e,{scope:t,includeIgnored:!1}),r=Ea(n,i.length);return i.slice(0,r).map(o=>vm(o))}function dk(e,t,n,i,r,o){let s=n.definition?mk(e,n.definition,i.semantic):pk(t,n.unit.file),a=n.definition?s.length>0?"exact":"none":s.length>0?"file-level":"none",c=n.unit.file,l=Qe(ni.dirname(c)),u=bk(s),d=hk(l),m=Fa([...ym(l),...u?ym(u):[]]),p=yk(n.unit,l,u,s),h=Sk(p,n.unit,l,u,s,r,o),g=Lk(n.unit,a,u,s,l,h.whyNoSuggestedHome),b=wk(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:p,suggestedHome:h.suggestedHome,destinationConfidence:h.confidence,whyNoSuggestedHome:h.whyNoSuggestedHome,counterevidence:g,reasons:b,recommendation:kk(p,h.suggestedHome,a)}}function mk(e,t,n){let i=bn(e,[t],{semantic:n!==!1,sourceFallback:!0});return Dm(i.get(t.symbolId)??[])}function pk(e,t){let n=[];for(let[i,r]of e.entries())i!==t&&r.has(t)&&n.push(i);return Dm(n)}function fk(e,t){let n=Ta(t),i=M(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 gk(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:y(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function vm(e){return{unit:{kind:"file",file:e,shortName:ni.basename(e)}}}function hk(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:_a(r)})}return t}function ym(e){return e==="."?[]:Rm(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function _a(e){return Fa(Rm(e).map(({marker:t})=>t))}function Rm(e){let t=e.split("/").filter(Boolean),n=[];for(let i=0;i<t.length;i+=1){let r=sk.get(t[i]);r&&n.push({marker:r,prefix:t.slice(0,i+1).join("/")})}return n}function bk(e){if(e.length===0)return null;let t=e.map(i=>Qe(ni.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 yk(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":xm(n,"package")?"package-level-shared":xm(n,"app")?"app-level-shared":Cm(n,["feature","domain","module"])||Cm(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function Sk(e,t,n,i,r,o,s){let a=xk(e,i);if(a)return Bt(a);let c=Nk(t.file),l=Ck(e,n,c,r,s);if(l)return l;let u=i;if(Qe(n)===Qe(u))return Bt(`${n} is already the nearest common owner for its consumers.`);let d=vk(u,n,c,s);return d||Rk(u,n,c,o,s)}function xk(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 Ck(e,t,n,i,r){if(e==="same-file"){let o=i[0]??null;return o?Ia(o):Bt("No same-file consumer path was available.")}if(e==="sibling-folder"&&i.length===1){let o=Qe(ni.dirname(i[0])),s=km(t,n,o,r);return s?Bt(s):Ia(o)}return null}function vk(e,t,n,i){return Tk(e)?Lm(e,t,n,i,`Nearest shared owner ${e} is outside source root ${n}.`):null}function Rk(e,t,n,i,r){if(e===".")return Bt("The nearest common owner is the repository root.");let o=`${e}/shared`,s=Lm(o,t,n,r,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||i.has(o)?s:Bt(`${o} does not exist in the indexed project.`)}function Lm(e,t,n,i,r){if(!wm(e,n))return Bt(r);let o=km(t,n,e,i);return o?Bt(o):Ia(e)}function Ia(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function Bt(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function Lk(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 wk(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 kk(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 Dk(e,t){return Sm(t)-Sm(e)||e.candidatePath.localeCompare(t.candidatePath)}function Sm(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 Ik(e){let t=new Set(["."]);for(let n of e){let i=Qe(ni.dirname(n));for(;!t.has(i)&&(t.add(i),i!==".");)i=Qe(ni.dirname(i))}return t}function Nk(e){let t=Na(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function wm(e,t){let n=Qe(e),i=Qe(t);return i==="."||n===i||n.startsWith(`${i}/`)}function Ek(e,t,n){let i=Na(e),r=Na(t);return(wm(e,t)?i.slice(r.length):i).some(s=>n.has(s.toLowerCase()))}function km(e,t,n,i){return Qe(e)===Qe(n)||!Ek(e,t,i)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function Pk(...e){let t=new Set(ck);for(let n of e)for(let i of n??[]){let r=_k(i);r&&t.add(r)}return t}function _k(e){let t=e.trim().toLowerCase();return t===""?null:t}function xm(e,t){return _a(e).includes(t)}function Cm(e,t){let n=_a(e);return t.some(i=>n.includes(i))}function Tk(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?ak.has(n):!1}function Ta(e){return e.replaceAll("\\","/").replace(/^\.\//,"")}function Qe(e){let t=Ta(e);return t===""?".":t}function Na(e){let t=Ta(e);return t==="."?[]:t.split("/").filter(Boolean)}function Ea(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function Dm(e){return Fa([...e]).sort((t,n)=>t.localeCompare(n))}function Fa(e){return[...new Set(e)]}function zi(e,t,n={}){let{maxDepth:i=5,scope:r}=n,o=j(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 Fk(e,m,r)){let h=`${p.file}|${p.shortName}`;if(p.symbolId!==null){if(a.has(p.symbolId))continue;a.add(p.symbolId)}else if(c.has(h))continue;c.add(h),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 Fk(e,t,n){let i=He(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 $k(e,t,n)){if(r.has(l))continue;let u=G(e,l),d=u.length>0?Me(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=Hn(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:y(l.symbol),file:l.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!Ak(u.symbol))continue;let d=`${u.symbolId}|${u.relativePath}`;c.has(d)||(c.add(d),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:y(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function $k(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
|
|
462
462
|
FROM mentions m
|
|
463
463
|
JOIN chunks c ON m.chunk_id = c.id
|
|
464
464
|
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
@@ -466,44 +466,46 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
466
466
|
AND m.role != 1
|
|
467
467
|
AND c.document_id != ?
|
|
468
468
|
${e.pathExclusionsFor("consumer_d")}
|
|
469
|
-
${
|
|
469
|
+
${i}`,...r).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function Ak(e){let t=Y(e);return t==="method"||t==="type"||e.endsWith("().")}function Ki(e,t,n={}){let i=ke(e,t);if(!i)return null;let r=Mk(e,i);if(!r||e.isIgnored(r.relative_path))return null;let o=[],s=0,a=Ok(e,r.relative_path),c=n.semantic===!1?new Map:Yn(e,a);for(let l of a){let u=jk(e,r,l,c.get(l.symbolId)??new Set);s+=u,o.push({symbol:l.symbol,shortName:y(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:u,riskLevel:Bk(u)})}return{file:r.relative_path,symbols:o,totalExternalConsumers:s}}function Mk(e,t){return e.get(`SELECT id, relative_path FROM documents
|
|
470
470
|
WHERE relative_path = ?
|
|
471
471
|
${e.pathExclusionsFor("documents")}
|
|
472
|
-
LIMIT 1`,t)??null}function
|
|
472
|
+
LIMIT 1`,t)??null}function Ok(e,t){return new E(e).definitionsForFile(t).sort((n,i)=>n.startLine-i.startLine||n.endLine-i.endLine)}function jk(e,t,n,i){let r=e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
473
473
|
FROM mentions m
|
|
474
474
|
JOIN chunks c ON m.chunk_id = c.id
|
|
475
475
|
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
476
476
|
WHERE m.symbol_id = ?
|
|
477
477
|
AND m.role != 1
|
|
478
|
-
AND c.document_id != ?`,n.symbolId,t.id);return new Set([...
|
|
478
|
+
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 Bk(e){return e>10?"high":e>0?"medium":"low"}function lo(e,t={}){let{scope:n,minLoc:i=1,maxDepth:r=5,scanLimit:o}=t,s=new E(e),a=Hk(e,n,i,o),c=new $a;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(Im(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 b=s.calleeMap(d,{semantic:!1}),S=new Set;for(let _ of d)for(let w of b.get(_.symbolId)??[])m.has(w.symbol)||S.add(w.symbol);let v=[];for(let _ of S){m.add(_);let w=Nm(e,_);if(!w||e.isIgnored(w.relativePath)||Re(e,w.relativePath)||ne(e,w.symbol,w.relativePath)||s.fileKind(w.relativePath)==="test"||s.hasSuppressionComment(w))continue;let C=qk(e,w,c);C.removable?v.push(Vk(w,"cascade")):C.blockingFiles.length>0&&u.push({shortName:y(w.symbol),file:w.relativePath,blockingFiles:C.blockingFiles.slice(0,3)})}if(v.length===0)break;for(let _ of v)c.add(_);l.push(Im(e,g,v,c)),d=v.map(_=>_.definition).filter(_=>_!==null)}let p=l.reduce((g,b)=>g+b.loc,0),h=l.reduce((g,b)=>g+b.entries.length,0);return{batches:l,totalSymbols:h,totalLoc:p,blocked:u}}function Hk(e,t,n,i){let r=xt(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:i,semantic:!1}),o=[];for(let s of r.symbols)s.kind==="dead-code"&&(Re(e,s.relativePath)||ne(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:Nm(e,s.symbol)}));return o}function Vk(e,t){return{symbol:e.symbol,shortName:y(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function Nm(e,t){let n=e.get(`SELECT d.relative_path
|
|
479
479
|
FROM global_symbols gs
|
|
480
480
|
JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
481
481
|
JOIN documents d ON d.id = der.document_id
|
|
482
482
|
WHERE gs.symbol = ?
|
|
483
|
-
LIMIT 1`,t);return n?
|
|
483
|
+
LIMIT 1`,t);return n?G(e,n.relative_path).find(i=>i.symbol===t)??null:null}function qk(e,t,n){let i=an(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 Im(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=G(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 $a=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 VN}from"crypto";import{existsSync as nc,readFileSync as fp}from"fs";import{execFileSync as Uk}from"child_process";var Pm=2e3,_m=50,Wk=8,Gk=3,zk=2160*60*60,Kk=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,Jk=3,Qk=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,Xk=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function Aa(e){let t=X(e,{clearGroups:["whole-project"]});return(n,i)=>{let r=Zk(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 Yk=Aa("git-commit-history");function Ht(e){return Yk(e,eD)}function Zk(e){try{return uo(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function uo(e,t){return Uk("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function eD(e,t){let n;try{n=uo(e,["log","--no-merges","--name-only","-n",String(Pm),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let i=[],r=0;for(let o of n.split("")){if(o.trim()==="")continue;let s=o.indexOf(`
|
|
484
484
|
`),a=s>=0?o.slice(0,s):o,[c,l,u]=a.split("\0");if(!c||!l)continue;let d=s>=0?o.slice(s+1).split(`
|
|
485
|
-
`).map(m=>m.trim()).filter(m=>m!==""):[];if(d.length>
|
|
486
|
-
`).map(
|
|
487
|
-
`),s=o>=0?
|
|
488
|
-
`)){let u=l.trim();u!==""&&n.set(u,{commitsAgo:r,addedAt:c})}}return n}function Xi(e,t={}){let{minTogether:n=4,minConfidence:r=.6,maxFilesPerCommit:i=Cd}=t,o=mn(e);if(!o)return null;let s=new Map,a=new Map;for(let l of o.commits){let u=[...new Set(l.files)].sort();if(!(u.length>i)){for(let d of u)s.set(d,(s.get(d)??0)+1);for(let d=0;d<u.length;d++)for(let m=d+1;m<u.length;m++){let f=`${u[d]}\0${u[m]}`;a.set(f,(a.get(f)??0)+1)}}}let c=[];for(let[l,u]of a){if(u<n)continue;let[d,m]=l.split("\0"),f=s.get(d)??u,g=s.get(m)??u,h=Math.max(u/f,u/g);h<r||c.push({fileA:d,fileB:m,together:u,confidence:h,changesA:f,changesB:g})}return c.sort((l,u)=>u.together-l.together||u.confidence-l.confidence||l.fileA.localeCompare(u.fileA)),c}import{existsSync as LR}from"fs";import{join as IR}from"path";function ca(e){return aa.test(e)}var aa=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|CHANGELOG(?:\.[a-z]+)?|.*\.map)$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function pn(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=mn(e),c=t!==void 0,l=Xi(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=ne(e),d=kR(e),m=n.includeLinked===!0||c,f=[];for(let g of l){if(aa.test(g.fileA)||aa.test(g.fileB)||!Ld(e,g.fileA)||!Ld(e,g.fileB)||c&&!g.fileA.includes(t)&&!g.fileB.includes(t)||!c&&(z(g.fileA)==="test"||z(g.fileB)==="test"||DR(g.fileA,g.fileB)))continue;let h=wR(u,d,g.fileA,g.fileB);if(!(!m&&h)&&(f.push({...g,structurallyLinked:h}),f.length>=o))break}return{available:!0,commitsAnalyzed:a.commits.length,findings:f}}function Ld(e,t){return LR(IR(e.config.projectRoot,t))}function DR(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 kR(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function wR(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))}import{execFileSync as rt}from"child_process";import{existsSync as NR,readFileSync as PR}from"fs";import{basename as Id}from"path";var la="Unable to compute git diff.";function Kn(e,t={}){let n=t.plan??it(e,t);return n.note?_R(n.note,n.changedFileLines):n.changedFiles.length===0?ER(n.changedFileLines):Zi(n.changedFiles,[Yi(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function it(e,t={}){let{base:n="HEAD"}=t;try{let r=FR(e.config.projectRoot,n),i=jR(e,r),o=BR(e,TR(e.config.projectRoot,n));return{changedFileLines:r,changedFiles:i,changedRanges:o,renamedFiles:AR(e.config.projectRoot,n,i),note:r.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:la}}}function Yi(e,t,n,r=[]){let i=new N(e),o=new Set(n),s=HR(r),a=[],c=new Map,l=t.flatMap(g=>i.definitionsForFile(g)).filter(KR).filter(g=>qR(g,s)).sort((g,h)=>g.relativePath.localeCompare(h.relativePath)||g.startLine-h.startLine),u=l.map(g=>g.symbolId),d=JR(e,u),m=GR(e,u,n),f=Un(e,l.filter(g=>d.get(g.symbolId)===0));for(let g of l)UR(e,g,o,a,c,f.get(g.symbolId)??new Set,d.get(g.symbolId)??0,m.get(g.symbolId)??new Set);return{changedSymbols:a,consumerEntries:[...c.entries()].map(([g,h])=>({file:g,symbols:[...h].sort()}))}}function Zi(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=zR(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:i.length}}}function _R(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function ER(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 FR(e,t){let n=rt("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=rt("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=rt("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,r,i].flatMap(o=>o.split(`
|
|
489
|
-
`)).map(o=>o.trim()).filter(o=>o.length>0))]}function
|
|
490
|
-
`),...
|
|
491
|
-
`)].map(
|
|
492
|
-
`).map(t=>t.trim()).filter(t=>t.length>0)}function
|
|
493
|
-
ORDER BY id`).map(
|
|
494
|
-
`)){if(
|
|
485
|
+
`).map(m=>m.trim()).filter(m=>m!==""):[];if(d.length>_m){r+=1;continue}i.push({hash:c,timestamp:Number(l)||0,subject:u??"",files:d})}return{head:t,commits:i,skippedBulkCommits:r}}function tD(e){return Kk.test(e.subject)}function mo(e){let t=Ht(e);if(!t)return null;let n=new Map;for(let i of t.commits){let r=tD(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 Tm(e){let t=Ht(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:Em(n,.5),p90FilesPerCommit:Em(n,.9),commitsAnalyzed:n.length}}function Em(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var nD=Aa("git-tracked-files");function Ma(e){return nD(e,t=>{try{let n=uo(t,["ls-files"]);return new Set(n.split(`
|
|
486
|
+
`).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}})}var iD=Aa("git-file-adds");function Fm(e){return iD(e,t=>rD(t))}function rD(e){let t;try{t=uo(e,["log","--no-merges","--diff-filter=A","--name-only","-n",String(Pm),"--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(`
|
|
487
|
+
`),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(`
|
|
488
|
+
`)){let u=l.trim();u!==""&&n.set(u,{commitsAgo:i,addedAt:c})}}return n}function $m(e,t={}){let n=Ht(e);return n?Mm(n,t):null}function Am(e,t,n={}){let i=Ht(e);return i?t.size===0?[]:Mm(i,n,t):null}function Mm(e,t,n){let{minTogether:i=4,minConfidence:r=.6,maxFilesPerCommit:o=_m}=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 p=oD(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 b=g+1;b<m.length;b++){if(n&&!n.has(m[g])&&!n.has(m[b]))continue;let S=`${m[g]}\0${m[b]}`,v=a.get(S)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};v.together+=1,p?v.broadTogether+=1:v.focusedTogether+=1,d.timestamp>v.lastTogetherAt&&(v.lastTogetherAt=d.timestamp),v.timestamps.push(d.timestamp),v.subjects.push(d.subject),a.set(S,v)}}let l=[],u=c-zk;for(let[d,m]of a){let p=m.together;if(p<i)continue;let[h,g]=d.split("\0"),b=s.get(h)??p,S=s.get(g)??p,v=Math.max(p/b,p/S);if(v<r)continue;let _=m.broadTogether/p,w=m.timestamps.filter(C=>C>=u).length;l.push({fileA:h,fileB:g,together:p,confidence:v,changesA:b,changesB:S,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:_,lastTogetherAt:m.lastTogetherAt,recentTogether:w,commitScope:aD(m.broadTogether,p),recency:w>0?"recent":"stale",subjectContext:cD(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function oD(e){return e.length>=Wk?!0:sD(e).size>=Gk}function sD(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 aD(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function cD(e){let t=new Set,n=[],i=[];for(let r of e){!i.includes(r)&&i.length<Jk&&i.push(r);for(let o of lD(r))t.add(o);for(let o of r.match(Qk)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:i,externalIssueLabelStatus:"unavailable"}}function lD(e){let t=new Set,n=Xk.exec(e)?.[1]?.toLowerCase();return n&&t.add(uD(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 uD(e){return e==="feat"?"feature":e}import{existsSync as dD}from"fs";import{join as mD}from"path";function ja(e){return Oa.test(e)}var Oa=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|CHANGELOG(?:\.[a-z]+)?|.*\.map)$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function yn(e,t,n={}){let{minTogether:i=4,minConfidence:r=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=Ht(e),c=t!==void 0,l=$m(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=te(e),d=Hm(e),m=Va(e,u,d),p=n.includeLinked===!0||c,h=[];for(let g of l){if(Oa.test(g.fileA)||Oa.test(g.fileB)||!Om(e,g.fileA)||!Om(e,g.fileB)||c&&!g.fileA.includes(t)&&!g.fileB.includes(t)||!c&&(K(g.fileA)==="test"||K(g.fileB)==="test"||pD(g.fileA,g.fileB)))continue;let b=m(g.fileA,g.fileB);if(!p&&b)continue;let S=Ba(g.fileA,g.fileB),v=Ha(g,S,b);if(h.push({...g,structurallyLinked:b,partnerClass:S.partnerClass,partnerClassReasons:S.reasons,...v?{declaredCouplingSuggestion:v}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:a.commits.length,findings:h}}function Om(e,t){return dD(mD(e.config.projectRoot,t))}function Ba(e,t){let n=jm(e),i=jm(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=LD(n.tokens,i.tokens).filter(c=>!vD.has(c));return Bm(e,t)||a.length>=2?(o(Bm(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 Ha(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!CD.has(t.partnerClass))return;let i=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${wD(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 Va(e,t=te(e),n=Hm(e)){return(i,r)=>fD(t,n,i,r)}function pD(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 Hm(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function fD(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 gD=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,hD=/(?:^|\/)(?:\.[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,bD=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,yD=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,SD=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,xD=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,CD=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),vD=new Set(["src","lib","app","test","tests","spec","index","main","utils","util","types","type","config","docs","doc"]);function jm(e){let t=e.replace(/\\/g,"/"),n=new Set;return gD.test(t)&&n.add("doc"),hD.test(t)&&n.add("config"),bD.test(t)&&n.add("schema"),yD.test(t)&&n.add("script"),SD.test(t)&&n.add("model"),xD.test(t)&&n.add("view"),K(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:RD(t)}}function Bm(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 RD(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 LD(e,t){let n=new Set(t);return[...new Set(e.filter(i=>n.has(i)))].sort()}function wD(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as st}from"child_process";import{existsSync as kD,readFileSync as DD}from"fs";import{basename as Vm}from"path";var qa="Unable to compute git diff.";function ii(e,t={}){let n=t.plan??at(e,t);return n.note?ID(n.note,n.changedFileLines):n.changedFiles.length===0?ND(n.changedFileLines):fo(n.changedFiles,[po(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function at(e,t={}){let{base:n="HEAD"}=t;try{let i=ED(e.config.projectRoot,n),r=AD(e,i),o=MD(e,PD(e.config.projectRoot,n));return{changedFileLines:i,changedFiles:r,changedRanges:o,renamedFiles:_D(e.config.projectRoot,n,r),note:i.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:qa}}}function po(e,t,n,i=[]){let r=new E(e),o=new Set(n),s=jD(i),a=[],c=new Map,l=t.flatMap(h=>r.definitionsForFile(h)).filter(GD).filter(h=>BD(h,s)).sort((h,g)=>h.relativePath.localeCompare(g.relativePath)||h.startLine-g.startLine),u=l.map(h=>h.symbolId),d=qD(e,u),m=UD(e,u,n),p=Yn(e,l.filter(h=>d.get(h.symbolId)===0));for(let h of l)VD(e,h,o,a,c,p.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 fo(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=WD(n);return{changedFiles:[...e],changedSymbols:i,affectedConsumers:r,summary:{totalChangedFiles:e.length,totalChangedSymbols:i.length,totalAffectedFiles:r.length}}}function ID(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function ND(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 ED(e,t){let n=st("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=st("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=st("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,i,r].flatMap(o=>o.split(`
|
|
489
|
+
`)).map(o=>o.trim()).filter(o=>o.length>0))]}function PD(e,t){let n=st("git",["diff","--unified=0",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=st("git",["diff","--unified=0","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return Km([...Wm(n),...Wm(i)])}function Ji(e,t,n){try{return st("git",["show",`${t}:./${n}`],{encoding:"utf-8",cwd:e,timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return null}}function _D(e,t,n){if(n.length===0)return[];let i=new Map,r=new Set;for(let s of FD(e,t))n.includes(s.to)&&(i.set(s.to,s),r.add(s.from));let o=TD(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)||!kD(`${e}/${s}`))continue;let a=o.filter(u=>!r.has(u)).filter(u=>Vm(u)===Vm(s));if(a.length===0)continue;let c=DD(`${e}/${s}`,"utf-8"),l=a.map(u=>({from:u,to:s,similarity:$D(Ji(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 TD(e,t){let n=st("git",["diff","--name-only","--diff-filter=D",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=st("git",["diff","--name-only","--diff-filter=D","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([...Um(n),...Um(i)])]}function FD(e,t){let n=st("git",["diff","--name-status","--find-renames",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=st("git",["diff","--name-status","--find-renames","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4});return[...n.split(`
|
|
490
|
+
`),...i.split(`
|
|
491
|
+
`)].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 $D(e,t){let n=new Set(qm(e)),i=new Set(qm(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 qm(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function Um(e){return e.split(`
|
|
492
|
+
`).map(t=>t.trim()).filter(t=>t.length>0)}function AD(e,t){let n=zm(e),i=[];for(let r of t){let o=n(r);o&&!e.isIgnored(o)&&i.push(o)}return i}function MD(e,t){let n=zm(e),i=[];for(let r of t){let o=n(r.file);o&&!e.isIgnored(o)&&i.push({...r,file:o})}return Km(i)}function zm(e){let t=e.all(`SELECT relative_path FROM documents
|
|
493
|
+
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 Wm(e){let t=[],n=null;for(let i of e.split(`
|
|
494
|
+
`)){if(i.startsWith("+++ ")){n=OD(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 OD(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function Km(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 jD(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}function BD(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(i=>HD(e.startLine,e.endLine,i.startLine,i.endLine))}function HD(e,t,n,i){return e<=i&&n<=t}function VD(e,t,n,i,r,o,s,a){let c=Math.max(s,o.size);if(!zD(t,c))return;let l=y(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)Gm(e,n,r,u,l);for(let u of o)Gm(e,n,r,u,l)}function qD(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
|
|
495
495
|
FROM mentions m
|
|
496
496
|
JOIN chunks c ON m.chunk_id = c.id
|
|
497
497
|
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
498
498
|
AND m.role != 1
|
|
499
|
-
GROUP BY m.symbol_id`,...t);return new Map(n.map(
|
|
499
|
+
GROUP BY m.symbol_id`,...t);return new Map(n.map(i=>[i.symbol_id,i.fan_in]))}function UD(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
|
|
500
500
|
FROM mentions m
|
|
501
501
|
JOIN chunks c ON m.chunk_id = c.id
|
|
502
502
|
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
503
503
|
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
504
504
|
AND m.role != 1
|
|
505
505
|
AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
|
|
506
|
-
${e.pathExclusionsFor("ref_d")}`,...t,...n),
|
|
506
|
+
${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 Gm(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 WD(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function GD(e){return!(Pt(e.symbol)||e.parentTypeName!==null&&!be(e.symbol))}function zD(e,t){return be(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}function bo(e,t){let n=KD(e,t)??JD(e,t)??QD(e,t)??XD(e,t);return YD(e,n,t)}function KD(e,t){let n=-1,i=null;for(let r=0;r<=t;r+=1){let o=Ua(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(Ua(e[r]??"")===i)return{start:n,end:r+1};return{start:n,end:e.length}}function Ua(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function JD(e,t){if(!go(e[t]??""))return null;let n=t;for(;n>0&&go(e[n-1]??"");)n-=1;let i=t+1;for(;i<e.length&&go(e[i]??"");)i+=1;return{start:n,end:i}}function go(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function QD(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(ho(o)!==null)break;if(Wa(o)!==null)return null;n-=1}if(n<0)return null;let i=ho(e[n]??"");if(i===null)return null;let r=n+1;for(;r<e.length;){let o=e[r]??"",s=ho(o);if(s!==null){if(s<=i)break;r+=1;continue}if(Wa(o)!==null)break;r+=1}return{start:n,end:r}}function ho(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function XD(e,t){let n=e[t]??"";if(Qm(n)||n.trim().length===0)return{start:t,end:t+1};let i=t;for(;i>0&&Jm(e[i-1]??"");)i-=1;let r=t+1;for(;r<e.length&&Jm(e[r]??"");)r+=1;return{start:i,end:r}}function Jm(e){return Wa(e)===null}function Wa(e){return e.trim().length===0?"blank":Qm(e)?"heading":Ua(e)?"fence":go(e)?"table":ho(e)!==null?"list":null}function Qm(e){return/^#{1,6}\s+/.test(e.trim())}function YD(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(`
|
|
507
|
+
`).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}import{existsSync as Ym,readFileSync as za}from"fs";import{join as Xi}from"path";var Qi=/\.(?:md|mdx|rst|txt)$/i;function ZD(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var eI=3,Zm=/[A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6}\b/g;function Ka(e,t={}){let{doc:n,limit:i=20,minCoupling:r=eI}=t,o=iI(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&&!tp(e,a)||n!==void 0&&!Ym(Xi(e.config.projectRoot,a)))continue;let c=Math.max(0,...o.changeTimes.get(a)??[]),l=tI(e,a),u=new Map,{resolved:d,broken:m,citations:p}=ip(e,a,o.tracked,o.trackedBySuffix,o.everSeenInHistory),h=new Map(p.map(b=>[b.file,b.contexts]));for(let b of d){if(b===a||Qi.test(b))continue;let S=(o.changeTimes.get(b)??[]).filter(v=>v>c).length;S!==0&&u.set(b,{file:b,evidence:"reference",coChanges:0,changesSinceDocUpdate:S,...Ga("reference",l),citationContexts:h.get(b)})}for(let[b,S]of o.coupling.get(a)??[]){if(S<r||!o.tracked.has(b))continue;let v=(o.changeTimes.get(b)??[]).filter(w=>w>c).length;if(v===0)continue;let _=u.get(b);_?(_.evidence="both",_.coChanges=S,Object.assign(_,Ga("both",l))):u.set(b,{file:b,evidence:"co-change",coChanges:S,changesSinceDocUpdate:v,...Ga("co-change",l)})}if(u.size===0&&m.length===0)continue;let g=[...u.values()].sort((b,S)=>S.changesSinceDocUpdate-b.changesSinceDocUpdate);s.push({doc:a,docLastChangedAt:c,staleness:g.reduce((b,S)=>b+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 tI(e,t){let n;try{n=za(Xi(e.config.projectRoot,t),"utf8").slice(0,6e3)}catch{return{docIntent:"unknown",reasons:["doc text unavailable"]}}let i=`${t}
|
|
508
|
+
${n}`.toLowerCase(),r=Xm(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=Xm(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 Xm(e,t){return t.filter(n=>e.includes(n))}function Ga(e,t){return{actionTier:nI(e,t.docIntent),docIntent:t.docIntent,docIntentReasons:t.reasons}}function nI(e,t){return t==="historical-note"?"support":e==="co-change"?"signal":"direct"}function iI(e){let t=Ht(e);if(!t)return null;let n=Ma(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=>Qi.test(u)),l=a.filter(u=>!Qi.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=>Qi.test(s)),everSeenInHistory:o,historyCommitCount:t.commits.length,tracked:n,trackedBySuffix:np(n)}}function ep(e,t){let n=Ma(e)??new Set,i=np(n),r=[];for(let o of n){if(!tp(e,o))continue;let{resolved:s,citations:a}=ip(e,o,n,i,new Set),c=[...s].filter(l=>t.has(l));if(c.length>0){let l=c.sort(),u=new Set(l),d=a.filter(m=>u.has(m.file));r.push({doc:o,cited:l,citations:d,citedClaims:Ja(d.flatMap(m=>m.contexts)).slice(0,3)})}}return r}function tp(e,t){return Qi.test(t)&&!ZD(t)&&Ym(Xi(e.config.projectRoot,t))}function np(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 ip(e,t,n,i,r){let o=new Set,s=new Set,a=sI(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=rI(e,t,a),l=new Map,u=(d,m)=>{let p=c.get(m);if(!p||p.length===0)return;let h=l.get(d)??[];h.push(...p),l.set(d,Ja(h).slice(0,3))};for(let d of a){if(n.has(d)){o.add(d),u(d,d);continue}let m=i.get(d);if(m&&m.length===1){o.add(m[0]),u(m[0],d);continue}m&&m.length>1||r.has(d)&&s.add(d)}return{resolved:o,broken:[...s],citations:[...l].map(([d,m])=>({file:d,contexts:m}))}}function rI(e,t,n){let i;try{i=za(Xi(e.config.projectRoot,t),"utf-8").split(/\r?\n/)}catch{return new Map}let r=new Set(n),o=new Map;for(let s=0;s<i.length;s+=1){let a=i[s]??"";for(let c of a.matchAll(Zm)){let l=c[0].replace(/^\.?\//,"");if(!r.has(l))continue;let u=bo(i,s);if(u.length===0)continue;let d=o.get(l)??[];d.push(u),o.set(l,Ja(d).slice(0,3))}}return o}function Ja(e){let t=[];for(let n of new Set(e))t.some(i=>oI(i,n))||t.push(n);return t}function oI(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}function sI(e,t){let n;try{n=za(Xi(e.config.projectRoot,t),"utf-8")}catch{return null}let i=Gt(e,t,n),r=Cr(e,"doc-path-tokens",t,i);if(r!==null)try{return JSON.parse(r)}catch{}let o=[...new Set([...n.matchAll(Zm)].map(s=>s[0].replace(/^\.?\//,"")))];return vr(e,"doc-path-tokens",t,i,JSON.stringify(o)),o}import{existsSync as SN,readFileSync as xN,writeFileSync as CN}from"fs";import{isAbsolute as vN,join as RN}from"path";var se={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 Yi from"path";function Sn(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 Qa(e,t){if(e===t)return"ok";let n=yo(e),i=yo(t);return n&&i?aI(n,i)?"ok":"violation":cI(e,t)}function rp(e,t){let n=yo(Sn(e)),i=yo(Sn(t));return!!n&&!!i}function yo(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function aI(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 cI(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 xn(e,t){let{scope:n,minDeviation:i=5}=t??{},r=t?.semantic!==!1,s=new E(e).fileDependencyGraph(n),a=gI(e,n);return mI([...lI(e,s,a,{semantic:r}),...uI(s),...dI(s,i)])}function lI(e,t,n,i){let r=[];for(let[o,s]of t){if(Rt(o))continue;let a=n.get(o)??new Set;for(let c of s)if(!Rt(c)&&!a.has(c)){if(i.semantic&&CI(e,o,c)||vI(e,o,c)||RI(e,o,c)||xI(c)||wI(e,o,c)||LI(c))continue;r.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 r}function uI(e){let t=[],n=SI(e);for(let[i,r]of e){if(Rt(i))continue;let o=Sn(i);for(let s of r){if(Rt(s))continue;let a=Sn(s);if(o===a)continue;let c=Qa(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 dI(e,t){let n=[];for(let[i,r]of pI(e)){let o=r.filter(a=>!Rt(a));if(o.length<t)continue;let s=fI(e,o);for(let a of o)for(let c of e.get(a)??[])Rt(c)||(s.get(c)??0)===1&&Yi.dirname(c)!==i&&Yi.dirname(c)!==Yi.dirname(i)&&(rp(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 mI(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 pI(e){let t=new Map;for(let n of e.keys()){let i=Yi.dirname(n),r=t.get(i);r||(r=[],t.set(i,r)),r.push(n)}return t}function fI(e,t){let n=new Map;for(let i of t)for(let r of e.get(i)??[])Rt(r)||n.set(r,(n.get(r)??0)+1);return n}function gI(e,t){let n=new Map;return hI(e,n,t),yI(e,n),n}function hI(e,t,n){for(let i of bI(e,n))op(e,t,i.from_file,i.to_file)}function bI(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
|
|
507
509
|
FROM mentions m
|
|
508
510
|
JOIN chunks c ON m.chunk_id = c.id
|
|
509
511
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -519,30 +521,32 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
519
521
|
WHERE d1.id != d2.id
|
|
520
522
|
AND m.role != 1
|
|
521
523
|
${e.pathExclusionsFor("d1","d2")}
|
|
522
|
-
${n}`)}function
|
|
523
|
-
`)
|
|
524
|
-
`);for(let a=
|
|
524
|
+
${n}`)}function yI(e,t){new E(e).scanSourceReferences({paths:M(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||op(e,t,i.sourceFile,i.target.relativePath))})}function op(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 SI(e){let t=new Map;for(let[i,r]of e){if(Rt(i))continue;let o=Sn(i);for(let s of r){if(Rt(s))continue;let a=Sn(s);if(o===a||Qa(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 xI(e){return e.includes("types")||e.endsWith(".d.ts")}function CI(e,t,n){let i=_i(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.isUsed)}function vI(e,t,n){let i=de(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.used)}function RI(e,t,n){let i=de(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.every(r=>r.isTypeOnly===!0)}function LI(e){return e.endsWith(".vue")}function wI(e,t,n){let i=de(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 Rt(e){let t=K(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||kI(Yi.basename(e)))}function kI(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 sp,extname as ap}from"path";function So(e,t,n,i,r,o){let s=new Set;II(e,t,n,i)&&s.add(r);for(let a of o)a.value&&DI(s,a.label,a.value);return[...s].slice(0,6)}function DI(e,t,n){let i=NI(n);t.endsWith("name")&&EI(i)&&e.add(`${t} has type-guard boundary shape`);for(let r of i){let o=PI.get(r);o&&e.add(`${t} has ${o} term: ${r}`)}}function II(e,t,n,i){if(n<=0)return!1;let r=Pe(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(gi(s)===i)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function NI(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 EI(e){return e.some(t=>_I.has(t))&&e.some(t=>TI.has(t))}var PI=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"]]),_I=new Set(["can","has","is","should"]),TI=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function Cn(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new E(e);return qe({candidates:()=>qI(s,n,i),orderCandidates:ro,scanLimit:o,prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>FI(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:r})}function FI(e,t,n){let i=VI(n);if(i.size!==1||!ps(e,t.relativePath,t.startLine,t.endLine))return null;let[,r]=[...i.entries()][0],o=$I(e,t,r),s=MI(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:y(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:q(t),forwardsTo:r.symbol,forwardsToShort:y(r.symbol),forwardsToFile:r.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:AI(a,o,s)}}function $I(e,t,n){return So(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:y(t.symbol)},{label:"callee name",value:y(n.symbol)},{label:"passthrough module",value:sp(t.relativePath,ap(t.relativePath))},{label:"callee module",value:sp(n.file,ap(n.file))}])}function AI(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(BI);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 MI(e,t){return OI(e,t)?Kn(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:ne(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function OI(e,t){let n=Pe(e,t.relativePath);if(n.length===0)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
|
|
525
|
+
`);return UI.test(i)?!0:jI(n,F(t.symbol))}function jI(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${HI(t)}\\b`);return e.some(i=>n.test(i))}function BI(e){return e.includes("public surface")}function HI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function VI(e){let t=e.some(i=>oe(i.symbol))?e.filter(i=>oe(i.symbol)):e,n=new Map;for(let i of t)n.has(i.symbol)||n.set(i.symbol,i);return n}function qI(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:3,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0})}var UI=/^\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 E(e),u=l.scopedDefinitions(n),d=iN(l,n),m={high:0,medium:1,low:2};return qe({candidates:()=>WI(e,l,u,{minLoc:i,maxLoc:r}),orderCandidates:(p,h)=>q(h)-q(p)||p.relativePath.localeCompare(h.relativePath),scanLimit:a,prepare:p=>({consumerFileMap:GI(l,p,{semantic:c}),singletonBackedClassIds:XI(e,l,u,p,{semantic:c}),candidateIndex:zI(p)}),evaluate:(p,h)=>{if(h.singletonBackedClassIds.has(p.symbolId))return null;let g=KI(e,p,h.consumerFileMap,h.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!oN(g.definition,g.realConsumers.length,d))return null;let b=JI(e,g);return!s&&b.confidence==="low"?null:b},orderResults:(p,h)=>m[p.confidence]-m[h.confidence]||h.loc-p.loc||p.file.localeCompare(h.file)||p.startLine-h.startLine,limit:o})}function WI(e,t,n,i){return n.filter(r=>r.isTypeLike&&q(r)>=i.minLoc).filter(r=>q(r)<=i.maxLoc).filter(r=>!e.isIgnored(r.relativePath)).filter(r=>K(r.relativePath)!=="test").filter(r=>!ne(e,r.symbol,r.relativePath)).filter(r=>!rN(r.symbol)).filter(r=>!t.hasSuppressionComment(r))}function GI(e,t,n){return bn(e,t,{semantic:n.semantic})}function zI(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=F(n.symbol);r&&i.set(r,n)}return t}function KI(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}=co(e,t,o),l=sN(e,t,n,i);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function JI(e,t){let n=up(e,t.definition.relativePath,t.definition.startLine),i=lp(t.definition.relativePath)?!0:aN(e,t.definition),{confidence:r,reason:o}=cN(t.realConsumers.length,n,i),s=QI(t.realConsumers.length,n,i);return{symbol:t.definition.symbol,shortName:y(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:q(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 QI(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 XI(e,t,n,i,r){let o=ZI(e,YI(n),i),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=bn(t,s,{semantic:r.semantic}),c=new Set;for(let{singleton:l,classId:u}of o)tN(e,l,a)&&c.add(u);return c}function YI(e){let t=new Map;for(let n of e){let i=F(n.symbol);i&&t.set(cp(n.relativePath,i),n)}return t}function ZI(e,t,n){let i=[];for(let r of n){let o=eN(e,t,r);o&&i.push({singleton:o,classId:r.symbolId})}return i}function eN(e,t,n){if(up(e,n.relativePath,n.startLine)!=="class")return null;let i=F(n.symbol);if(!i)return null;let r=nN(e,n.relativePath,i);return r?t.get(cp(n.relativePath,r))??null:null}function tN(e,t,n){let i=F(t.symbol),r=n.get(t.symbolId);return!i||!r?!1:[...r].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!Da(e,o,i))}function cp(e,t){return`${e}\0${t}`}function nN(e,t,n){let i=A(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 iN(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function rN(e){let t=ue(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 lp(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 oN(e,t,n){return!(lp(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function sN(e,t,n,i){let r=gs(e,t.relativePath),o=F(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 up(e,t,n){let i=A(e,t);if(!i)return"other";let r=i.split(`
|
|
526
|
+
`),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 aN(e,t){let n=A(e,t.relativePath);if(!n)return!1;let i=F(t.symbol);if(!i)return!1;let r=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${r}\\b`),s=n.split(`
|
|
527
|
+
`);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function cN(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 ri,extname as xo}from"path";function Rn(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new E(e),a=hN(s.fileDependencyGraph(n));return qe({candidates:()=>uN(s,n,i),orderCandidates:ro,scanLimit:o,prepare:c=>({callerFileMap:bn(s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>lN(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:r})}function lN(e,t,n,i){let r=dN(e,t,n,i.callerFileMap);if(r.length!==1)return null;let o=r[0],s=mN(e,n.symbolId,o);if(!s)return null;let a=pN(t,e,o,n.symbol,s);if(a&&An(a.symbol))return null;let{fanIn:c,source:l}=fN(i.callerFileMap,i.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=yN(e,n,o,a);return{symbol:n.symbol,shortName:y(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:q(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?y(a.symbol):ri(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function uN(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:2,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0})}function dN(e,t,n,i){let r=ri(n.relativePath,xo(n.relativePath)),o=[...i.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>ri(s,xo(s))!==r).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return co(e,n,o).realConsumers}function mN(e,t,n){return e.get(`SELECT c.start_line, c.end_line
|
|
525
528
|
FROM mentions m
|
|
526
529
|
JOIN chunks c ON m.chunk_id = c.id
|
|
527
530
|
JOIN documents d ON c.document_id = d.id
|
|
528
531
|
WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
|
|
529
|
-
LIMIT 1`,t,n)}function
|
|
530
|
-
`),{path:
|
|
532
|
+
LIMIT 1`,t,n)}function pN(e,t,n,i,r){let o=e.definitionsForFile(n),s=gN(t,n,i,r.start_line,r.end_line);return Me(o,s)}function fN(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:bN(t,n),source:"file"}}function gN(e,t,n,i,r){let o=F(n);if(!o)return i;let s=St(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 hN(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 bN(e,t){let n=e.get(t)??0;if(n>0)return n;let i=ri(t,xo(t)),r=0;for(let[o,s]of e)o!==t&&ri(o,xo(o))===i&&s>r&&(r=s);return r}function yN(e,t,n,i){return So(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:y(t.symbol)},{label:"caller name",value:i?.symbol?y(i.symbol):ri(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var LN=75e3,wN=5e3,kN=2500;function DN(e){let t=Ae(e);return t.symbols>=LN||t.documents>=wN?kN:void 0}var IN=".scipquery-baseline.json";function Co(e,t){return t&&vN(t)?t:RN(e.config.projectRoot,t??IN)}function Xa(e,t={}){let{scope:n}=t,i=DN(e),r=[],o=xt(e,{scope:n,...se.dead,scanLimit:i});for(let s of o.symbols)Re(e,s.relativePath)||ne(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&r.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of ln(e,{scope:n,...se.isolated,scanLimit:i}))Re(e,s.relativePath)||ne(e,s.symbol,s.relativePath)||r.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of cn(e,{scope:n}))s.kind==="real"&&r.push(`cycle:${NN(s.path)}`);for(let s of Ct(e,{scope:n,...se.similar,scanLimit:i}))r.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of hn(e,{scope:n,...se.extract,scanLimit:i}))r.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of Rn(e,{scope:n,...se.wrappers,scanLimit:i}))r.push(`wrapper:${s.file}:${s.shortName}`);for(let s of Cn(e,{scope:n,...se.passthroughs,scanLimit:i}))r.push(`passthrough:${s.file}:${s.shortName}`);for(let s of vn(e,{scope:n,...se.stale,scanLimit:i}))r.push(`stale:${s.file}:${s.shortName}`);for(let s of xn(e,{scope:n,...se.drift}).results)s.kind!=="pattern-deviation"&&r.push(`drift:${s.kind}:${s.file}:${s.dep}`);return[...new Set(r)].sort()}function NN(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 Ya(e,t={}){let n=Xa(e,{scope:t.scope}),i=Co(e,t.path);return CN(i,JSON.stringify({version:1,findings:n},null,2)+`
|
|
533
|
+
`),{path:i,findingCount:n.length}}function Zi(e,t={}){let n=Co(e,t.path);if(!SN(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let i=JSON.parse(xN(n,"utf-8")),r=new Set(i.findings??[]),o=Xa(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 EN=5;function er(e,t={}){let{base:n="HEAD",minContainment:i=.7,minCallees:r=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20}=t,c=t.semantic!==!1,l=t.diffPlan??at(e,{base:n}),u={available:l.note!==qa,base:n,changedFiles:l.changedFiles,helpersChecked:0,skipped:[],findings:[]};if(!u.available||l.changedFiles.length===0)return u;let d=new E(e),m=new Set(l.changedFiles),p=new Map(l.renamedFiles.map(w=>[w.to,w.from])),h=MN(e,d,m,n,p);if(h.length===0)return u;let g=h.slice(0,s);h.length>s&&(u.note=`helper scoring capped at ${s} of ${h.length} new symbols`);let b=so(e,{minCallees:Math.min(3,r),semantic:c}),S=PN(b),v=d.calleeMap(g,{semantic:c}),_=g.map(w=>({def:w,callees:ao((v.get(w.symbolId)??[]).map(C=>C.symbol))}));for(let{def:w,callees:C}of _){let N=y(w.symbol);if(C.size<r){u.skipped.push({helperShortName:N,helperFile:w.relativePath,reason:`fewer than ${r} meaningful callees \u2014 too small to score`});continue}let H=AN(C,S);if(H===0){u.skipped.push({helperShortName:N,helperFile:w.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let B=ON(e,w.symbolId);if(B.length===0){u.skipped.push({helperShortName:N,helperFile:w.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}u.helpersChecked+=1;let he=_N({candidateIndex:S,changed:m,helperCallees:C,helperFile:w.relativePath,helperSymbol:w.symbol,minContainment:i,minSiteCoverage:o,migratedFiles:B});he.length!==0&&(he.sort((ce,Ee)=>dp(Ee.migrationScope)-dp(ce.migrationScope)||Ee.containment-ce.containment||Ee.siteCoverage-ce.siteCoverage||ce.file.localeCompare(Ee.file)),u.findings.push({helperSymbol:w.symbol,helperShortName:N,helperFile:w.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:C.size,specificHelperCalleeCount:H,migratedFiles:B.sort(),leftovers:he.slice(0,EN)}))}return u.findings.sort((w,C)=>(C.leftovers[0]?.containment??0)-(w.leftovers[0]?.containment??0)||w.helperFile.localeCompare(C.helperFile)),u.findings=u.findings.slice(0,a),u}function PN(e){let t=new Map,n=new Map;for(let i of e)for(let r of i.callees){t.set(r,(t.get(r)??0)+1);let o=n.get(r);o||(o=[],n.set(r,o)),o.push(i)}return{candidatesByCallee:n,docFreq:t,ubiquityThreshold:Math.max(8,Math.ceil(Math.sqrt(e.length)))}}function _N(e){let t=[],n=TN(e.helperSymbol,e.helperFile,e.migratedFiles),i=new Set;for(let r of e.helperCallees)for(let o of e.candidateIndex.candidatesByCallee.get(r)??[])i.add(o);for(let r of i){if(r.symbol===e.helperSymbol||e.changed.has(r.file)||r.callees.has(e.helperSymbol))continue;let o=im(e.helperCallees,r.callees);if(o<e.minContainment)continue;let s=[...e.helperCallees].filter(l=>r.callees.has(l)),a=r.callees.size===0?0:s.length/r.callees.size;if(a<e.minSiteCoverage||!s.some(l=>(e.candidateIndex.docFreq.get(l)??0)<=e.candidateIndex.ubiquityThreshold))continue;let c=FN(n,r.symbol,r.file);t.push({symbol:r.symbol,shortName:y(r.symbol),file:r.file,...c,containment:o,siteCoverage:a,uniqueSiteCalleeCount:Math.max(0,r.callees.size-s.length),sharedCallees:s.map(y).sort()})}return t}function dp(e){return e==="same-scope"?2:e==="unknown"?1:0}function TN(e,t,n){let i=new Set([...Za(t),...ec(F(e))]);for(let r of n)for(let o of Za(r))i.add(o);return i}function FN(e,t,n){let i=new Set([...Za(n),...ec(F(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 $N=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 Za(e){return ec(e.replace(/\.[^.]+$/,""))}function ec(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!$N.has(t))}function AN(e,t){let n=0;for(let i of e)(t.docFreq.get(i)??0)<=t.ubiquityThreshold&&(n+=1);return n}function MN(e,t,n,i,r){let o=new Map;return t.productionCallableDefinitions({requireFunctionLikeSymbol:!0}).filter(s=>{if(!n.has(s.relativePath))return!1;let a=r.get(s.relativePath)??s.relativePath,c=o.get(a);return c===void 0&&(c=Ji(e.config.projectRoot,i,a),o.set(a,c)),c===null||!new RegExp(`\\b${jN(s.leaf)}\\b`).test(c)})}function ON(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
|
|
531
534
|
FROM mentions m
|
|
532
535
|
JOIN chunks c ON m.chunk_id = c.id
|
|
533
536
|
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
534
537
|
WHERE m.symbol_id = ?
|
|
535
538
|
AND m.role != 1
|
|
536
|
-
${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}function bI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qr(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=t.files===void 0?null:new Set(t.files),s=new N(e);return Ve({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}).filter(a=>yI(a.relativePath)&&(o===null||o.has(a.relativePath))),scanLimit:i,evaluate:a=>{let c=ee(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=gt(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("_")||SI(l.get(m.name),c.paramsEndLine,c.endLine))break;u.unshift(m.name)}return u.length===0?null:{symbol:a.symbol,shortName:y(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 yI(e){let t=U(e);return t==="typescript"||t==="tsx"||t==="javascript"}function SI(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}var io=["echo","incomplete-migration","co-change-partner","doc-reference","unused-params","new-dead","baseline"];function ha(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}=t,c=new Set(t.skip??[]),l=it(e,{base:n}),u=Kn(e,{base:n,plan:l}),d=u.changedFiles,m=new Set(d),f=NI(e.config.projectRoot,n,l),g={base:n,changedFiles:d,changedSymbols:u.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],note:u.summary.note};if(d.length===0)return g;let h=(b,L)=>{if(c.has(b)){g.skipped.push({check:b,reason:"skipped via --skip"});return}L()};return h("echo",()=>RI(e,u.changedSymbols,m,f,o,a,g)),h("incomplete-migration",()=>LI(e,n,l,s,g)),h("co-change-partner",()=>II(e,m,r,i,g)),h("doc-reference",()=>DI(e,m,g)),h("unused-params",()=>kI(e,d,g)),h("new-dead",()=>wI(e,u.changedSymbols,f,g)),h("baseline",()=>EI(e,g)),CI(g,e.config.suppressions??[]),g}function CI(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let r of e.findings){let i=t.find(o=>vI(o,r));i?e.suppressed.push({finding:r,suppression:i}):n.push(r)}e.findings=n}function vI(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 RI(e,t,n,r,i,o,s){s.checksRun.push("echo");for(let a of t.slice(0,i)){if(r(a))continue;let c=Pr(e,a.symbol,{minSimilarity:o,limit:3});for(let l of c){let u=l.fileA===a.file?l.fileB:l.fileA,d=l.fileA===a.file?l.shortNameB:l.shortNameA,m=l.fileA===a.file?l.symbolB:l.symbolA;if(n.has(u))continue;let f=Sn("echo",a.symbol,a.file,m,u);s.findings.push({id:f,check:"echo",severity:"warning",evidence:"heuristic",confidence:l.similarity,file:a.file,symbol:a.symbol,relatedFiles:[u],message:`${a.shortName} (${a.file}) is ${Math.round(l.similarity*100)}% similar to established ${d} (${u})`,why:[`${a.shortName} was changed in this diff.`,`${d} is outside this diff and scored ${Math.round(l.similarity*100)}% similar by ${l.similarityBasis??"callee"} evidence.`,`Shared evidence: ${l.sharedCallees.slice(0,5).join(", ")||"(none listed)"}.`],remediation:`Extend or reuse ${d} instead of keeping the re-implementation.`,suppressionHint:`scip-query: ignore echo ${f} -- <reason>`})}}t.length>i&&s.skipped.push({check:"echo",reason:`echo check capped at ${i} of ${t.length} changed symbols`})}function LI(e,t,n,r,i){let o=Hr(e,{base:t,maxHelpers:r,diffPlan:n});if(!o.available){i.skipped.push({check:"incomplete-migration",reason:"no git history"});return}i.checksRun.push("incomplete-migration"),o.note&&i.skipped.push({check:"incomplete-migration",reason:o.note});for(let s of o.findings){let a=s.leftovers.map(d=>`${d.shortName} (${d.file}, ${Math.round(d.containment*100)}%)`).join(", "),c=[...s.migratedFiles,...s.leftovers.map(d=>d.file)],l=s.leftovers.length===0?void 0:Math.max(...s.leftovers.map(d=>d.containment)),u=Sn("incomplete-migration",s.helperSymbol,s.helperFile,c.join("|"));i.findings.push({id:u,check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:l,file:s.helperFile,symbol:s.helperSymbol,relatedFiles:c,message:`new helper ${s.helperShortName} (${s.helperFile}) is wired into ${s.migratedFiles.length} file(s), but ${s.leftovers.length} similar un-migrated site(s) remain: ${a}`,why:[`${s.helperShortName} is new in this diff and already referenced by ${s.migratedFiles.join(", ")}.`,`Unchanged site(s) still contain the helper's callee pattern: ${a}.`],remediation:`Migrate the remaining sites to ${s.helperShortName}, or confirm they are intentionally different.`,suppressionHint:`scip-query: ignore incomplete-migration ${u} -- <reason>`})}}function II(e,t,n,r,i){let o=Xi(e,{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;for(let a of o){let c=t.has(a.fileA),l=t.has(a.fileB);if(c===l)continue;let u=c?a.fileA:a.fileB,d=c?a.fileB:a.fileA,m=c?a.changesA:a.changesB,f=m>0?a.together/m:0;if(f<r||ca(d)||ca(u)||!Hd(`${e.config.projectRoot}/${d}`))continue;let g=`${u}|${d}`;if(s.has(g))continue;s.add(g);let h=Sn("co-change-partner",u,d,String(a.together));i.findings.push({id:h,check:"co-change-partner",severity:"warning",evidence:"change-graph",confidence:f,file:u,relatedFiles:[d],message:`${u} changed, but ${d} did not \u2014 they change together ${a.together}x (${Math.round(f*100)}% of the time)`,why:[`${u} is in this diff and ${d} is not.`,`Git history shows ${a.together} co-change(s), which is ${Math.round(f*100)}% of changes to the edited side.`],remediation:`Update ${d} alongside this change, or confirm the coupling no longer holds.`,suppressionHint:`scip-query: ignore co-change-partner ${h} -- <reason>`})}}function DI(e,t,n){n.checksRun.push("doc-reference");for(let r of Fd(e,t)){if(t.has(r.doc))continue;let i=Sn("doc-reference",r.doc,r.cited.join("|"));n.findings.push({id:i,check:"doc-reference",severity:"warning",evidence:"change-graph",confidence:1,file:r.doc,relatedFiles:r.cited,message:`${r.doc} cites ${r.cited.join(", ")} \u2014 changed in this diff, doc untouched`,why:[`${r.cited.join(", ")} changed in this diff.`,`${r.doc} cites the changed file(s) but was not updated in the same diff.`],remediation:`Re-read ${r.doc} and update its claims, or update its citations.`,suppressionHint:`scip-query: ignore doc-reference ${i} -- <reason>`})}}function kI(e,t,n){n.checksRun.push("unused-params");for(let r of qr(e,{files:t,limit:50})){let i=Sn("unused-params",r.symbol,r.file,r.unusedTrailing.join("|"));n.findings.push({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.",suppressionHint:`scip-query: ignore unused-params ${i} -- <reason>`})}}function wI(e,t,n,r){r.checksRun.push("new-dead");let i=new N(e);for(let o of t){if(n(o)||o.fanIn>0||i.fileKind(o.file)==="test"||xe(e,o.file)||le(e,o.symbol,o.file))continue;let s=Sn("new-dead",o.symbol,o.file);r.findings.push({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.",suppressionHint:`scip-query: ignore new-dead ${s} -- <reason>`})}}function NI(e,t,n){let r=new Map(n.renamedFiles.map(o=>[o.to,o.from])),i=new Map;return o=>{let s=r.get(o.file);if(!s)return!1;let a=$(o.symbol);if(!a)return!1;let c=i.get(s);return c===void 0&&(c=$r(e,t,s),i.set(s,c)),c!==null&&PI(c,a)}}function PI(e,t){return new RegExp(`\\b${_I(t)}\\b`).test(e)}function _I(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function EI(e,t){if(!Hd(ro(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=Vr(e);for(let r of n.newFindings){let i=Sn("baseline",r);t.findings.push({id:i,check:"baseline",severity:"error",evidence:"baseline",confidence:1,message:`new finding vs committed baseline: ${r}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline."],remediation:"Fix the finding, or knowingly accept it via health --write-baseline.",suppressionHint:`scip-query: ignore baseline ${i} -- <reason>`})}}function Sn(e,...t){return`SQ${xI("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}var FI=.7,qd=.62,Wd=.45;function ba(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=Rd(e);if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let c=TI(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic}).map(l=>BI(l,s,n)).filter(l=>l!==null);return c.sort((l,u)=>(l.kind===u.kind?0:l.kind==="echo"?-1:1)||u.similarity-l.similarity||l.echoFile.localeCompare(u.echoFile)||l.echoSymbol.localeCompare(u.echoSymbol)||l.domain.localeCompare(u.domain)),{available:!0,windowCommits:n,findings:c.slice(0,r)}}function TI(e,t){let n=VI(t.limit);return[...AI(e,{scope:t.scope,minSimilarity:t.minSimilarity??FI,limit:n,scanLimit:t.scanLimit,semantic:t.semantic}),...$I(e,{scope:t.scope,minSimilarity:t.minSimilarity??qd,limit:n,scanLimit:t.scanLimit}),...MI(e,{scope:t.scope,minSimilarity:t.minSimilarity??Wd,limit:n,scanLimit:t.scanLimit}),...OI(e,{scope:t.scope,minSimilarity:t.minSimilarity??qd,limit:n,scanLimit:t.scanLimit}),...jI(e,{scope:t.scope,minSimilarity:t.minSimilarity??Wd,limit:n,scanLimit:t.scanLimit})]}function AI(e,t){return bt(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 $I(e,t){return sn(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,scanLimit:t.scanLimit}).filter(n=>n.fileA!==n.fileB).map(n=>({domain:"react-component",basis:"jsx-structure",symbolA:n.componentA,fileA:n.fileA,symbolB:n.componentB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:so(["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]),sharedCallees:[]}))}function MI(e,t){return cn(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,scanLimit:t.scanLimit}).filter(n=>n.fileA!==n.fileB).map(n=>({domain:"react-hook",basis:"react-behavior",symbolA:n.componentA,fileA:n.fileA,symbolB:n.componentB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:so(["hook",n.sharedHooks],["react-hook",n.sharedReactHooks],["effect",n.sharedEffects],["state",n.sharedState],["request",n.sharedRequests],["handler",n.sharedHandlers],["action",n.sharedHandlerVerbs]),sharedCallees:[]}))}function OI(e,t){return ln(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,scanLimit:t.scanLimit}).filter(n=>n.fileA!==n.fileB).map(n=>({domain:"vue-component",basis:"vue-template",symbolA:oo(n.fileA),fileA:n.fileA,symbolB:oo(n.fileB),fileB:n.fileB,similarity:n.similarity,sharedEvidence:so(["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]),sharedCallees:[]}))}function jI(e,t){return un(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,scanLimit:t.scanLimit}).filter(n=>n.fileA!==n.fileB).map(n=>({domain:"vue-composable",basis:"vue-behavior",symbolA:oo(n.fileA),fileA:n.fileA,symbolB:oo(n.fileB),fileB:n.fileB,similarity:n.similarity,sharedEvidence:so(["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]),sharedCallees:[]}))}function BI(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 VI(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function so(...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 oo(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var HI=ie("suppression-inventory",{clearGroups:["whole-project"]});function ao(e){return HI.get(e,()=>qI(e))}function qI(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 Le(e)){let o=A(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=Bo(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=WI(a);t[c]+=1}}return{total:r,byCategory:t,byFile:n}}function WI(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as UI}from"fs";import{join as JI}from"path";function Wr(e,t,n={}){let r=B(e,t);if(!r)return null;let i=new N(e),o=XI(zI(e,r.relativePath,r.startLine,r.endLine),GI(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:y(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o,cyclomaticEstimate:o+1,calleeCount:l.size,fanIn:KI(e,r.symbolId),fanOut:QI(c,r.relativePath)}}function GI(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function zI(e,t,n,r){try{return UI(JI(e.config.projectRoot,t),"utf-8").split(`
|
|
537
|
-
`).slice(n,r+1).join(`
|
|
538
|
-
`)
|
|
539
|
+
${e.pathExclusionsFor("ref_d")}`,t).map(i=>i.relative_path)}function jN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tr(e,t={}){let{scope:n,limit:i=30,scanLimit:r}=t,o=t.files===void 0?null:new Set(t.files),s=new E(e);return qe({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}).filter(a=>BN(a.relativePath)&&(o===null||o.has(a.relativePath))),scanLimit:r,evaluate:a=>{let c=re(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=St(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("_")||HN(l.get(m.name),c.paramsEndLine,c.endLine))break;u.unshift(m.name)}return u.length===0?null:{symbol:a.symbol,shortName:y(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:i})}function BN(e){let t=W(e);return t==="typescript"||t==="tsx"||t==="javascript"}function HN(e,t,n){return e?e.some(i=>i>t&&i<=n):!1}var Lo=["echo","incomplete-migration","co-change-partner","doc-reference","unused-params","new-dead","baseline"];function ic(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}=t,c=new Set(t.skip??[]),l=at(e,{base:n}),u=ii(e,{base:n,plan:l}),d=u.changedFiles,m=new Set(d),p=new Set(l.changedFileLines),h=LE(e.config.projectRoot,n,l),g={base:n,changedFiles:d,changedSymbols:u.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],rootCauseGroups:[],note:u.summary.note};if(d.length===0)return g;let b=(S,v)=>{if(c.has(S)){g.skipped.push({check:S,reason:"skipped via --skip"});return}v()};return b("echo",()=>KN(e,u.changedSymbols,m,h,o,a,g)),b("incomplete-migration",()=>iE(e,n,l,s,g)),b("co-change-partner",()=>rE(e,m,i,r,g)),b("doc-reference",()=>lE(e,m,p,l.changedRanges,g)),b("unused-params",()=>CE(e,d,g)),b("new-dead",()=>vE(e,u.changedSymbols,h,g)),b("baseline",()=>DE(e,g)),GN(g,e.config.suppressions??[]),g.rootCauseGroups=qN(g.findings),g}function qN(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=UN(r.severity,n.severity),r.actionTier=WN(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||Ro(i.severity)-Ro(n.severity)||n.groupKey.localeCompare(i.groupKey))}function UN(e,t){return Ro(t)>Ro(e)?t:e}function Ro(e){return e==="error"?2:e==="warning"?1:0}function WN(e,t){return e?t&&mp(t)>mp(e)?t:e:t}function mp(e){return e==="direct"?2:e==="signal"?1:0}function GN(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let i of e.findings){let r=t.find(o=>zN(o,i));r?e.suppressed.push({finding:i,suppression:r}):n.push(i)}e.findings=n}function zN(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 KN(e,t,n,i,r,o,s){s.checksRun.push("echo");for(let a of t.slice(0,r)){if(i(a))continue;let c=Vi(e,a.symbol,{minSimilarity:o,limit:5}),l=[];for(let p of c){let h=p.fileA===a.file?p.fileB:p.fileA,g=p.fileA===a.file?p.shortNameB:p.shortNameA,b=p.fileA===a.file?p.symbolB:p.symbolA;n.has(h)||l.push({otherFile:h,otherShort:g,otherSymbol:b,similarity:p.similarity,similarityBasis:p.similarityBasis??"callees",sharedEvidence:p.sharedCallees})}if(l.length===0)continue;let u=l[0],d=Ln("echo",a.symbol,a.file,...l.map(p=>`${p.otherSymbol}|${p.otherFile}`).sort()),m=JN(a,l);s.findings.push({id:d,groupKey:d,actionTier:m,check:"echo",severity:"warning",evidence:"heuristic",confidence:u.similarity,file:a.file,symbol:a.symbol,relatedFiles:[...new Set(l.map(p=>p.otherFile))].sort(),message:eE(a,l),why:tE(a,l),remediation:nE(m,a.shortName,u.otherShort),suppressionHint:`scip-query: ignore echo ${d} -- <reason>`})}t.length>r&&s.skipped.push({check:"echo",reason:`echo check capped at ${r} of ${t.length} changed symbols`})}function JN(e,t){return t.some(i=>QN(e.symbol,i))?"direct":"signal"}function QN(e,t){if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let n=F(e),i=F(t.otherSymbol);return!n||!i?!1:n===i?!0:ZN(t.sharedEvidence)?!1:XN(n,i)}function XN(e,t){let n=pp(e),i=pp(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 pp(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 YN=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function ZN(e){return e.length>=3&&e.every(t=>YN.has(t.toLowerCase()))}function eE(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 tE(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 nE(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 iE(e,t,n,i,r){let o=er(e,{base:t,maxHelpers:i,diffPlan:n});if(!o.available){r.skipped.push({check:"incomplete-migration",reason:"no git history"});return}r.checksRun.push("incomplete-migration"),o.note&&r.skipped.push({check:"incomplete-migration",reason:o.note});for(let s of o.findings){let a=s.leftovers.map(p=>`${p.shortName} (${p.file}, ${Math.round(p.containment*100)}% helper / ${Math.round(p.siteCoverage*100)}% site, ${p.migrationScope})`).join(", "),c=s.leftovers.map(p=>`${p.shortName}: ${p.migrationScope} (${p.migrationScopeReasons[0]})`).join("; "),l=[...s.migratedFiles,...s.leftovers.map(p=>p.file)],u=s.leftovers.length===0?void 0:Math.max(...s.leftovers.map(p=>Math.min(p.containment,p.siteCoverage))),d=s.leftovers.some(p=>p.migrationScope==="possible-subtype"),m=Ln("incomplete-migration",s.helperSymbol,s.helperFile,l.join("|"));r.findings.push({id:m,check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:u,file:s.helperFile,symbol:s.helperSymbol,relatedFiles:l,message:`new helper ${s.helperShortName} (${s.helperFile}) is wired into ${s.migratedFiles.length} file(s), but ${s.leftovers.length} similar un-migrated site(s) remain: ${a}`,why:[`${s.helperShortName} is new in this diff and already referenced by ${s.migratedFiles.join(", ")}.`,`Helper shape: ${s.helperShape}; ${s.specificHelperCalleeCount}/${s.helperCalleeCount} helper callees are specific enough to score.`,`Unchanged site(s) still contain the helper's callee pattern: ${a}.`,`Migration scope hints: ${c}.`],remediation:d?`Migrate same-scope sites to ${s.helperShortName}; review possible subtype/variant sites before applying the helper.`:`Migrate the remaining sites to ${s.helperShortName}, or confirm they are intentionally different.`,suppressionHint:`scip-query: ignore incomplete-migration ${m} -- <reason>`})}}function rE(e,t,n,i,r){let o=Am(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,h=p>0?c.together/p:0;if(h<i||ja(m)||ja(d)||!nc(`${e.config.projectRoot}/${m}`))continue;let g=`${d}|${m}`;if(s.has(g))continue;s.add(g);let b=Ln("co-change-partner",d,m,String(c.together)),S=Ba(d,m),v=Ha({fileA:d,fileB:m,together:c.together,confidence:h,commitScope:c.commitScope,recency:c.recency,subjectContext:c.subjectContext},S,(a??=Va(e))(d,m)),_=[d,m].sort().join("|");r.findings.push({id:b,check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${_}`,confidence:h,file:d,relatedFiles:[m],sourceAnalyzer:"co-change",rootCauseKey:_,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,...v?{declaredCouplingSuggestion:v}:{},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: ${oE(c)}.`,`Subject context: ${sE(c.subjectContext)}.`,...aE(c),`Partner class: ${S.partnerClass} (${S.reasons.join("; ")}).`],remediation:v?`Update ${m} alongside this change, declare the coupling "${v.name}", or confirm the coupling no longer holds.`:`Update ${m} alongside this change, or confirm the coupling no longer holds.`,suppressionHint:`scip-query: ignore co-change-partner ${b} -- <reason>`})}}function oE(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${cE(e.lastTogetherAt)}`}function sE(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 aE(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 cE(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function lE(e,t,n,i,r){r.checksRun.push("doc-reference");let o=gE(e,t,i);if(o.size!==0)for(let s of ep(e,o)){if(n.has(s.doc))continue;let a=s.citedClaims.length>0?s.citedClaims:dE(e,s.doc,s.cited),c=uE(a),l=Ln("doc-reference",s.doc,s.cited.join("|"));r.findings.push({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 ${pE(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:fE(c.citationKind,s.doc),suppressionHint:`scip-query: ignore doc-reference ${l} -- <reason>`})}}function uE(e){let t=e.join(`
|
|
540
|
+
`).toLowerCase(),n=[],i=tc(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=tc(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=tc(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 dE(e,t,n){let i;try{i=fp(`${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(bo(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 tc(e,t){return t.filter(n=>e.includes(n))}function pE(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 fE(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 gE(e,t,n){let i=hE(n),r=new Set;for(let o of t)bE(e,o,i.get(o)??[])&&r.add(o);return r}function hE(e){let t=new Map;for(let n of e){let i=t.get(n.file)??[];i.push(n),t.set(n.file,i)}return t}function bE(e,t,n){if(n.length===0)return!1;if(!yE.test(t))return!0;let i=`${e.config.projectRoot}/${t}`;if(!nc(i))return!0;let r=fp(i,"utf-8").split(/\r?\n/),o=SE(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 yE=/\.(?:[cm]?[jt]sx?)$/i;function SE(e){let t=new Set,n=!1;for(let i=0;i<e.length;i+=1){let r=e[i].trim();!n&&xE(r)&&(n=!0),n&&(t.add(i),r.endsWith(";")&&(n=!1))}return t}function xE(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}function CE(e,t,n){n.checksRun.push("unused-params");for(let i of tr(e,{files:t,limit:50})){let r=Ln("unused-params",i.symbol,i.file,i.unusedTrailing.join("|"));n.findings.push({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.",suppressionHint:`scip-query: ignore unused-params ${r} -- <reason>`})}}function vE(e,t,n,i){i.checksRun.push("new-dead");let r=new E(e);for(let o of t){if(n(o)||o.fanIn>0||r.fileKind(o.file)==="test"||Re(e,o.file)||ne(e,o.symbol,o.file)||RE(o.symbol))continue;let s=Ln("new-dead",o.symbol,o.file);i.findings.push({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.",suppressionHint:`scip-query: ignore new-dead ${s} -- <reason>`})}}function RE(e){if(Y(e)!=="type")return!1;let t=F(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function LE(e,t,n){let i=new Map(n.renamedFiles.map(o=>[o.to,o.from])),r=new Map;return o=>{let s=i.get(o.file)??o.file,a=F(o.symbol);if(!a)return!1;let c=r.get(s);return c===void 0&&(c=Ji(e,t,s),r.set(s,c)),c!==null&&wE(c,a)}}function wE(e,t){return new RegExp(`\\b${kE(t)}\\b`).test(e)}function kE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function DE(e,t){if(!nc(Co(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=Zi(e);for(let i of n.newFindings){let r=IE(i),o=Ln("baseline",i);t.findings.push({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,suppressionHint:`scip-query: ignore baseline ${o} -- <reason>`})}}function IE(e){let[t,n]=vo(e,":"),i=t||"unknown",r=(o={})=>{let s=o.actionTier??NE(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??EE(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]=vo(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]=vo(n,":"),[a,c]=vo(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 NE(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 EE(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 vo(e,t){let n=e.indexOf(t);return n<0?[e,""]:[e.slice(0,n),e.slice(n+t.length)]}function Ln(e,...t){return`SQ${VN("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}var PE=.7,gp=.62,hp=.45;function rc(e,t={}){let{windowCommits:n=100,limit:i=30,scope:r,scanLimit:o}=t,s=Fm(e);if(!s)return{available:!1,windowCommits:n,findings:[]};if(i<=0)return{available:!0,windowCommits:n,findings:[]};let c=_E(e,{limit:i,minSimilarity:t.minSimilarity,scanLimit:o,scope:r,semantic:t.semantic}).map(u=>OE(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,i).map(jE);return{available:!0,windowCommits:n,findings:l,rootCauseGroups:BE(l)}}function _E(e,t){let n=VE(t.limit);return[...TE(e,{scope:t.scope,minSimilarity:t.minSimilarity??PE,limit:n,scanLimit:t.scanLimit,semantic:t.semantic}),...FE(e,{scope:t.scope,minSimilarity:t.minSimilarity??gp,limit:n,scanLimit:t.scanLimit}),...$E(e,{scope:t.scope,minSimilarity:t.minSimilarity??hp,limit:n,scanLimit:t.scanLimit}),...AE(e,{scope:t.scope,minSimilarity:t.minSimilarity??gp,limit:n,scanLimit:t.scanLimit}),...ME(e,{scope:t.scope,minSimilarity:t.minSimilarity??hp,limit:n,scanLimit:t.scanLimit})]}function TE(e,t){return Ct(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 FE(e,t){return un(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,scanLimit:t.scanLimit}).filter(n=>n.fileA!==n.fileB).map(n=>({domain:"react-component",basis:"jsx-structure",symbolA:n.componentA,fileA:n.fileA,symbolB:n.componentB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:ko(["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]),sharedCallees:[]}))}function $E(e,t){return mn(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,scanLimit:t.scanLimit}).filter(n=>n.fileA!==n.fileB).map(n=>({domain:"react-hook",basis:"react-behavior",symbolA:n.componentA,fileA:n.fileA,symbolB:n.componentB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:ko(["hook",n.sharedHooks],["react-hook",n.sharedReactHooks],["effect",n.sharedEffects],["state",n.sharedState],["request",n.sharedRequests],["handler",n.sharedHandlers],["action",n.sharedHandlerVerbs]),sharedCallees:[]}))}function AE(e,t){return pn(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,scanLimit:t.scanLimit}).filter(n=>n.fileA!==n.fileB).map(n=>({domain:"vue-component",basis:"vue-template",symbolA:wo(n.fileA),fileA:n.fileA,symbolB:wo(n.fileB),fileB:n.fileB,similarity:n.similarity,sharedEvidence:ko(["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]),sharedCallees:[]}))}function ME(e,t){return gn(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,scanLimit:t.scanLimit}).filter(n=>n.fileA!==n.fileB).map(n=>({domain:"vue-composable",basis:"vue-behavior",symbolA:wo(n.fileA),fileA:n.fileA,symbolB:wo(n.fileB),fileB:n.fileB,similarity:n.similarity,sharedEvidence:ko(["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]),sharedCallees:[]}))}function OE(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 jE(e){let t=bp(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function bp(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 BE(e){let t=new Map;for(let[n,i]of e.entries()){let r=i.rootCauseKey??bp(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:HE(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 HE(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 VE(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function ko(...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 wo(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var qE=X("suppression-inventory",{clearGroups:["whole-project"]});function Do(e){return qE.get(e,()=>UE(e))}function UE(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 we(e)){let o=A(e,r);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=gi(s);if(a===null)continue;i+=1,n.set(r,(n.get(r)??0)+1);let c=WE(a);t[c]+=1}}return{total:i,byCategory:t,byFile:n}}function WE(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as GE}from"fs";import{join as zE}from"path";function nr(e,t,n={}){let i=j(e,t);if(!i)return null;let r=new E(e),o=YE(JE(e,i.relativePath,i.startLine,i.endLine),KE(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:y(i.symbol),relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,loc:s,branches:o,cyclomaticEstimate:o+1,calleeCount:l.size,fanIn:QE(e,i.symbolId),fanOut:XE(c,i.relativePath)}}function KE(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function JE(e,t,n,i){try{return GE(zE(e.config.projectRoot,t),"utf-8").split(`
|
|
541
|
+
`).slice(n,i+1).join(`
|
|
542
|
+
`)}catch{return""}}function QE(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
|
|
539
543
|
FROM mentions m
|
|
540
544
|
JOIN chunks c ON m.chunk_id = c.id
|
|
541
|
-
WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function QI(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function XI(e,t){let n=Kt(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 Ur(e,t,n={}){let r=B(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=$t(e,r,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?y(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=YI(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:y(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:y(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)":y(c.symbol),file:c.file}))}}function YI(e,t,n,r){let i=Gn(_e(e,t,{limit:30,semantic:r.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=Gn(je(e,t,{limit:30,semantic:r.semantic})),s=o.length>0?o:Gn(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function Qn(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=B(e,t);return o?r==="backward"?ZI(e,o,i,{semantic:n.semantic!==!1}):eD(e,o,{semantic:n.semantic!==!1}):null}function ZI(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=_e(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:y(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=$n(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:y(t.symbol),direction:"backward",connectedSymbols:i}}function eD(e,t,n){let r=new Set,i=[],o=new N(e);for(let s of $t(e,t,{semantic:n.semantic})){if(i.length>=30)break;let a=s.enclosingSymbol??Ae(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=$n(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:y(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:y(t.symbol),direction:"forward",connectedSymbols:i}}function ya(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=!nD(t),a=s?vr(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?wr(e,t,{semantic:o}):null,l=s?Wr(e,t,{semantic:o}):null,u=s?Ur(e,t,{semantic:o}):null,d=s?Qn(e,t,{direction:"backward",maxDepth:i,semantic:o}):null,m=s?Qn(e,t,{direction:"forward",maxDepth:i,semantic:o}):null,f=s?Tr(e,t,{maxDepth:r,scope:n.scope}):[],g=Ar(e,t,{semantic:o}),h=Rr(e,t),b=Lr(e,t),L=Ir(e,t),F=Dr(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:g!==null||h.length>0||b.length>0,module:L.files.length>0||L.symbols.length>0||F.length>0},E=[];!k.symbol&&!k.file&&!k.module&&E.push("No symbol, file, or module matched target.");let C=g?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:k,history:tD(e,C),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:d,forwardSlice:m,affected:f,changeSurface:g,deps:h,rdeps:b,system:L,surface:F,warnings:E}}function tD(e,t){let n={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return n;let r=Qi(e);if(!r)return n;let i=pn(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})),suppressionsInFile:ao(e).byFile.get(t)??0}}function nD(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}function Jr(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new N(e);return Ve({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)=>rD(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function rD(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:y(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 Xn(e){return e.scoreCount??e.count}function Kd(e){let t=aD(e),{breakdown:n,pressure:r}=cD(e),i=zd(n,"risk"),o=zd(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:Xn(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Xn(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null},axes:iD(e),validation:sD(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function iD(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:oD(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 oD(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:ot(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function sD(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?ot(i/r.size):0,c=s>0?ot(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 h of m)f+=t[h]?.fixChanges??0;let g=ot(f/m.size);l[u]={flaggedFiles:m.size,fixDensity:g,lift:c>0?ot(g/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?ot(a/c):null,byCategory:l}}function ot(e){return Math.round(e*100)/100}function Qd(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Ud(e){let t=Xn(e);return Math.abs(t-e.count)<.01?"":` (${Qd(t)} score-weighted after existing shared infrastructure discount)`}function Jd(e,t){let n=Xn(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${Qd(n)} score-weighted)`}function aD(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${Ud(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${Ud(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 extract method opportunities`,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 that could be inlined`,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 premature abstraction`,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(", "),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`+(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 Gd={"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 zd(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 cD(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(C,w,M)=>{w>0&&r.push({axis:C,points:w,detail:M,kind:Gd[C]??"hygiene"})},s=(C,w,M,j,ye,Fe,Dt)=>{let lt=Math.max(j,1);if(M<=lt)return;let Ao=M/lt,$o=Math.min(ye,Math.ceil(Math.log2(Ao)*Fe));if($o<=0)return;let Kf=Gd[C]??"hygiene";i.push({axis:C,category:w,kind:Kf,count:M,threshold:ot(lt),ratio:ot(Ao),extraPenalty:$o}),o(C,$o,`${M} ${Dt} exceed pressure threshold ${ot(lt)} (${ot(Ao)}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=Xn(e.reactHookCandidates),m=d/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(m)),Jd(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 g=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(g)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let h=Xn(e.vueComposableCandidates),b=h/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(b)),Jd(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let L=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(L/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let F=e.extractCount/n*1e3;o("extract",Math.min(5,Math.round(F/2)),`${e.extractCount} extraction candidate(s)`),o("wrappers",Math.min(3,e.wrappers.count),`${e.wrappers.count} wrapper candidate(s)`),o("passthroughs",Math.min(3,e.passthroughs.count),`${e.passthroughs.count} passthrough candidate(s)`);let k=e.stale.count/Math.max(n*.1,1);o("stale-abstractions",Math.min(8,Math.round(k*10)),`${e.stale.count} stale abstraction(s)`);let E=e.drift.count/t;return o("drift",Math.min(5,Math.round(E*50)),`${e.drift.count} drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence&&o("hidden-coupling",Math.min(5,e.gitEvidence.hiddenCoupling.pairCount),`${e.gitEvidence.hiddenCoupling.pairCount} co-changing pair(s) without a structural link`),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&&s("hidden-coupling-pressure","Hidden coupling",e.gitEvidence.hiddenCoupling.pairCount,50,10,4,"co-changing pair(s)"),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",h,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",e.wrappers.count,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",e.passthroughs.count,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Stale abstractions",e.stale.count,Math.max(50,n*.02),4,2,"stale abstraction(s)"),s("drift-pressure","Structural drift",e.drift.count,Math.max(10,t*.1),4,2,"drift finding(s)"),{breakdown:r,pressure:i}}import{getHeapStatistics as lD}from"v8";var uD=64*1024*1024;function Sa(){let e=globalThis.gc;if(!e)return;let t=lD();t.heap_size_limit-t.used_heap_size<uD||e()}var dD=50,mD=75e3,pD=5e3,Xd=2500,Yd=50,fD=10,Gr=["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"],gD={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:yD(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:SD(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:xD(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:CD(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:RD(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:LD(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:ID(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:DD(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:kD(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:wD(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:vD(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:ND(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:PD(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:_D(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:TD(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:AD(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:ED(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:FD(e,n)})};function xa(e,t,n={}){return hD(e,n.full===!0,(r,i)=>gD[t](e,n.scope,i,r))}function hD(e,t,n){let r=Te(e),i=$D(r,t);try{return n(r,i)}finally{ws(e,{semanticProvider:!0}),Sa()}}function Ca(e){return Kd(bD(e))}function bD(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:Zd(e,"git-evidence")?.gitEvidence??null,suppressions:Zd(e,"suppressions")?.suppressions??null}}function Zd(e,t){return e.find(n=>n.phase===t)}function de(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function yD(e,t,n){return me(e,n,"dead",()=>{let r=ht(e,{scope:t,...re.dead,scanLimit:n.candidateScanLimit});return co(jD(e,r.symbols))})}function SD(e,t,n){return me(e,n,"isolated",()=>{let r=on(e,{scope:t,...re.isolated,scanLimit:n.candidateScanLimit});return co(BD(e,r))})}function xD(e,t,n){return me(e,n,"cycles",()=>rn(e,{scope:t}).filter(i=>i.kind==="real").length)}function CD(e,t,n){return me(e,n,"similar",()=>bt(e,{scope:t,...re.similar,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function vD(e,t,n){return me(e,n,"extract-candidates",()=>dn(e,{scope:t,...re.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function RD(e,t,n){return me(e,n,"react-component-duplicates",()=>{let r=sn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return va(r)})}function LD(e,t,n){return me(e,n,"react-hook-candidates",()=>{let r=cn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return tm(r,HD)})}function ID(e,t,n){return me(e,n,"react-large-component-pressure",()=>{let r=Er(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return VD(r)})}function DD(e,t,n){return me(e,n,"vue-component-duplicates",()=>{let r=ln(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return va(r)})}function kD(e,t,n){return me(e,n,"vue-composable-candidates",()=>{let r=un(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return tm(r,qD)})}function wD(e,t,n){return me(e,n,"vue-large-view-pressure",()=>{let r=Fr(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return co(r)})}function ND(e,t,n){return em(e,n,"wrapper-candidates",()=>yn(e,{scope:t,...re.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}))}function PD(e,t,n){return em(e,n,"passthrough-candidates",()=>hn(e,{scope:t,...re.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}))}function _D(e,t,n){return me(e,n,"stale-abstractions",()=>{let r=bn(e,{scope:t,...re.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 ED(e,t){return me(e,t,"git-evidence",()=>{let n=Qi(e);if(!n)return null;let r=pn(e,void 0,{limit:t.candidateResultLimit}),i={};for(let[o,s]of n)i[o]={changes:s.changes,fixChanges:s.fixChanges};return{amplification:vd(e),hiddenCoupling:{pairCount:r.findings.length,top:r.findings.slice(0,5).map(o=>({fileA:o.fileA,fileB:o.fileB,together:o.together,confidence:o.confidence}))},fileStats:i}})}function FD(e,t){return me(e,t,"suppressions",()=>{let n=ao(e);return{total:n.total,byCategory:{...n.byCategory}}})}function TD(e,t,n){return me(e,n,"drift",()=>{let r=gn(e,{scope:t,...re.drift});return{count:r.unusedImports+r.layerViolations,unusedImports:r.unusedImports,layerViolations:r.layerViolations}})}function AD(e,t,n){return me(e,n,"complexity-hotspots",()=>{let r=Jr(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>dD).length}})}function $D(e,t){let n=e.symbols>=mD||e.documents>=pD,r=t?Number.POSITIVE_INFINITY:Yd,i=t?Number.POSITIVE_INFINITY:fD;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 was supplied."]:[]}:{candidateScanLimit:Xd,candidateResultLimit:r,complexityResultLimit:i,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${Xd} symbols and reported their top ${Yd} findings. Run "scip-query health --full" for unbounded candidate counts.`]}}function MD(e,t){t.releaseCachesBetweenPhases&&(ws(e),Sa())}function me(e,t,n,r){OD(n);try{return r()}finally{MD(e,t)}}function em(e,t,n,r){return me(e,t,n,()=>co(r()))}function OD(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function jD(e,t){return t.filter(n=>!xe(e,n.relativePath)&&!le(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function BD(e,t){return t.filter(n=>!xe(e,n.relativePath)&&!le(e,n.symbol,n.relativePath))}function co(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 VD(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 va(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 tm(e,t){return{...va(e),scoreCount:WD(e.reduce((r,i)=>r+t(i),0))}}function HD(e){let t=e.sharedHooks.length>0,n=nm({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:rm(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function qD(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=nm({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:rm(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function nm(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!om.has(im(t))).length+Math.min(e.functions.length,3)}function rm(e,t,n){let r=[...e,...t,...n].map(im);return r.length>0&&r.every(i=>om.has(i))}function im(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function WD(e){return Math.round(e*100)/100}var om=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 Ra(e,t,n,r={}){let i=B(e,t),o=B(e,n);if(!i||!o)return null;let s=new Set(_e(e,i,{semantic:r.semantic}).map(b=>b.symbol)),a=new Set(_e(e,o,{semantic:r.semantic}).map(b=>b.symbol)),c=[];for(let b of s)a.has(b)&&c.push(b);let l=[];for(let b of s)a.has(b)||l.push(b);let u=[];for(let b of a)s.has(b)||u.push(b);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 g=i.endLine-i.startLine+1,h=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:y(i.symbol),file:i.relativePath,loc:g},symbolB:{symbol:o.symbol,shortName:y(o.symbol),file:o.relativePath,loc:h},similarity:m,sharedCallees:c.map(y),uniqueToA:l.map(y),uniqueToB:u.map(y),consolidationStrategy:f}}import{readFileSync as sm}from"fs";import{extname as UD,join as am}from"path";function La(e,t,n={}){let{context:r=0}=n,i=JD(t);if(i)return zD(e,i.filePath,i.startLine,i.endLine,r);let o=B(e,t);return o?GD(e,o,r):null}function JD(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 GD(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=am(e.config.projectRoot,t.relativePath),o;try{o=sm(i,"utf-8")}catch{return null}let s=o.split(`
|
|
545
|
+
WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function XE(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function YE(e,t){let n=Zt(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 ir(e,t,n={}){let i=j(e,t);if(!i)return null;let r=[{file:i.relativePath,line:i.startLine}],o=jt(e,i,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?y(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=ZE(e,i,o,{semantic:n.semantic!==!1});return{symbol:i.symbol,shortName:y(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:y(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)":y(c.symbol),file:c.file}))}}function ZE(e,t,n,i){let r=ei(Fe(e,t,{limit:30,semantic:i.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=ei(He(e,t,{limit:30,semantic:i.semantic})),s=o.length>0?o:ei(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:r,consumers:s}}function oi(e,t,n={}){let{direction:i="backward",maxDepth:r=3}=n,o=j(e,t);return o?i==="backward"?eP(e,o,r,{semantic:n.semantic!==!1}):tP(e,o,{semantic:n.semantic!==!1}):null}function eP(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=Fe(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:y(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=Hn(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:y(t.symbol),direction:"backward",connectedSymbols:r}}function tP(e,t,n){let i=new Set,r=[],o=new E(e);for(let s of jt(e,t,{semantic:n.semantic})){if(r.length>=30)break;let a=s.enclosingSymbol??Me(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=Hn(e,a);!c||e.isIgnored(c.relativePath)||i.has(c.symbol)||(i.add(c.symbol),r.push({symbol:c.symbol,shortName:y(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:y(t.symbol),direction:"forward",connectedSymbols:r}}function oc(e,t,n={}){let i=n.impactDepth??3,r=n.sliceDepth??3,o=n.semantic,s=!iP(t),a=s?Fi(e,t,{semantic:o}):{definitions:[],referencedBy:[]},c=s?Bi(e,t,{semantic:o}):null,l=s?nr(e,t,{semantic:o}):null,u=s?ir(e,t,{semantic:o}):null,d=s?oi(e,t,{direction:"backward",maxDepth:r,semantic:o}):null,m=s?oi(e,t,{direction:"forward",maxDepth:r,semantic:o}):null,p=s?zi(e,t,{maxDepth:i,scope:n.scope}):[],h=Ki(e,t,{semantic:o}),g=$i(e,t),b=Ai(e,t),S=Mi(e,t),v=Oi(e,t),_={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||d!==null||m!==null||p.length>0,file:h!==null||g.length>0||b.length>0,module:S.files.length>0||S.symbols.length>0||v.length>0},w=[];!_.symbol&&!_.file&&!_.module&&w.push("No symbol, file, or module matched target.");let C=h?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:_,history:nP(e,C),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:d,forwardSlice:m,affected:p,changeSurface:h,deps:g,rdeps:b,system:S,surface:v,warnings:w}}function nP(e,t){let n={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return n;let i=mo(e);if(!i)return n;let r=yn(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:Do(e).byFile.get(t)??0}}function iP(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}function rr(e,t){let{scope:n,minLoc:i=10,limit:r=30,scanLimit:o}=t??{},s=new E(e);return qe({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)=>rP(a,c,i),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:r})}function rP(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=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:y(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:i,fanIn:r,fanOut:a,calleeCount:c,score:Math.round(i/50*(r/5)*Math.max(a/5,1)*100)/100}}function Lt(e){return e.scoreCount??e.count}function xp(e){let t=cP(e),{breakdown:n,pressure:i}=lP(e),r=Sp(n,"risk"),o=Sp(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:Lt(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Lt(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:Lt(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:oP(e),validation:aP(e),suppressions:e.suppressions,actions:t,pressure:i,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function oP(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:sP(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 sP(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:ct(n.score*Math.log2(1+i))}}).sort((n,i)=>i.weighted-n.weighted):null}function aP(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?ct(r/i.size):0,c=s>0?ct(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 h=ct(p/m.size);l[u]={flaggedFiles:m.size,fixDensity:h,lift:c>0?ct(h/c):null}}return{flaggedFiles:i.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:i.size>0&&c>0?ct(a/c):null,byCategory:l}}function ct(e){return Math.round(e*100)/100}function Cp(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Io(e,t="existing shared infrastructure discount"){let n=Lt(e);return Math.abs(n-e.count)<.01?"":` (${Cp(n)} score-weighted after ${t})`}function or(e,t){let n=Lt(e),i=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?i:`${i} (${Cp(n)} score-weighted)`}function cP(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${Io(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${Io(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${Io(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`+Io({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 yp={"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 Sp(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 lP(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),i=[],r=[],o=(C,N,H)=>{N>0&&i.push({axis:C,points:N,detail:H,kind:yp[C]??"hygiene"})},s=(C,N,H,B,he,ce,Ee)=>{let ft=Math.max(B,1);if(H<=ft)return;let rs=H/ft,os=Math.min(he,Math.ceil(Math.log2(rs)*ce));if(os<=0)return;let Wh=yp[C]??"hygiene";r.push({axis:C,category:N,kind:Wh,count:H,threshold:ct(ft),ratio:ct(rs),extraPenalty:os}),o(C,os,`${H} ${Ee} exceed pressure threshold ${ct(ft)} (${ct(rs)}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=Lt(e.reactHookCandidates),m=d/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(m)),or(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 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=Lt(e.vueComposableCandidates),b=g/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(b)),or(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 v=Lt(e.wrappers);o("wrappers",Math.min(3,v),or(e.wrappers,"wrapper candidate(s)"));let _=Lt(e.passthroughs);o("passthroughs",Math.min(3,_),or(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 w=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(w*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 C=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(C/10)),or({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:C},"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 C=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",C,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",v,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",_,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 uP}from"v8";var dP=64*1024*1024;function sc(){let e=globalThis.gc;if(!e)return;let t=uP();t.heap_size_limit-t.used_heap_size<dP||e()}var mP=50,pP=75e3,fP=5e3,vp=2500,Rp=50,gP=10,sr=["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"],hP={overview:(e,t,n,i)=>({phase:"overview",statsResult:i,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:SP(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:xP(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:CP(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:vP(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:LP(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:wP(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:kP(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:DP(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:IP(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:NP(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:RP(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:EP(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:PP(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:_P(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:$P(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:AP(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:TP(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:FP(e,n)})};function ac(e,t,n={}){return bP(e,n.full!==!1,(i,r)=>hP[t](e,n.scope,r,i))}function bP(e,t,n){let i=Ae(e),r=MP(i,t);try{return n(i,r)}finally{Ks(e,{semanticProvider:!0}),sc()}}function cc(e){return xp(yP(e))}function yP(e){let t=pe(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:pe(e,"dead").dead,isolated:pe(e,"isolated").isolated,realCycleCount:pe(e,"cycles").realCycleCount,similarCount:pe(e,"similar").similarCount,reactComponentDuplicates:pe(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:pe(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:pe(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:pe(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:pe(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:pe(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:pe(e,"extract-candidates").extractCount,wrappers:pe(e,"wrapper-candidates").wrappers,passthroughs:pe(e,"passthrough-candidates").passthroughs,stale:pe(e,"stale-abstractions").stale,drift:pe(e,"drift").drift,complexity:pe(e,"complexity-hotspots").complexity,gitEvidence:Lp(e,"git-evidence")?.gitEvidence??null,suppressions:Lp(e,"suppressions")?.suppressions??null}}function Lp(e,t){return e.find(n=>n.phase===t)}function pe(e,t){let n=e.find(i=>i.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function SP(e,t,n){return ae(e,n,"dead",()=>{let i=xt(e,{scope:t,...se.dead,scanLimit:n.candidateScanLimit});return No(BP(e,i.symbols))})}function xP(e,t,n){return ae(e,n,"isolated",()=>{let i=ln(e,{scope:t,...se.isolated,scanLimit:n.candidateScanLimit});return No(HP(e,i))})}function CP(e,t,n){return ae(e,n,"cycles",()=>cn(e,{scope:t}).filter(r=>r.kind==="real").length)}function vP(e,t,n){return ae(e,n,"similar",()=>Ct(e,{scope:t,...se.similar,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function RP(e,t,n){return ae(e,n,"extract-candidates",()=>hn(e,{scope:t,...se.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}).length)}function LP(e,t,n){return ae(e,n,"react-component-duplicates",()=>{let i=un(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return lc(i)})}function wP(e,t,n){return ae(e,n,"react-hook-candidates",()=>{let i=mn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Dp(i,qP)})}function kP(e,t,n){return ae(e,n,"react-large-component-pressure",()=>{let i=Wi(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return VP(i)})}function DP(e,t,n){return ae(e,n,"vue-component-duplicates",()=>{let i=pn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return lc(i)})}function IP(e,t,n){return ae(e,n,"vue-composable-candidates",()=>{let i=gn(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Dp(i,UP)})}function NP(e,t,n){return ae(e,n,"vue-large-view-pressure",()=>{let i=Gi(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return No(i)})}function EP(e,t,n){return ae(e,n,"wrapper-candidates",()=>{let i=Rn(e,{scope:t,...se.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return kp(i,WP)})}function PP(e,t,n){return ae(e,n,"passthrough-candidates",()=>{let i=Cn(e,{scope:t,...se.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return kp(i,GP)})}function _P(e,t,n){return ae(e,n,"stale-abstractions",()=>{let i=vn(e,{scope:t,...se.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 TP(e,t){return ae(e,t,"git-evidence",()=>{let n=mo(e);if(!n)return null;let i=yn(e,void 0,{limit:t.candidateResultLimit}),r={};for(let[o,s]of n)r[o]={changes:s.changes,fixChanges:s.fixChanges};return{amplification:Tm(e),hiddenCoupling:{pairCount:i.findings.length,scoreCount:uc(i.findings.reduce((o,s)=>o+wp(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:wp(o),subjectContext:o.subjectContext}))},fileStats:r}})}function FP(e,t){return ae(e,t,"suppressions",()=>{let n=Do(e);return{total:n.total,byCategory:{...n.byCategory}}})}function $P(e,t,n){return ae(e,n,"drift",()=>{let i=xn(e,{scope:t,...se.drift}),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 AP(e,t,n){return ae(e,n,"complexity-hotspots",()=>{let i=rr(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>mP).length}})}function MP(e,t){let n=e.symbols>=pP||e.documents>=fP,i=t?Number.POSITIVE_INFINITY:Rp,r=t?Number.POSITIVE_INFINITY:gP;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:vp,candidateResultLimit:i,complexityResultLimit:r,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${vp} symbols and reported their top ${Rp} findings. Enable full mode for unbounded candidate counts.`]}}function OP(e,t){t.releaseCachesBetweenPhases&&(Ks(e),sc())}function ae(e,t,n,i){jP(n);try{return i()}finally{OP(e,t)}}function jP(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function BP(e,t){return t.filter(n=>!Re(e,n.relativePath)&&!ne(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function HP(e,t){return t.filter(n=>!Re(e,n.relativePath)&&!ne(e,n.symbol,n.relativePath))}function No(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 kp(e,t){return{...No(e),scoreCount:uc(e.reduce((i,r)=>i+t(r),0))}}function VP(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 lc(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 Dp(e,t){return{...lc(e),scoreCount:uc(e.reduce((i,r)=>i+t(r),0))}}function qP(e){let t=e.sharedHooks.length>0,n=Ip({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:Np(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function UP(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=Ip({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:Np(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function Ip(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!Pp.has(Ep(t))).length+Math.min(e.functions.length,3)}function Np(e,t,n){let i=[...e,...t,...n].map(Ep);return i.length>0&&i.every(r=>Pp.has(r))}function Ep(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function WP(e){return e.actionTier==="signal"?.25:1}function GP(e){return e.actionTier==="signal"?.25:1}function wp(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 uc(e){return Math.round(e*100)/100}var Pp=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 dc(e,t,n,i={}){let r=j(e,t),o=j(e,n);if(!r||!o)return null;let s=new Set(Fe(e,r,{semantic:i.semantic}).map(b=>b.symbol)),a=new Set(Fe(e,o,{semantic:i.semantic}).map(b=>b.symbol)),c=[];for(let b of s)a.has(b)&&c.push(b);let l=[];for(let b of s)a.has(b)||l.push(b);let u=[];for(let b of a)s.has(b)||u.push(b);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 h=r.endLine-r.startLine+1,g=o.endLine-o.startLine+1;return{symbolA:{symbol:r.symbol,shortName:y(r.symbol),file:r.relativePath,loc:h},symbolB:{symbol:o.symbol,shortName:y(o.symbol),file:o.relativePath,loc:g},similarity:m,sharedCallees:c.map(y),uniqueToA:l.map(y),uniqueToB:u.map(y),consolidationStrategy:p}}import{readFileSync as _p}from"fs";import{extname as zP,join as Tp}from"path";function mc(e,t,n={}){let{context:i=0}=n,r=KP(t);if(r)return QP(e,r.filePath,r.startLine,r.endLine,i);let o=j(e,t);return o?JP(e,o,i):null}function KP(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 JP(e,t,n){let i=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),r=Tp(e.config.projectRoot,t.relativePath),o;try{o=_p(r,"utf-8")}catch{return null}let s=o.split(`
|
|
542
546
|
`),a=Math.max(0,t.startLine-n),c=Math.min(s.length-1,t.endLine+n),l=s.slice(a,c+1).join(`
|
|
543
|
-
`);return{symbol:t.symbol,shortName:y(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:
|
|
544
|
-
`),u=Math.max(0,n-1-
|
|
545
|
-
`);return{symbol:`${s.relative_path}:${n}-${
|
|
547
|
+
`);return{symbol:t.symbol,shortName:y(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:i?.language??Fp(t.relativePath),source:l}}function QP(e,t,n,i,r){let o=ke(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=Tp(e.config.projectRoot,s.relative_path),c;try{c=_p(a,"utf-8")}catch{return null}let l=c.split(`
|
|
548
|
+
`),u=Math.max(0,n-1-r),d=Math.min(l.length-1,i-1+r),m=l.slice(u,d+1).join(`
|
|
549
|
+
`);return{symbol:`${s.relative_path}:${n}-${i}`,shortName:`${s.relative_path}:${n}-${i}`,relativePath:s.relative_path,startLine:u,endLine:d,language:s.language??Fp(s.relative_path),source:m}}function Fp(e){switch(zP(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 pc(e,t={}){let{scope:n,limit:i}=t,r=new E(e),o=r_([...XP(e,n),...e_(e,r,n)]);return o_(o),i?o.slice(0,i):o}function XP(e,t){let n=[];for(let i of YP(e,t)){if(e.isIgnored(i.barrel_path)||e.isIgnored(i.original_path)||_s(e,i.barrel_path)||A(e,i.barrel_path)&&Ur(e,i.barrel_path).length===0)continue;let r=ZP(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:y(i.symbol),originalFile:i.original_path,barrelConsumers:o,directConsumers:s,...Ap(e,i.barrel_path)})}return n}function YP(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
|
|
546
550
|
barrel_d.id AS barrel_doc_id,
|
|
547
551
|
barrel_d.relative_path AS barrel_path,
|
|
548
552
|
gs.id AS symbol_id,
|
|
@@ -572,7 +576,7 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
572
576
|
-- Only function-level symbols (ending with ().), not module-level
|
|
573
577
|
AND gs.symbol LIKE '%().'
|
|
574
578
|
${n}
|
|
575
|
-
ORDER BY barrel_d.relative_path, gs.symbol`)}function
|
|
579
|
+
ORDER BY barrel_d.relative_path, gs.symbol`)}function ZP(e,t){return e.get(`SELECT
|
|
576
580
|
SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
|
|
577
581
|
SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
|
|
578
582
|
FROM (
|
|
@@ -601,7 +605,7 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
601
605
|
AND consumer_d.id != ?
|
|
602
606
|
${e.pathExclusionsFor("consumer_d")}
|
|
603
607
|
GROUP BY consumer_d.id
|
|
604
|
-
)`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function
|
|
608
|
+
)`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function e_(e,t,n){let i=[];for(let r of t_(e,n))Mp(e,r,r)>0||i.push(...n_(e,t,r));return i}function t_(e,t){return M(e,{scope:t,includeIgnored:!1}).filter(n=>Ur(e,n).length>0||ki(e,n).length>0)}function n_(e,t,n){let i=Ur(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>$p(e,t,n,o.sourcePath)),r=ki(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>$p(e,t,n,o.sourcePath));return[...i,...r]}function $p(e,t,n,i){let r=i_(t,i);return r?[{barrelFile:n,symbol:r.symbol,shortName:y(r.symbol),originalFile:i,barrelConsumers:0,directConsumers:Mp(e,i,n),...Ap(e,n)}]:[]}function Ap(e,t){return Kn(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 Mp(e,t,n){let i=new Set;for(let r of M(e,{includeIgnored:!1}))if(r!==n)for(let o of de(e,r))o.sourcePath===t&&i.add(r);return i.size}function i_(e,t){let n=e.definitionsForFile(t);return n.find(i=>Y(i.symbol)==="method")??n[0]??null}function r_(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 o_(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function gc(e,t={}){let{samples:n=50,scope:i,maxDisagreements:r=5}=t,o=new E(e),s=s_(o.productionCallableDefinitions({scope:i,minLoc:2,requireFunctionLikeSymbol:!0}),n);if(s.length===0||!a_(e,s))return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let a={references:Op(),callees:Op()},c=[],l=0,u=eo(e,s);for(let d of s){let m=Eo(d,sn(e,d).map(b=>b.file)),p=Eo(d,(u.get(d.symbolId)??[]).map(b=>b.file));if(m.size===0&&p.size===0)continue;l+=1;let h=Eo(d,an(e,d).map(b=>b.file)),g=Eo(d,(o.calleeMap([d],{semantic:!1}).get(d.symbolId)??[]).map(b=>b.file));jp(a.references,d,"references",h,m,c),jp(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?fc(l/s.length):0,scores:["references","callees"].map(d=>l_(d,a[d])),topDisagreements:c.slice(0,r)}}function Op(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0}}function s_(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 a_(e,t){let n=t[0];if(!n)return!1;try{return on(e,n.relativePath).availability().available}catch{return!1}}function Eo(e,t){let n=new Set;for(let i of t)i!==e.relativePath&&n.add(i);return n}function jp(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:y(t.symbol),question:n,cheapOnly:s,oracleOnly:a})}var c_={references:!0,callees:!1};function l_(e,t){let n=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed;return{question:e,comparedSymbols:t.comparedSymbols,precision:c_[e]&&t.cheapTotal>0?fc(t.agreed/t.cheapTotal):null,recall:fc(n),unverified:i}}function fc(e){return Math.round(e*1e3)/1e3}function hc(e,t={}){let{scope:n,minLoc:i=1,limit:r,scanLimit:o}=t,s=t.semantic!==!1,a=d_(e,u_(e,{scope:n,minLoc:i,scanLimit:o}),{semantic:s}),c=p_(a);return r?c.slice(0,r):c}function u_(e,t){let n=tt(e,{scope:t.scope}).filter(i=>i.isFunctionLike&&!e.isIgnored(i.relativePath)).filter(i=>q(i)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((i,r)=>q(r)-q(i)||i.relativePath.localeCompare(r.relativePath)),Ve(n,t.scanLimit)}function d_(e,t,n){let i=new Map;for(let r of t){let o=f_(e,r,n);if(!o)continue;let s=i.get(o)??[];s.push(m_(r)),i.set(o,s)}return i}function m_(e){return{symbol:e.symbol,shortName:y(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:q(e)}}function p_(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 f_(e,t,n){if(n.semantic){let o=Cd(e,t);if(o)return o}let i=g_(t.documentation),r=i?y_(i):null;return r||S_(h_(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function g_(e){return Kt(Jt(e))}function h_(e,t,n,i,r){let o=A(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=C_(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,b_(u)))return u}if(u&&u.includes("("))return u}return null}function b_(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||Li(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function y_(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 S_(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${Bp(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=x_(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 x_(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 C_(e,t,n,i){let r=Bp(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 Bp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{existsSync as Kp}from"fs";import{join as j_}from"path";import v_ from"better-sqlite3";var R_=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".scipquery-cache","__pycache__",".venv","venv"],Po=class{db;config;pathFilter;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new v_(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
|
|
605
609
|
EXISTS (
|
|
606
610
|
SELECT 1
|
|
607
611
|
FROM defn_enclosing_ranges local_der
|
|
@@ -618,8 +622,8 @@ ${m}`,l+=1+m.length,u+=fr(m),r+=m.length+1}let d=oS(c);d&&n.push({...d,start:a,e
|
|
|
618
622
|
AND local_m.role = 1
|
|
619
623
|
${this.pathExclusionsFor("local_d").trimStart()}
|
|
620
624
|
)
|
|
621
|
-
)`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>
|
|
622
|
-
`)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.db.prepare(t).all(...n)}get(t,...n){return this.db.prepare(t).get(...n)}close(){this.db.close()}};import
|
|
625
|
+
)`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>R_.flatMap(i=>[`AND ${n}.relative_path NOT LIKE '${i}/%'`,`AND ${n}.relative_path NOT LIKE '%/${i}/%'`])).join(`
|
|
626
|
+
`)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.db.prepare(t).all(...n)}get(t,...n){return this.db.prepare(t).get(...n)}close(){this.db.close()}};import L_ from"ignore";import{readFileSync as w_,existsSync as bc}from"fs";import{dirname as yc,isAbsolute as Hp,join as Sc,relative as k_,resolve as D_}from"path";function si(e){let t=L_(),n=!1,i=I_(e);for(let r of i)try{let o=w_(r,"utf-8");t.add(o),n=!0}catch{}return n||t.add(N_),{isIgnored:r=>Vp(t,e,r),filter:r=>r.filter(o=>!Vp(t,e,o))}}function I_(e){let t=[],n=Sc(e,".gitignore");bc(n)&&t.push(n);let i=yc(e),r=0;for(;i!==yc(i)&&r<5;){let o=Sc(i,".gitignore");if(bc(o)&&t.push(o),bc(Sc(i,".git")))break;i=yc(i),r++}return t}var N_=`
|
|
623
627
|
# Dependencies
|
|
624
628
|
node_modules/
|
|
625
629
|
vendor/
|
|
@@ -676,29 +680,29 @@ Thumbs.db
|
|
|
676
680
|
|
|
677
681
|
# Type definitions (often noise in queries)
|
|
678
682
|
*.d.ts
|
|
679
|
-
`;function
|
|
680
|
-
`),n}function
|
|
681
|
-
`),{path:n,suppressionCount:
|
|
682
|
-
${n}`:""}`)}return JSON.parse(t.stdout)}function
|
|
683
|
-
`)}function
|
|
683
|
+
`;function Vp(e,t,n){let i=E_(t,n);if(!i)return!1;try{return e.ignores(i)}catch{return!1}}function E_(e,t){if(!t||t===".")return null;if(!Hp(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=Hp(t)?t:D_(e,t),i=k_(e,n).replaceAll("\\","/");return!i||i==="."||i.startsWith("..")?null:i}import{readFileSync as P_,writeFileSync as Up,existsSync as _o,mkdirSync as __}from"fs";import{join as ut,resolve as qp}from"path";import{createHash as T_}from"crypto";import{homedir as F_}from"os";var ar=".scipquery.json",$_={enabled:!1,debounceMs:3e4,cooldownMs:6e4,ignore:[]},A_=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"];function wt(e){let t=ut(e,ar);if(!_o(t))return{};try{let n=P_(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 ${ar} at ${t}: ${i}`,{cause:n}):new Error(`unable to read ${ar} at ${t}: ${i}`,{cause:n})}}function To(e,t={}){let n=[],i=new Set(A_);for(let[o,s]of(e.languages??[]).entries())i.has(s)||n.push({level:"error",path:`languages[${o}]`,message:`Unsupported language: ${s}`});if(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.locality!==void 0)if(!O_(e.locality))n.push({level:"error",path:"locality",message:"Must be an object."});else{let o=e.locality.architecturalBoundarySegments;if(o!==void 0)if(!Array.isArray(o))n.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});else for(let[s,a]of o.entries()){let c=`locality.architecturalBoundarySegments[${s}]`;typeof a!="string"||a.trim()===""?n.push({level:"error",path:c,message:"Boundary segment must be a non-empty string."}):(a.includes("/")||a.includes("\\"))&&n.push({level:"error",path:c,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[o,s]of(e.declaredCouplings??[]).entries()){let a=`declaredCouplings[${o}]`;if((!s.name||s.name.trim()==="")&&n.push({level:"error",path:`${a}.name`,message:"Declared coupling name is required."}),!Array.isArray(s.files)||s.files.length<2)n.push({level:"error",path:`${a}.files`,message:"Declared coupling needs at least two files."});else for(let[c,l]of s.files.entries())!l||l.trim()===""?n.push({level:"error",path:`${a}.files[${c}]`,message:"Declared coupling file path is required."}):t.projectRoot&&!_o(ut(t.projectRoot,l))&&n.push({level:"warning",path:`${a}.files[${c}]`,message:`Declared coupling file does not exist: ${l}`});s.reason!==void 0&&s.reason.trim()===""&&n.push({level:"error",path:`${a}.reason`,message:"Declared coupling reason cannot be blank."})}let r=t.now??new Date;for(let[o,s]of(e.suppressions??[]).entries()){let a=`suppressions[${o}]`;if((!s.reason||s.reason.trim()==="")&&n.push({level:"error",path:`${a}.reason`,message:"Suppression reason is required."}),!s.id&&!s.check&&n.push({level:"error",path:a,message:"Suppression must include id or check."}),s.file!==void 0&&(s.file.trim()===""?n.push({level:"error",path:`${a}.file`,message:"Suppression file path cannot be blank."}):t.projectRoot&&!_o(ut(t.projectRoot,s.file))&&n.push({level:"warning",path:`${a}.file`,message:`Suppression file does not exist: ${s.file}`})),s.expiresAt){let c=Date.parse(s.expiresAt);Number.isNaN(c)?n.push({level:"error",path:`${a}.expiresAt`,message:"Must be an ISO date string."}):c<=r.getTime()&&n.push({level:"warning",path:`${a}.expiresAt`,message:"Suppression has expired."})}}return n}function Wp(e){return{...$_,...e.watch}}function M_(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return xc(n);if(t?.dbPath)return xc(qp(e,t.dbPath));let r=process.env.XDG_CACHE_HOME||ut(F_(),".cache"),o=T_("sha256").update(qp(e)).digest("hex").slice(0,12),s=ut(r,"scip-query","projects",o);return xc(s)}function ai(e,t){let n=M_(e,t);return{cacheDir:n,dbPath:ut(n,"index.db"),indexPath:ut(n,"index.scip"),metaPath:ut(n,"meta.json")}}function Gp(e,t){let n=ut(e,ar);return _o(n)||Up(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4}},null,2)+`
|
|
684
|
+
`),n}function zp(e,t){let n=ut(e,ar),i=wt(e),r={...i,suppressions:[...i.suppressions??[],t]},o=To(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 Up(n,JSON.stringify(r,null,2)+`
|
|
685
|
+
`),{path:n,suppressionCount:r.suppressions?.length??0}}function xc(e){return __(e,{recursive:!0}),e}function O_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ye(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function Fo(e=ye()){let t=wt(e),n=ai(e,t),i=process.env.SCIP_QUERY_INDEX_DB??(Kp(n.dbPath)?n.dbPath:j_(e,"index.db"));return{projectRoot:e,config:t,paths:n,dbPath:i}}function Cc(e){return Fo(e).dbPath}function B_(){let{projectRoot:e,config:t,paths:n,dbPath:i}=Fo();Kp(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=si(e);return new Po(r,o)}function dt(e){let t=B_();try{return e(t)}finally{t.close()}}function vc(e,t){return t.concat([e])}function ci(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 Jp(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 H_(e)}}function H_(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}import{spawnSync as V_}from"child_process";function Rc(e){let t=V_(process.execPath,[...process.execArgv,e.cliPath,e.command,...e.args??[]],{cwd:process.cwd(),env:e.env??process.env,encoding:"utf8",maxBuffer:e.maxBuffer??10485760});if(t.status!==0){let n=t.stderr.trim();throw new Error(`${e.label} failed${n?`:
|
|
686
|
+
${n}`:""}`)}return JSON.parse(t.stdout)}function Qp(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function $e(e){return e+1}function Se(e,t){return`${$e(e)}-${$e(t)}`}function fe(e,t,n){return`${e}:${Se(t,n)}`}function $o(e,t=180){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var D={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 U_=q_(import.meta.url),{version:Ao}=K_(),Mo="__health-phase",Oo="__diff-impact-batch",W_=10,G_=75e3,z_=5e3,Xp=2500;function K_(){for(let e of["../package.json","../../package.json"])try{return U_(e)}catch{}return{version:"0.0.0"}}function li(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
|
|
687
|
+
`)}function wc(e){let t=Ae(e);return t.symbols>=G_||t.documents>=z_}function Zp(e,t,n,i={}){return wc(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 ${Xp} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:Xp,semantic:!1}):{semantic:!0}}function ef(e){let t=sr.map(n=>J_(n,e));return cc(t)}function J_(e,t){let n=process.argv[1]??Yp(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),Rc({cliPath:n,command:Mo,args:i,label:`Health phase "${e}"`})}function tf(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
|
|
684
688
|
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)
|
|
685
|
-
`),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${
|
|
686
|
-
`),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let
|
|
687
|
-
Prioritized Actions (highest impact + lowest effort first):`);for(let
|
|
688
|
-
Top Complexity Hotspots:`);for(let
|
|
689
|
-
Score Breakdown (100 minus the following):`);for(let
|
|
690
|
-
No issues found. Codebase is clean.`)}function
|
|
691
|
-
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
|
|
692
|
-
Axes:`),console.log(` Deletable: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let
|
|
693
|
-
Affected consumer files:`),
|
|
689
|
+
`),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${ci(e.overview.indexSizeBytes)}
|
|
690
|
+
`),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: ${Lc(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: ${Lc(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: ${Lc(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(`
|
|
691
|
+
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(`
|
|
692
|
+
Top Complexity Hotspots:`);for(let i of e.topComplexity)console.log(` ${i.score.toFixed(1).padStart(6)} ${i.symbol}`)}if(Y_(e),X_(e),e.scoreBreakdown.length>0){console.log(`
|
|
693
|
+
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(`
|
|
694
|
+
No issues found. Codebase is clean.`)}function Lc(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${Q_(t)} score-weighted)`}function Q_(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function X_(e){if(e.pressure.length!==0){console.log(`
|
|
695
|
+
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 Y_(e){let t=e.axes;if(console.log(`
|
|
696
|
+
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})`)}}function nf(e){return dt(t=>{let n=at(t,{base:e.base});if(n.note)return ii(t,{base:e.base});if(n.changedFiles.length===0)return ii(t,{base:e.base});let i=[];for(let r of Qp(n.changedFiles,W_))i.push(Z_(r,e));return fo(n.changedFiles,i)})}function Z_(e,t){let n=process.argv[1]??Yp(import.meta.url),i=[];return t.base&&i.push("--base",t.base),Rc({cliPath:n,command:Oo,args:i,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function rf(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:"),D.list(e.changedSymbols,t=>` ${t.file} ${t.shortName} (fan-in: ${t.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
|
|
697
|
+
Affected consumer files:`),D.list(e.affectedConsumers,t=>` ${t.file} (${t.consumedSymbols} symbol(s))`))}var jo=vc,x=(e=>parseInt(e,10)),Bo=(e=>{let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}),Xe=parseFloat,kc=parseInt;function f(e,t,n,...i){return i.length>0?{flags:e,description:t,parser:n,defaultValue:i[0]}:{flags:e,description:t,parser:n}}function Dc(){return f("--json","Output as JSON for programmatic consumption")}function T(e=[]){return e.some(t=>t.flags==="--json")?e:[...e,Dc()]}function L(e,t=[]){return{category:e,examples:t}}import{existsSync as Pc,mkdirSync as oT,symlinkSync as sT,readlinkSync as aT,unlinkSync as cT}from"fs";import{join as cr,dirname as cf,resolve as _c}from"path";import{homedir as Tc,platform as lT}from"os";import{fileURLToPath as uT}from"url";import{execFileSync as of}from"child_process";import{platform as Ic,arch as iT}from"os";import{execFileSync as eT}from"child_process";import{platform as tT}from"os";var nT=tT()==="win32";function Ue(e){let t=nT?"where":"which";try{return eT(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var sf="v0.7.0";function Nc(){return Ue("scip")}function rT(){let e=Ic(),t=iT(),n,i,r;switch(e){case"darwin":n="darwin",r="tar.gz";break;case"linux":n="linux",r="tar.gz";break;case"win32":n="windows",r="zip";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:`https://github.com/sourcegraph/scip/releases/download/${sf}/${o}`,filename:o}}function Ec(){let e=rT();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Ic()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
|
|
694
698
|
`),console.log("Or download manually:")):console.log("Download from:"),console.log(e?` ${e.url}
|
|
695
|
-
`:` https://github.com/sourcegraph/scip/releases/tag/${
|
|
696
|
-
`),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function
|
|
697
|
-
VALUES (?, ?, NULL, ?)`),c=
|
|
698
|
-
`).filter(
|
|
699
|
-
`)){if(!
|
|
700
|
-
`).filter(Boolean)}catch{return null}}function
|
|
701
|
-
`)[0]}`;return n(`Skipping ${e.language}: ${s}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:s}}}finally{
|
|
699
|
+
`:` https://github.com/sourcegraph/scip/releases/tag/${sf}
|
|
700
|
+
`),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function af(e){if(Ic()==="darwin"&&Ue("brew")){e("Installing scip CLI via Homebrew...");try{if(of("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),Ue("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`Homebrew install failed: ${n}`)}}if(Ue("go")){e("Installing scip CLI via go install...");try{if(of("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),Ue("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`go install failed: ${n}`)}}return e("Could not auto-install scip CLI."),e("Install manually from: https://github.com/sourcegraph/scip/releases"),!1}var dT=lT()==="win32",Fc=["scip-query","scip-query-setup","concrete-plan","scip-ai-cleanup","scip-explore","scip-debloat","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook"];function lf(e={}){let t=e.quiet?()=>{}:console.log,n=uT(import.meta.url),i=_c(cf(n),"..","skills"),r=[cr(Tc(),".claude","skills"),cr(Tc(),".codex","skills"),cr(Tc(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[]};for(let s of r){let a=cf(s);if(!Pc(a))continue;oT(s,{recursive:!0});let c=mT(s);for(let l of Fc){let u=cr(i,l),d=cr(s,l);if(!Pc(u)){o.skipped.push(`${c}/${l}`);continue}if(Pc(d)){try{let m=aT(d);if(_c(m)===_c(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}cT(d)}sT(u,d,dT?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}function mT(e){return e.includes(".codex")?"Codex":e.includes(".agents")?"Agents":"Claude"}import{existsSync as U$}from"fs";import{execFileSync as DF}from"child_process";import{closeSync as IF,copyFileSync as NF,existsSync as Go,mkdirSync as Xc,mkdtempSync as EF,openSync as PF,readFileSync as tg,renameSync as Yc,rmSync as Zc,writeFileSync as ng}from"fs";import{basename as Wo,dirname as Dt,extname as _F,join as mt}from"path";import pT from"better-sqlite3";import{execFileSync as fT}from"child_process";import{existsSync as gT,readdirSync as hT,readFileSync as bT}from"fs";import{extname as Ho,join as uf}from"path";function Vt(e){let t=new Set((e.extensions??ql).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!gT(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=si(e.projectRoot),i=yT(e.projectRoot,t).filter(o=>!n.isIgnored(o)),r=new pT(e.dbPath);try{let o=xT(r,i),s=r.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
|
|
701
|
+
VALUES (?, ?, NULL, ?)`),c=r.transaction(u=>{let d=0;for(let m of u){if(o.has(m))continue;let p=bT(uf(e.projectRoot,m),"utf-8"),h=s.run(CT(m),m,p);d+=Number(h.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 yT(e,t){let n=ST(e,t);if(n)return n;let i=[],r=o=>{let s=o?uf(e,o):e,a;try{a=hT(s,{withFileTypes:!0})}catch{return}for(let c of a){if(bs.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){r(l);continue}t.has(Ho(c.name).toLowerCase())&&i.push(l)}};return r(""),i.sort()}function ST(e,t){try{return fT("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
|
|
702
|
+
`).filter(i=>i&&t.has(Ho(i).toLowerCase())).sort()}catch{return null}}function xT(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 CT(e){return Ho(e).toLowerCase()===".vue"?"vue":Ho(e).replace(/^\./,"").toLowerCase()||"source"}import{execFileSync as vT}from"child_process";import{existsSync as RT,readdirSync as mf}from"fs";import{extname as pf,join as ff}from"path";var LT=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),wT=[{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 kt(e){let t=[],n=kT(e),i=ET(e);for(let r of wT){if(DT(e,r.files)){t.push(r.language);continue}if(IT(n,r.globs)){t.push(r.language);continue}_T(i,r.extensions)&&t.push(r.language)}return t.includes("typescript")&&df(t,"javascript"),t.includes("cpp")&&!i.has(".c")&&df(t,"c"),t}function kT(e){try{return mf(e)}catch{return[]}}function DT(e,t){return t?.length?t.some(n=>RT(ff(e,n))):!1}function IT(e,t){return t?.length?e.some(n=>t.some(i=>NT(n,i))):!1}function NT(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 ET(e){let t=PT(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=mf(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=ff(r,s.name);if(s.isDirectory()){LT.has(s.name)||i.push(a);continue}let c=pf(s.name).toLowerCase();c&&n.add(c)}}return n}function PT(e){try{let t=vT("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(`
|
|
703
|
+
`)){if(!i)continue;let r=pf(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 df(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as gf,readdirSync as TT}from"fs";import{join as $c}from"path";var FT={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n})=>{let i=["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:"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",hf(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",hf(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=$c(e,"vendor","bin","scip-php"),i=$c(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",gf(i)?i:gf(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function lr(e){return FT[e]}function hf(e,t){let n;try{n=TT(e)}catch{return null}for(let i of n)if(t.some(r=>i.endsWith(r)))return $c(e,i);return null}import{readFileSync as $T,writeFileSync as AT}from"fs";import{create as Ac}from"@bufbuild/protobuf";import{deserializeSCIP as MT,serializeSCIP as OT,DocumentSchema as jT,IndexSchema as BT,SymbolInformationSchema as HT}from"@c4312/scip";function VT(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=qT(e),n=UT(e.flatMap(r=>r.documents??[])),i=yf(e.flatMap(r=>r.externalSymbols??[]));return Ac(BT,{metadata:t,documents:n,externalSymbols:i})}function bf(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(r=>MT($T(r))),i=VT(n);return AT(t,Buffer.from(OT(i))),{documentCount:i.documents.length,externalSymbolCount:i.externalSymbols.length,inputCount:e.length}}function qT(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 UT(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,Ac(jT,{language:i.language||n.language,relativePath:i.relativePath||n.relativePath,occurrences:[...i.occurrences,...n.occurrences],symbols:yf([...i.symbols,...n.symbols]),text:GT(i.text,n.text),positionEncoding:i.positionEncoding||n.positionEncoding}))}return[...t.values()]}function yf(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,Ac(HT,{symbol:i.symbol,documentation:zT([...i.documentation,...n.documentation]),relationships:WT([...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 WT(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 GT(e,t){return e?t?e.length>=t.length?e:t:e:t}function zT(e){return[...new Set(e)]}import{execFileSync as KT}from"child_process";import{createHash as JT}from"crypto";import{readdirSync as QT,readFileSync as XT}from"fs";import{join as xf}from"path";function Sf(e){return(ZT(e)??e0(e)).filter(t=>t&&!Cf(t)).sort()}function wn(e,t={}){return(t.language?Sf(e).filter(i=>YT(i,t.language,t.markerFiles)):Sf(e)).map(i=>{let r=xf(e,i);try{let o=XT(r);return{path:i,size:o.byteLength,hash:JT("sha256").update(o).digest("hex")}}catch{return{path:i,size:-1,hash:"unreadable"}}})}function YT(e,t,n){let i=e.split("/").at(-1)??e;if(n?.includes(e)||n?.includes(i)||n0.has(i))return!0;let r=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return(i0[t]??[]).includes(r)}function ZT(e){try{return KT("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
|
|
704
|
+
`).filter(Boolean)}catch{return null}}function e0(e){let t=[],n=[""];for(;n.length>0;){let i=n.pop(),r=i?xf(e,i):e,o;try{o=QT(r,{withFileTypes:!0})}catch{continue}for(let s of o){let a=i?`${i}/${s.name}`:s.name;if(s.isDirectory()){Cf(a)||n.push(a);continue}t.push(a)}}return t}function Cf(e){return e.split("/").some(n=>t0.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var t0=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]),n0=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"]),i0={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 r0,writeFileSync as o0}from"fs";import{create as vf}from"@bufbuild/protobuf";import{deserializeSCIP as s0,DocumentSchema as a0,IndexSchema as c0,serializeSCIP as l0,SymbolRole as u0}from"@c4312/scip";function Rf(e){let t;try{t=s0(r0(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=d0(t);return n.removedDefinitionOccurrences>0&&o0(e,Buffer.from(l0(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function d0(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&u0.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){r.push(o);continue}i+=1,r.push(vf(a0,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:vf(c0,{metadata:e.metadata,documents:r,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:i}}import{execFile as m0}from"child_process";import{existsSync as Vo,renameSync as Oc,rmSync as jc}from"fs";import{cpus as p0}from"os";import{join as Lf}from"path";function f0(e,t,n){if(!e.defaultOutputPath)return;let i=Lf(t,e.defaultOutputPath);n!==i&&Vo(i)&&Oc(i,n)}function g0(e,t,n){if(!e.defaultOutputPath)return null;let i=Lf(t,e.defaultOutputPath);if(i===n)return null;let r=`${n}.default-output-backup`;return jc(r,{force:!0}),Vo(i)?(Oc(i,r),{defaultOutputPath:i,backupPath:r}):{defaultOutputPath:i,backupPath:null}}function h0(e){e&&(jc(e.defaultOutputPath,{force:!0}),e.backupPath&&Vo(e.backupPath)&&Oc(e.backupPath,e.defaultOutputPath))}function b0(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(2,Math.max(1,p0().length-1));return Math.max(1,Math.min(e,Math.floor(i)))}async function wf(e,t,n,i){let r=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=b0(o.length,i),c=await S0(o,a,l=>Mc(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.language===u.language);d&&(n(`Retrying ${d.language} indexer serially after parallel failure...`),l.set(d.language,await Mc(d,t,n)))}s.push(...c.map(u=>l.get(u.language)??u))}else s.push(...c);for(let l of r)s.push(await Mc(l,t,n));return s.sort((l,u)=>e.findIndex(d=>d.language===l.language)-e.findIndex(d=>d.language===u.language))}async function Mc(e,t,n){n(`Indexing ${e.language} with ${e.resolvedBinary}...`),jc(e.scipPath,{force:!0});let i=g0(e.config,t,e.scipPath);try{await y0(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),f0(e.config,t,e.scipPath)}catch(r){let o=r instanceof Error?r.message:String(r),s=`${e.resolvedBinary} indexer failed: ${o.split(`
|
|
705
|
+
`)[0]}`;return n(`Skipping ${e.language}: ${s}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:s}}}finally{h0(i)}if(!Vo(e.scipPath)){let r=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`;return n(`Skipping ${e.language}: ${r}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:r}}}return{language:e.language,scipPath:e.scipPath}}function y0(e,t,n){return new Promise((i,r)=>{m0(e,[...t],n,o=>{o?r(o):i()})})}async function S0(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 Hc}from"child_process";import{existsSync as Bc,readFileSync as x0}from"fs";import{createRequire as C0}from"module";import{platform as v0}from"os";import{dirname as kf,join as qo}from"path";var R0=C0(import.meta.url);function Vc(e){return[e.indexerBinary,...e.binaryAliases??[]]}function Uo(e){let t=Vc(e);return t.length===1?t[0]:t.join(" or ")}function ui(e){for(let t of Vc(e))if(Ue(t))return t;return w0(e)}function Df(e){return ui(e)!==null||L0(e)}function L0(e){return If(e)!==null}function w0(e){let t=If(e);if(!t)return null;let i=JSON.parse(x0(t,"utf8")).bin;if(!i)return null;if(typeof i=="string")return qo(kf(t),i);for(let r of Vc(e)){let o=i[r];if(o)return qo(kf(t),o)}return null}function If(e){if(!e.bundledNpmPackage)return null;try{return R0.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function qc(e,t){for(let n of e.projectLocalBinaries??[]){let i=qo(t,n);if(Bc(i))return i}return null}function k0(e,t){return qc(e,t)??ui(e)}function Nf(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Uc(n,t))return t;let i=_f(n,t);return i?{...t,DOTNET_ROOT:i}:t}function Ef(e,t){let n=Uo(e),i=t?k0(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=D0(i);return{language:e.language,binaryLabel:n,installed:!0,runnable:r.runnable,resolvedBinary:i,installUrl:e.installUrl,note:r.note}}function Pf(e,t){let n=e.installMethods,i=Uo(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(Ue(r.prerequisite)){t(`Installing ${i} via ${r.label}...`);try{Hc(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 D0(e){if(Uc(e,process.env))return{runnable:!0};let t=_f(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=Tf(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 _f(e,t){for(let n of Tf(t))if(Uc(e,{...t,DOTNET_ROOT:n}))return n;return null}function Tf(e){let t=[],n=e.DOTNET_ROOT;if(n&&Bc(n)&&t.push(n),v0()==="darwin"&&Ue("brew"))try{let i=Hc("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),r=qo(i,"libexec");Bc(r)&&!t.includes(r)&&t.push(r)}catch{}return t}function Uc(e,t){try{return Hc(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import aF from"better-sqlite3";import{existsSync as cF,readFileSync as lF,writeFileSync as uF}from"fs";import{dirname as dF,join as mF,resolve as pF}from"path";import{readFileSync as I0,rmSync as N0,statSync as E0,mkdtempSync as P0}from"fs";import{cpus as _0,tmpdir as T0}from"os";import{join as Wc}from"path";import{Worker as F0}from"worker_threads";function Ff(e){return e.length>=8&&Af(e.length)>1}function $f(e){let t=Af(e.vueFiles.length),n=A0(e.vueFiles),i=O0(n,t),r=new URL("./augment-vue-worker.js",import.meta.url),o=P0(Wc(T0(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=$0(),l=Date.now();try{for(let d=0;d<i.length;d++)new F0(r,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:i[d],resultPath:Wc(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(I0(Wc(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{N0(o,{recursive:!0,force:!0})}}function Af(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,_0().length-1));return Math.max(1,Math.min(e,n))}function $0(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function A0(e){let t=M0(),n=[];for(let i of e){let r=Mf(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 M0(){return Number.POSITIVE_INFINITY}function O0(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),i=e.map(r=>({task:r,weight:j0(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 j0(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Mf(e.fileName)-e.startOffset)}function Mf(e){try{return E0(e).size}catch{return 1}}import{createRequire as B0}from"module";import{existsSync as H0,readFileSync as zc}from"fs";import{dirname as Of,extname as V0,join as jf,relative as q0,resolve as U0}from"path";import{pathToFileURL as W0}from"url";function G0(e){e.transaction(()=>{e.prepare(`
|
|
702
706
|
DELETE FROM mentions
|
|
703
707
|
WHERE chunk_id IN (
|
|
704
708
|
SELECT c.id
|
|
@@ -713,12 +717,12 @@ Affected consumer files:`),I.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
|
|
|
713
717
|
FROM documents
|
|
714
718
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
715
719
|
)
|
|
716
|
-
`).run()})()}function
|
|
720
|
+
`).run()})()}function Bf(e,t){return e.prepare(`
|
|
717
721
|
SELECT relative_path AS relativePath
|
|
718
722
|
FROM documents
|
|
719
723
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
720
724
|
ORDER BY relative_path
|
|
721
|
-
`).all().map(
|
|
725
|
+
`).all().map(i=>U0(t,i.relativePath))}function Hf(e,t){let{vueCore:n,ts:i,volarTs:r}=z0(e),{parsed:o,vueOptions:s}=K0(n,i,t),a=Of(t),c=n.createVueLanguagePlugin(i,o.options,s,p=>p),l=J0(n,i,c),u=Q0(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 z0(e){let t=B0(W0(jf(e,"package.json")).href);return{vueCore:Gc(t,"@vue/language-core",e),ts:Gc(t,"typescript",e),volarTs:Gc(t,"@volar/typescript",e)}}function K0(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,Of(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function J0(e,t,n){let i={},r=e.createLanguage([n],new Map,o=>{if(!H0(o))return;let s=zc(o,"utf-8");i.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??nF(o))});return i.current=r,r}function Q0(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Gc(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 Vf(e,t,n){let i=X0(e);return r=>{let o=kn(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:Y0(c.starts,a.line,2)}}function X0(e){let t=e.prepare(`
|
|
722
726
|
SELECT
|
|
723
727
|
d.relative_path AS relativePath,
|
|
724
728
|
der.start_line AS startLine,
|
|
@@ -727,23 +731,23 @@ Affected consumer files:`),I.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
|
|
|
727
731
|
FROM defn_enclosing_ranges der
|
|
728
732
|
JOIN documents d ON d.id = der.document_id
|
|
729
733
|
ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
|
|
730
|
-
`).all(),n=new Map;for(let
|
|
734
|
+
`).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 Y0(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 qf(e,t,n){let i=oF(t),r=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
|
|
731
735
|
INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
|
|
732
736
|
VALUES (?, ?, ?, ?)
|
|
733
|
-
`),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let u=
|
|
737
|
+
`),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let u=kn(t,l),d=Yf(i.name,i.version,u);o.run(d,"default",7,`Vue component|${u}`);let m=sF(r,i,t,l);m&&(s++,a.set(l,m))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Uf(e,t,n,i,r){return e.transaction(()=>(G0(e),Z0(e,t,n,i),eF(e,r)))()}function Z0(e,t,n,i){let r=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
|
|
734
738
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
735
739
|
VALUES (?, ?, ?, ?, X'00')
|
|
736
740
|
`),s=e.prepare(`
|
|
737
741
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
738
742
|
VALUES (?, ?, 1)
|
|
739
|
-
`);for(let a of n){let c=
|
|
743
|
+
`);for(let a of n){let c=i.get(a);if(!c)continue;let l=kn(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 Wf(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(Kc(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(r)?n.get(e.fileName):null}return t(e)}function Gf(e){let t=new Set,n=[];for(let i of e){let r=zf(i);t.has(r)||(t.add(r),n.push(i))}return n}function zf(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function eF(e,t){let n=rF(e,[...new Set(t.map(c=>c.sourceFile))]),i=e.prepare(`
|
|
740
744
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
741
745
|
VALUES (?, ?, ?, ?, X'00')
|
|
742
|
-
`),
|
|
746
|
+
`),r=e.prepare(`
|
|
743
747
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
744
748
|
VALUES (?, ?, 0)
|
|
745
|
-
`),o=new Set,s=0,a=0;for(let c of t){let l=
|
|
746
|
-
`)}function
|
|
749
|
+
`),o=new Set,s=0,a=0;for(let c of t){let l=zf(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*Kf(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 Jf(e,t){for(let[n]of e.toGeneratedLocation(t,i=>!!i.navigation))return n;return null}function Kc(e,t){let n=e;for(let[i]of n.toSourceLocation(t,r=>!!r.navigation))return i;return null}function tF(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 Qf(e,t){return kn(e,t).startsWith("node_modules/")}function kn(e,t){return q0(e,t).replaceAll("\\","/")}function nF(e){switch(V0(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 Xf(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=zc(t,"utf-8"),i={text:n,lineStarts:iF(n)};return e.set(t,i),i}catch{return e.set(t,null),null}},positionAt:tF}}function iF(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function rF(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 oF(e){try{let t=JSON.parse(zc(jf(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 sF(e,t,n,i){let r=kn(n,i),o=Yf(t.name,t.version,r);return e.get(o)?.id??null}function Yf(e,t,n){let i=n.split("/").map(r=>`\`${r.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${i}/default.`}function Jc(e){Vt({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=pF(e.projectRoot,e.tsconfig);if(!cF(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new aF(e.dbPath);try{let i=Bf(n,e.projectRoot),r=mF(dF(e.dbPath),"augment-vue-meta.json"),o=Zf(n,e.projectRoot,e.tsconfig),s=fF(r,o,e.onStatus);if(s)return s;let a=gF({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:i,onStatus:e.onStatus});return yF(r,Zf(n,e.projectRoot,e.tsconfig),a),a}finally{n.close()}}function fF(e,t,n){let i=bF(e,t);return i&&n?.(`Vue references unchanged; reused ${i.resolvedReferences} cached resolved references.`),i}function gF(e){let t=qf(e.db,e.projectRoot,e.vueFiles),n=hF(e,t),i=Gf(n.occurrences),r=Uf(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 hF(e,t){if(Ff(e.vueFiles))return $f({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=SF({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return xF({...n,vueFiles:n.context.fileNames.filter(i=>i.endsWith(".vue"))})}function bF(e,t){try{let n=JSON.parse(lF(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function yF(e,t,n){uF(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
|
|
750
|
+
`)}function Zf(e,t,n){let i=e.prepare(`
|
|
747
751
|
SELECT
|
|
748
752
|
(SELECT COUNT(*) FROM documents) AS documents,
|
|
749
753
|
(SELECT COUNT(*) FROM global_symbols) AS symbols,
|
|
@@ -752,29 +756,29 @@ Affected consumer files:`),I.list(e.affectedConsumers,t=>` ${t.file} (${t.cons
|
|
|
752
756
|
(SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
|
|
753
757
|
(SELECT MAX(id) FROM chunks) AS maxChunkId,
|
|
754
758
|
(SELECT MAX(id) FROM global_symbols) AS maxSymbolId
|
|
755
|
-
`).get();return{version:2,tsconfig:n,files:
|
|
756
|
-
Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!
|
|
757
|
-
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
|
|
759
|
+
`).get();return{version:2,tsconfig:n,files:wn(t),db:i}}function SF(e){let t=Xf();return{projectRoot:e.projectRoot,context:Hf(e.projectRoot,e.configPath),symbolLookup:Vf(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function xF(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=CF(e,r);t.push(...o.occurrences),n+=o.skippedReferences}return{occurrences:t,skippedReferences:n}}function CF(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=kn(e.projectRoot,t.fileName),a=[...Kf(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:LF(a),processedStarts:new Set};return vF({...e,fileName:t.fileName,sourceInfo:r,sourceFile:s,map:o,tokenContext:c})}function vF(e){let t=[],n=0;for(let i of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(i.start))continue;let r=Jf(e.map,i.start);if(r===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,r+1)??[]).find(c=>!Qf(e.projectRoot,c.fileName));if(!s){n++;continue}let a=Wf(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}eg(t,e.sourceReader,e.sourceInfo,e.sourceFile,i,a),e.tokenContext.processedStarts.add(i.start),RF(t,e,i,r,a)}return{occurrences:t,skippedReferences:n}}function RF(e,t,n,i,r){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let o of wF(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&&(eg(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,r),t.tokenContext.processedStarts.add(o))}}function eg(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 LF(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function wF(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=kF(i,l.textSpan.start,o,r.text);u!==null&&a.push(u)}return a}function kF(e,t,n,i){let r=n.get(t);if(r?.text===i)return r.start;let o=Kc(e,t);if(o===null)return null;let s=n.get(o);return s?.text===i?s.start:null}async function ig(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:i=console.log,skipAutoInstall:r=!1}=e,o=TF(e),s=Date.now();Xc(Dt(o.outputScip),{recursive:!0}),Xc(Dt(o.outputDb),{recursive:!0});let a=e.languages??kt(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=XF(t,a,{pnpmWorkspaces:e.pnpmWorkspaces}),l=JF(mt(Dt(o.outputDb),"index.lock")),u=null;try{let d=FF({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:i});if(d)return d;HF(r,i);let m=$F(o);return u=m.runDir,await AF({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:m,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:r,onStatus:i})}finally{u&&Zc(u,{recursive:!0,force:!0}),l()}}function TF(e){let t=e.outputScip??mt(e.projectRoot,"index.scip"),n=e.outputDb??mt(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:mt(Dt(n),"meta.json")}}function FF(e){if(e.opts.skipIfUnchanged===!1||!Go(e.paths.outputScip)||!Go(e.paths.outputDb)||!YF(e.paths.metaPath,e.fingerprint))return null;Vt({projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let t=Date.now()-e.start;return 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:[]}}function $F(e){let t=EF(mt(Dt(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:mt(t,Wo(e.outputScip)),tempOutputDb:mt(t,Wo(e.outputDb)),tempMetaPath:mt(t,Wo(e.metaPath))}}async function AF(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:i,reusedLanguages:r}=await MF(e,t);r.length>0&&e.onStatus(`Reused ${r.length} cached language shard(s): ${r.join(", ")}`),OF(e,t,n,i);let o=Date.now()-e.start;return e.onStatus(`Done in ${(o/1e3).toFixed(1)}s`),{languages:n.map(s=>s.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:o,reused:!1,skipped:i}}async function MF(e,t){let n=jF(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}=VF({languages:e.languages.filter(l=>!i.has(l)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,onStatus:e.onStatus}),s=await wf(r,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:a}=UF(s,o),c=[...n,...a];return WF(c,o,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:c,skippedLanguages:o,reusedLanguages:[...i]}}function OF(e,t,n,i){BF(e.paths.outputDb,n),GF(n,e.tempPaths.tempOutputScip,e.onStatus),zF(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),Vt({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),ZF(e.tempPaths.tempMetaPath,{version:3,status:i.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,languageFingerprints:rg(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces}),requestedLanguages:e.languages,indexedLanguages:n.map(r=>r.language),skipped:[...i]}),QF({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath})}function jF(e){let t;try{t=JSON.parse(tg(e.paths.metaPath,"utf-8"))}catch{return[]}if(t.version!==3||!t.languageFingerprints)return[];let n=[],i=rg(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces});for(let r of e.languages){let o=og(e.paths.outputDb,r);Go(o)&&di(t.languageFingerprints[r])===di(i[r])&&n.push({language:r,scipPath:o})}return n}function BF(e,t){for(let n of t){let i=og(e,n.language);Xc(Dt(i),{recursive:!0}),n.scipPath!==i&&NF(n.scipPath,i)}}function HF(e,t){if(!Ue("scip")){if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
760
|
+
Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!af(t))throw new Error(`The scip CLI is required but could not be installed.
|
|
761
|
+
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function VF(e){let t=[],n=[],i=e.languages.map((r,o)=>({language:r,scipPath:e.languages.length>1?KF(e.tempOutputScip,r,o):e.tempOutputScip}));for(let{language:r,scipPath:o}of i){let s=qF({...e,language:r,scipPath:o});"skipped"in s?n.push(s.skipped):t.push(s.prepared)}return{preparedRuns:t,skippedLanguages:n}}function qF(e){let t=lr(e.language),n=Uo(t),i=qc(t,e.projectRoot);if(!i&&!Df(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...`),!Pf(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});return{prepared:{language:e.language,scipPath:e.scipPath,config:t,resolvedBinary:r,binary:o,args:s,env:Nf(t,e.env,r)}}}function UF(e,t){let n=[];for(let i of e)i.skipped?t.push(i.skipped):n.push({language:i.language,scipPath:i.scipPath});return{indexedOutputs:n}}function WF(e,t,n,i,r){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
|
|
758
762
|
`);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
|
|
759
|
-
`+o)}if(t.length!==0&&(
|
|
763
|
+
`+o)}if(t.length!==0&&(r(`Indexed ${e.length} of ${n.length} languages; skipped ${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.
|
|
760
764
|
`+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
|
|
761
|
-
`))}function
|
|
762
|
-
`),()=>{try{
|
|
763
|
-
`)}function
|
|
764
|
-
`).map(o=>o.slice(3).trim()).filter(o=>o!==""));return[...new Set(t.batches.flatMap(o=>o.entries.map(s=>s.file)))].filter(o=>
|
|
765
|
-
`),
|
|
766
|
-
`),o=new Set;for(let s of t){let a=
|
|
767
|
-
`)}function
|
|
768
|
-
${
|
|
769
|
-
`).map(s=>s.trim()).filter(s=>/\berror\b/i.test(s));return r.error&&o.length===0&&o.push(String(r.error)),{ok:!1,rawErrors:o,errorKeys:new Set(o.map(qp))}}var Jp={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"]},x_={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 Io(e,t){let n=t.languages??vt(e),r=n.map(s=>{let a=rp(Xr(s),e);return{...a,language:s,resolvedBinary:a.resolvedBinary??void 0}}),i=n.includes("typescript")?{language:"typescript",...Ap(e,t.semantic?.typescript?.tsconfigs)}:void 0,o=mc(e).map(s=>({label:s.label,coversExtensions:s.coversExtensions}));return{languages:n,indexers:r,semantic:i,checkers:o,gitAvailable:L_(e)}}function hc(e){let t=e.indexers.filter(i=>i.runnable).length,n=e.languages.length===0||t===0?"unavailable":t===e.indexers.length?"available":"partial",r=e.semantic?e.semantic.available?"available":"partial":"unavailable";return{languages:e.languages,matrix:e.languages.map(i=>C_(e,i)),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:r,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(i=>i.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 C_(e,t){let n=e.indexers.find(a=>a.language===t),r=n?.runnable?"available":"unavailable",i=x_[t],o=t==="typescript"?v_(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=R_(e,t);return{language:t,indexing:{id:"indexing",label:"SCIP indexing",status:r,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:r==="unavailable"?"unavailable":i.status,evidence:"heuristic",reason:r==="unavailable"?"Source fallback needs indexed documents before it can attach evidence.":i.reason},semantic:o,detectors:{id:"detectors",label:"Cleanup detectors",status:r==="unavailable"?"unavailable":"available",evidence:"heuristic",reason:r==="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 ${Jp[t].join(", ")} files.`}}}function v_(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 R_(e,t){let n=new Set(Jp[t]);return e.checkers.filter(r=>r.coversExtensions.some(i=>n.has(i)))}function L_(e){try{return S_("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{watch as I_}from"fs";import{existsSync as Gp,renameSync as zp}from"fs";import{join as D_,relative as k_}from"path";import{fork as w_}from"child_process";import N_ from"ignore";var Do=class{projectRoot;watchConfig;indexPaths;languages;pnpmWorkspaces;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.watchConfig=ym(t.config),this.indexPaths=Zn(t.projectRoot,t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=Yn(t.projectRoot),this.extraIgnore=N_(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"});try{let t=I_(this.projectRoot,{recursive:!0},(n,r)=>{r&&!this.stopped&&this.handleFileChange(r)});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.setStatus({state:"idle"})}handleFileChange(t){let n=k_(this.projectRoot,D_(this.projectRoot,t));if(this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||t.endsWith(".scipquery.json"))return;if(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 r=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:r}),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 i=Date.now()+r;this.setStatus({state:"cooldown",until:i,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=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex().then(r=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(r),this.dirty&&!this.stopped){let i=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:i,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(){return new Promise((t,n)=>{let r=Date.now(),i=this.indexPaths.dbPath+".tmp",o=P_(this.indexPaths.indexPath),s=w_(new URL("./reindex-worker.js",import.meta.url).pathname,[],{env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:o,SCIP_REINDEX_OUTPUT_DB:i,SCIP_REINDEX_LANGUAGES:this.languages?.join(",")??"",SCIP_REINDEX_PNPM_WORKSPACES:this.pnpmWorkspaces?"1":""},stdio:"pipe"});s.on("exit",a=>{if(a===0)try{Gp(i)&&zp(i,this.indexPaths.dbPath),Gp(o)&&zp(o,this.indexPaths.indexPath),t(Date.now()-r)}catch(c){n(new Error(`Atomic swap failed: ${c}`))}else n(new Error(`Reindex worker exited with code ${a}`))}),s.on("error",n)})}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)}};function P_(e){return e.endsWith(".scip")?e.slice(0,-5)+".tmp.scip":e+".tmp.scip"}import{chmodSync as __,existsSync as ko,readFileSync as wo,writeFileSync as Xp}from"fs";import{join as Zr}from"path";var Yr="<!-- scip-query:agent-setup:begin -->",bc="<!-- scip-query:agent-setup:end -->",Kp="# scip-query:agent-setup";function Yp(){if(process.stdin.isTTY)return"";try{return wo(0,"utf-8")}catch{return""}}function Zp(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function ef(e){let t=[`scip-query diff-gate found ${e.findings.length} issue(s) in this diff \u2014 fix or knowingly accept them before finishing:`];for(let n of e.findings)t.push(`- [${n.check}] ${n.message}`),t.push(` -> ${n.remediation}`);return t.join(`
|
|
770
|
-
`)}function
|
|
771
|
-
`);
|
|
772
|
-
`);
|
|
765
|
+
`))}function GF(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),bf(e.map(i=>i.scipPath),t)):e[0].scipPath!==t&&Yc(e[0].scipPath,t)}function zF(e,t,n,i){if(i("Converting to SQLite..."),!Go(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let r=Rf(e);r.removedDefinitionOccurrences>0&&i(`Sanitized ${r.removedDefinitionOccurrences} invalid definition occurrences across ${r.touchedDocuments} documents before SQLite conversion.`),DF("scip",["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 KF(e,t,n){let i=_F(e)||".scip",r=Wo(e,i);return mt(Dt(e),`${r}.${n+1}.${t}${i}`)}function JF(e){let t;try{t=PF(e,"wx")}catch(n){throw(typeof n=="object"&&n&&"code"in n?n.code:void 0)==="EEXIST"?new Error(`Another scip-query reindex is already running for ${Dt(e)}.`,{cause:n}):n}return ng(t,JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()})+`
|
|
766
|
+
`),()=>{try{IF(t)}finally{Zc(e,{force:!0})}}}function QF(e){Qc(e.tempOutputScip,e.outputScip),Qc(e.tempOutputDb,e.outputDb),Qc(e.tempMetaPath,e.metaPath)}function Qc(e,t){Zc(`${t}.tmp-replace`,{force:!0}),Yc(e,`${t}.tmp-replace`),Yc(`${t}.tmp-replace`,t)}function XF(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.pnpmWorkspaces===!0,files:wn(e)}}function rg(e,t,n){return Object.fromEntries(t.map(i=>{let r=lr(i).markerFiles;return[i,{version:1,languages:[i],pnpmWorkspaces:i==="typescript"&&n.pnpmWorkspaces===!0,files:wn(e,{language:i,markerFiles:r})}]}))}function og(e,t){return mt(Dt(e),"language-indexes",`${t}.scip`)}function YF(e,t){try{let n=JSON.parse(tg(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&di(n.fingerprint)===di(t)&&di([...n.indexedLanguages??[]].sort())===di(t.languages)}catch{return!1}}function ZF(e,t){ng(e,`${JSON.stringify(t,null,2)}
|
|
767
|
+
`)}function di(e){return JSON.stringify(e)}import{existsSync as sg,readFileSync as e$}from"fs";function ag(e,t,n){let i=new Date().toISOString();if(!sg(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!sg(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(e$(n.metaPath,"utf-8")),o=t.languages??kt(e),s=t$(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,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 t$(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces===!0,files:wn(e)}}import{execFileSync as C$}from"child_process";import{createRequire as n$}from"module";var i$=n$(import.meta.url);function cg(e,t=[]){let n=r$(),i=Os(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 r$(){try{return i$.resolve("ts-morph"),!0}catch{return!1}}import{execFileSync as mi,spawnSync as mg}from"child_process";import{existsSync as It,mkdtempSync as pg,readFileSync as o$,readdirSync as s$,rmSync as fg,symlinkSync as a$,writeFileSync as c$}from"fs";import{tmpdir as gg}from"os";import{join as We}from"path";var l$=3e5,u$=12;function el(e,t,n={}){let i=tl(e);if(i.length===0)return{checkers:[],uncoveredFiles:[],baselineErrors:0,dirtyOverlap:[],batches:[]};let r=d$(t,i),o=n.timeoutMs??l$,s=f$(e,t),a=pg(We(gg(),"scip-cleanup-verify-")),c=[],l=new Set;try{mi("git",["-C",e,"worktree","add","--detach","--force",a,"HEAD"],{stdio:"ignore"}),g$(e,a);for(let u of i)for(let d of dg(u,a,o).errorKeys)l.add(d);for(let u of t.batches){bg(a,u);let d=[];for(let m of i){let p=dg(m,a,o);d.push(...p.rawErrors.filter(h=>!l.has(hg(h))))}if(d.length===0)c.push({depth:u.depth,status:"verified"});else{c.push({depth:u.depth,status:"failed",errors:d.slice(0,u$)});break}}}finally{try{mi("git",["-C",e,"worktree","remove","--force",a],{stdio:"ignore"})}catch{fg(a,{recursive:!0,force:!0})}}return{checkers:i.map(u=>u.label),uncoveredFiles:r,baselineErrors:l.size,dirtyOverlap:s,batches:c}}function d$(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 hg(e){return e.replace(/\(\d+,\d+\)|:\d+(?::\d+)?/g,"").trim()}var lg=[".ts",".tsx",".mts",".cts",".js",".jsx",".vue"];function tl(e){let t=[];if(It(We(e,"tsconfig.json"))){let n=We(e,"node_modules",".bin","tsc");t.push(It(n)?{label:"tsc --noEmit",binary:n,args:["--noEmit"],coversExtensions:lg}:{label:"npx tsc --noEmit",binary:"npx",args:["tsc","--noEmit"],coversExtensions:lg})}if(It(We(e,"go.mod"))&&t.push({label:"go build ./...",binary:"go",args:["build","./..."],coversExtensions:[".go"]}),["pyproject.toml","setup.py","requirements.txt"].some(n=>It(We(e,n)))){let n=m$();n&&t.push(n)}for(let n of p$(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:We(e,n,"..","target")}});return t}function m$(){return ug("ruff")?{label:"ruff check --select E9,F821,F822",binary:"ruff",args:["check","--quiet","--select","E9,F821,F822","."],coversExtensions:[".py"]}:ug("python3")?{label:"python3 -m compileall (syntax only)",binary:"python3",args:["-m","compileall","-q","."],coversExtensions:[".py"]}:null}function ug(e){try{return mg(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}function p$(e){let t=[];if(It(We(e,"Cargo.toml")))return t.push("Cargo.toml"),t;let n;try{n=s$(e)}catch{return t}for(let i of n)i==="node_modules"||i.startsWith(".")||It(We(e,i,"Cargo.toml"))&&t.push(`${i}/Cargo.toml`);return t}function f$(e,t){let n;try{n=mi("git",["-C",e,"status","--porcelain"],{encoding:"utf-8"})}catch{return[]}let i=new Set(n.split(`
|
|
768
|
+
`).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 g$(e,t){for(let n of["node_modules"]){let i=We(e,n),r=We(t,n);if(It(i)&&!It(r))try{a$(i,r,"junction")}catch{}}}function bg(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=We(e,i);It(o)&&c$(o,h$(o$(o,"utf-8"),r,{rust:i.endsWith(".rs")}))}}function nl(e,t){for(let n of t)bg(e,n)}function yg(e,t){let n=pg(We(gg(),"scip-cleanup-patch-"));try{return mi("git",["-C",e,"worktree","add","--detach","--force",n,"HEAD"],{stdio:"ignore"}),nl(n,t),mi("git",["-C",n,"diff","--binary"],{encoding:"utf-8",maxBuffer:32*1024*1024})}finally{try{mi("git",["-C",e,"worktree","remove","--force",n],{stdio:"ignore"})}catch{fg(n,{recursive:!0,force:!0})}}}function il(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 rl(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 h$(e,t,n={}){let i=e.split(`
|
|
769
|
+
`),r=(n.rust===!0?b$(e):Zt(e)).split(`
|
|
770
|
+
`),o=new Set;for(let s of t){let a=y$(i,s.start),c=x$(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(`
|
|
771
|
+
`)}function b$(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 y$(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 S$=200;function x$(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>S$)break}return n}function dg(e,t,n){let i=mg(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??""}
|
|
772
|
+
${i.stderr??""}`.split(`
|
|
773
|
+
`).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(hg))}}var Sg={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"]},v$={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 zo(e,t){let n=t.languages??kt(e),i=n.map(s=>{let a=Ef(lr(s),e);return{...a,language:s,resolvedBinary:a.resolvedBinary??void 0}}),r=n.includes("typescript")?{language:"typescript",...cg(e,t.semantic?.typescript?.tsconfigs)}:void 0,o=tl(e).map(s=>({label:s.label,coversExtensions:s.coversExtensions}));return{languages:n,indexers:i,semantic:r,checkers:o,gitAvailable:k$(e)}}function ol(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=>R$(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 R$(e,t){let n=e.indexers.find(a=>a.language===t),i=n?.runnable?"available":"unavailable",r=v$[t],o=t==="typescript"?L$(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=w$(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 ${Sg[t].join(", ")} files.`}}}function L$(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 w$(e,t){let n=new Set(Sg[t]);return e.checkers.filter(i=>i.coversExtensions.some(r=>n.has(r)))}function k$(e){try{return C$("git",["rev-parse","--is-inside-work-tree"],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}import{watch as D$}from"fs";import{existsSync as xg,renameSync as Cg}from"fs";import{join as I$,relative as N$}from"path";import{fork as E$}from"child_process";import P$ from"ignore";var Ko=class{projectRoot;watchConfig;indexPaths;languages;pnpmWorkspaces;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.watchConfig=Wp(t.config),this.indexPaths=ai(t.projectRoot,t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=si(t.projectRoot),this.extraIgnore=P$(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"});try{let t=D$(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.setStatus({state:"idle"})}handleFileChange(t){let n=N$(this.projectRoot,I$(this.projectRoot,t));if(this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||t.endsWith(".scipquery.json"))return;if(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 i=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:i}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-t;this.dirty=!0;let r=Date.now()+i;this.setStatus({state:"cooldown",until:r,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex().then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let r=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:r,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(){return new Promise((t,n)=>{let i=Date.now(),r=this.indexPaths.dbPath+".tmp",o=_$(this.indexPaths.indexPath),s=E$(new URL("./reindex-worker.js",import.meta.url).pathname,[],{env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:o,SCIP_REINDEX_OUTPUT_DB:r,SCIP_REINDEX_LANGUAGES:this.languages?.join(",")??"",SCIP_REINDEX_PNPM_WORKSPACES:this.pnpmWorkspaces?"1":""},stdio:"pipe"});s.on("exit",a=>{if(a===0)try{xg(r)&&Cg(r,this.indexPaths.dbPath),xg(o)&&Cg(o,this.indexPaths.indexPath),t(Date.now()-i)}catch(c){n(new Error(`Atomic swap failed: ${c}`))}else n(new Error(`Reindex worker exited with code ${a}`))}),s.on("error",n)})}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)}};function _$(e){return e.endsWith(".scip")?e.slice(0,-5)+".tmp.scip":e+".tmp.scip"}import{chmodSync as T$,existsSync as Jo,readFileSync as Qo,writeFileSync as Lg}from"fs";import{join as dr}from"path";var ur="<!-- scip-query:agent-setup:begin -->",sl="<!-- scip-query:agent-setup:end -->",vg="# scip-query:agent-setup";function wg(){if(process.stdin.isTTY)return"";try{return Qo(0,"utf-8")}catch{return""}}function kg(e){if(!e.trim())return!1;try{return JSON.parse(e).stop_hook_active===!0}catch{return!1}}function Dg(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(`
|
|
774
|
+
`)}function Ig(e,t={}){let n={written:[],unchanged:[],skipped:[]};return F$(e,n),t.gitHook&&$$(e,n),n}function F$(e,t){let n=[ur,"## 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.",sl].join(`
|
|
775
|
+
`);Rg(e,"AGENTS.md",n,t);let i=Jo(dr(e,"CLAUDE.md"))?Qo(dr(e,"CLAUDE.md"),"utf-8"):"";if(i.includes("@AGENTS.md")&&!i.includes(ur)){t.unchanged.push("CLAUDE.md");return}let r=[ur,"@AGENTS.md",sl].join(`
|
|
776
|
+
`);Rg(e,"CLAUDE.md",r,t)}function Rg(e,t,n,i){let r=dr(e,t),o=Jo(r)?Qo(r,"utf-8"):"",s;if(o.includes(ur)){let a=new RegExp(`${ur}[\\s\\S]*?${sl}`);s=o.replace(a,n)}else s=o.length>0?`${o.replace(/\n*$/,`
|
|
773
777
|
|
|
774
778
|
`)}${n}
|
|
775
779
|
`:`${n}
|
|
776
|
-
`;s===o?
|
|
777
|
-
`);if(
|
|
780
|
+
`;s===o?i.unchanged.push(t):(Lg(r,s),i.written.push(t))}function $$(e,t){let n=dr(e,".git","hooks");if(!Jo(n)){t.skipped.push({target:".git/hooks/pre-commit",reason:"no .git/hooks directory (not a git repository?)"});return}let i=dr(n,"pre-commit"),r=["#!/bin/sh",vg,"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(`
|
|
781
|
+
`);if(Jo(i)){let o=Qo(i,"utf-8");if(o.includes(vg)){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}}Lg(i,r),T$(i,493),t.written.push(".git/hooks/pre-commit")}import{existsSync as A$,mkdirSync as M$,writeFileSync as O$}from"fs";import{dirname as j$,join as B$}from"path";function Ng(e,t={}){let n=B$(e,".github","workflows","scip-query.yml"),i=H$();return A$(n)&&!t.force?{path:n,written:!1,skipped:!0,content:i,reason:"Workflow already exists. Re-run with --force to overwrite."}:(t.dryRun||(M$(j$(n),{recursive:!0}),O$(n,i)),{path:n,written:!t.dryRun,skipped:!1,content:i})}function H$(){return`name: scip-query
|
|
778
782
|
|
|
779
783
|
on:
|
|
780
784
|
pull_request:
|
|
@@ -792,117 +796,130 @@ jobs:
|
|
|
792
796
|
- run: npm ci
|
|
793
797
|
- run: npx scip-query reindex
|
|
794
798
|
- run: npx scip-query diff-gate --base "origin/\${{ github.base_ref }}"
|
|
795
|
-
`}var
|
|
796
|
-
${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
|
|
799
|
+
`}var Eg=Symbol("option-value-source");function z(e){return(...t)=>{let{args:n,opts:i}=q$(t);dt(r=>e({db:r,args:n,opts:i}))}}function Q(e,t){return z(n=>{let i=Zp(n.db,e,R(n.opts,"full"),{quiet:R(n.opts,"json")});t({...n,budget:i})})}function Pg(e){return z(t=>pi(t,e,{kind:"list"}))}function _g(e){return z(t=>pi(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function Tg(e){return z(t=>pi(t,e,{kind:"grouped",key:e.key}))}function Dn(e){return z(t=>cl(t,e))}function Fg(e){return Dn({commandName:e.commandName,query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>D.sectionedReport(e.sections(t,n)),toJson:e.toJson,after:e.after})}function Ye(e,t){return Q(e,n=>cl(n,{...t,commandName:t.commandName??e}))}function $g(e,t){return Ye(e,{commandName:t.commandName??e,query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,i)=>D.sectionedReport(t.sections(n,i)),toJson:t.toJson,after:t.after})}function Nt(e,t){return Q(e,n=>pi(n,{...t,commandName:e},{kind:"list"}))}function Xo(e,t){return Q(e,n=>pi(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Yo(e,t){return Q(e,n=>pi(n,{...t,commandName:e},{kind:"grouped",key:t.key}))}function V(e,t){return String(e[t])}function ge(e,t){let n=e[t];return typeof n=="string"?n:void 0}function P(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Ne(e,t){let n=e[t];return typeof n=="number"?n:void 0}function R(e,t){return!!e[t]}function Ag(e,t){let n=e[t];return Array.isArray(n)&&n.every(i=>typeof i=="string")?n:[]}function I(e,t,n){return Ne(e,t)??n}function O(e,t,n){let i=Ne(e,t),r=i!==void 0&&al(e,t)!=="default";if(R(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 al(e,t){return e[Eg]?.(t)}function pi(e,t,n){cl(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"?D.list(i,o=>t.format(o,r)):n.kind==="table"?D.table(n.headers,i.map(o=>t.format(o,r)),n.dashWidths):D.groupedByFile(i,o=>t.format(o,r),n.key?o=>n.key(o,r):void 0)},toJson:t.toJson,after:t.after})}function cl(e,t){let n=t.query(e);if(R(e.opts,"json")){$(t.commandName,e.args,e.opts,t.toJson?t.toJson(n,e):n);return}let i=t.emptyMessage?.(n,e);if(i){D.empty(i);return}t.heuristicLabel&&li(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function $(e,t,n,i){console.log(JSON.stringify({command:e,args:V$(t),options:n,result:i},null,2))}function V$(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function q$(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:xe(t)}}function xe(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,Eg,{value:i=>t.getOptionValueSource(i),enumerable:!1}),n)}return e}var W$=new Set(["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"]);function G$(e){return e.filter(t=>W$.has(t))}async function Mg(e){let t=xe(e),n=ye(),i=wt(n),r=ai(n,i);try{let o=G$(Ag(t,"language")),s=await ig({projectRoot:n,languages:o.length>0?o:i.languages,outputScip:r.indexPath,outputDb:r.dbPath,pnpmWorkspaces:R(t,"pnpmWorkspaces")||i.indexer?.typescript?.pnpmWorkspaces,skipIfUnchanged:!R(t,"force"),allowPartial:R(t,"allowPartial"),indexerConcurrency:Ne(t,"indexerConcurrency")});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 Og(){let e=ye(),t=Cc(e);try{let n=Vt({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 jg(e){let t=xe(e),n=ye(),i=Cc(n);try{let r=Jc({projectRoot:n,dbPath:i,tsconfig:P(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 Bg(e){let t=xe(e);dt(n=>{let i=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),r=at(n,{base:P(t,"base")}),o=po(n,i,r.changedFiles,r.changedRanges);console.log(JSON.stringify(o))})}function Hg(e){let t=xe(e);try{rf(nf({base:P(t,"base")}))}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Vg(e,t){let n=xe(t);dt(i=>{sr.includes(e)||(console.error(`error: Unknown health phase: ${e}`),process.exit(1));let r=ac(i,e,{scope:P(n,"scope"),full:R(n,"full")});console.log(JSON.stringify(r))})}function qg(e){let t=xe(e);if(R(t,"writeBaseline")||R(t,"baseline")){z$(t);return}try{let n=ef({scope:P(t,"scope"),full:!0,json:R(t,"json")});if(R(t,"json")){$("health",[],t,n);return}tf(n,!1)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function z$(e){let t=P(e,"scope");dt(n=>{if(R(e,"writeBaseline")){let r=Ya(n,{scope:t});console.log(`Baseline written to ${r.path} (${r.findingCount} finding(s)).`);return}let i=Zi(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 Ug(){let e=lf(),t=e.installed.length+e.alreadyLinked.length;console.log(`
|
|
800
|
+
${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 Wg(){let e=!1;Nc()?console.log("scip CLI: installed"):(Ec(),e=!0);let t=ye(),n=wt(t),i=zo(t,n);if(i.languages.length===0){console.log(`
|
|
797
801
|
No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
|
|
798
|
-
Detected languages: ${
|
|
799
|
-
Indexer readiness:`);for(let
|
|
800
|
-
Semantic provider readiness:`),console.log(`${o} typescript: ts-morph${s}`),
|
|
801
|
-
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.")}function
|
|
802
|
+
Detected languages: ${i.languages.join(", ")}`),console.log(`
|
|
803
|
+
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(`
|
|
804
|
+
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 Gg(e){Kg(e,"capabilities")}function zg(e){Kg(e,"capability-matrix")}function Kg(e,t){let n=xe(e),i=ye(),r=wt(i),o=zo(i,r),s=ol(o);if(R(n,"json")){$(t,[],n,s);return}ll(s)}function Jg(){let e=ye(),t=kt(e),n=Gp(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Qg(e){let t=xe(e),n=ye(),i=wt(n),r=To(i,{projectRoot:n});if(R(t,"json"))$("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 Xg(e,t){let n=xe(t),i=P(n,"reason");if(!i||i.trim()===""){console.error("error: suppress requires --reason <text>."),process.exitCode=1;return}try{let r=zp(ye(),{id:String(e),check:P(n,"check"),file:P(n,"file"),reason:i,expiresAt:P(n,"expiresAt")});if(R(n,"json")){$("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 Yg(e){let t=xe(e),{report:n,hasIndexerProblems:i,hasErrors:r}=Zg("doctor");R(t,"json")?$("doctor",[],t,n):K$(n,i),process.exitCode=r?1:0}function Zg(e){let{projectRoot:t,config:n,paths:i,dbPath:r}=Fo(),o=To(n,{projectRoot:t}),s=zo(t,n),a=ol(s),c=ag(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:U$(r),configDiagnostics:o,readiness:s,freshness:c,capabilities:a,ok:!u},hasIndexerProblems:l,hasErrors:u}}function eh(e){let t=xe(e),n=ye(),i=Ig(n,{gitHook:R(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(`
|
|
805
|
+
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.")}function th(e){let t=xe(e),n=ye(),i=Ng(n,{force:R(t,"force"),dryRun:R(t,"dryRun")});if(R(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 nh(e){let t=xe(e),n=ye(),i=wt(n),r=Ne(t,"debounce"),o=Ne(t,"cooldown");r&&((i.watch??={}).debounceMs=r),o&&((i.watch??={}).cooldownMs=o);let s=new Ko({projectRoot:n,config:i,languages:i.languages,onStatus:a=>{process.stdout.write(`\r\x1B[K${Jp(a)}`)},onReindexComplete:a=>{console.log(`
|
|
802
806
|
Reindex complete in ${(a/1e3).toFixed(1)}s`)},onError:a=>{console.error(`
|
|
803
|
-
Watch error: ${a.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${
|
|
807
|
+
Watch error: ${a.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${i.watch?.debounceMs??3e4}ms | Cooldown: ${i.watch?.cooldownMs??6e4}ms`),console.log(`Press Ctrl+C to stop.
|
|
804
808
|
`),s.start(),process.on("SIGINT",()=>{s.stop(),console.log(`
|
|
805
|
-
Stopped.`),process.exit(0)})}function
|
|
806
|
-
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
|
|
807
|
-
Safe to delete.`,m),d.length>0&&(u.length>0&&console.log(""),
|
|
809
|
+
Stopped.`),process.exit(0)})}function ih(e){let t=xe(e),{report:n}=Zg("status");if(R(t,"json")){$("status",[],t,{...n,stats:Q$(n.exists)});return}J$(n,{capabilities:R(t,"capabilities")})}function K$(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})`:""}`),ll(e.capabilities)}function J$(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})`:""}`),X$(e.exists),t.capabilities&&(console.log(""),ll(e.capabilities))}function Q$(e){if(e)return dt(t=>{let n=Ae(t);return{symbols:n.symbols,files:n.documents,indexSizeBytes:n.indexSizeBytes,lastBuilt:n.lastBuilt?.toISOString()}})}function X$(e){e&&dt(t=>{let n=Ae(t);if(console.log(`Symbols: ${n.symbols}`),console.log(`Files: ${n.documents}`),console.log(`Size: ${ci(n.indexSizeBytes)}`),n.lastBuilt){let i=Math.round((Date.now()-n.lastBuilt.getTime())/1e3);console.log(`Built: ${i}s ago`)}})}function ll(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(`
|
|
810
|
+
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 mr(e){return{...e,options:T(e.options)}}function pt({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,...o}){let s=mr(o);return{...s,renderShape:"list",handler:Pg({commandName:s.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r})}}function Zo({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,headers:o,dashWidths:s,...a}){let c=mr(a);return{...c,renderShape:"table",handler:_g({commandName:c.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,headers:o,dashWidths:s})}}function rh({query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,key:o,...s}){let a=mr(s);return{...a,renderShape:"grouped-by-file",handler:Tg({commandName:a.id,query:e,format:t,emptyMessage:n,heuristicLabel:i,after:r,key:o})}}function oh({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:r,after:o,...s}){let a=mr(s);return{...a,renderShape:"sectioned-report",handler:Fg({commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:r,sections:i,after:o})}}function es({query:e,emptyMessage:t,heuristicLabel:n,sections:i,before:r,after:o,...s}){let a=mr(s);return{...a,budget:a.budget??"semantic",renderShape:"sectioned-report",handler:$g(a.id,{commandName:a.id,query:e,emptyMessage:t,heuristicLabel:n,before:r,sections:i,after:o})}}function ul(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(` ${Se(l.startLine,l.endLine)} (${l.loc} LOC) ${l.shortName}`)}}var sh=Q("dead",({db:e,args:t,opts:n,budget:i})=>{let r={scope:ge(t,0)||void 0,minLoc:I(n,"minLoc",1),includeTests:R(n,"includeTests"),skipBarrels:R(n,"skipBarrels"),includeMembers:R(n,"includeMembers"),scanLimit:i.scanLimit,semantic:i.semantic},o=xt(e,r),s=o.symbols.filter(b=>b.kind==="dead-code"),a=o.symbols.filter(b=>b.kind!=="dead-code"),c=!R(n,"onlyInternal"),l=!R(n,"onlyDead"),u=c?s:[],d=l?a:[],m=u.reduce((b,S)=>b+S.loc,0),p=d.reduce((b,S)=>b+S.loc,0),h={total:u.length+d.length,deadCode:u.length,fileInternal:d.length,loc:m+p};if(R(n,"json")){$("dead",t,n,{...o,shown:{deadCode:u,fileInternal:d},shownCounts:h,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){D.empty("No matching dead-code symbols found.");return}u.length>0&&ul(u,"DEAD CODE",` Zero references anywhere \u2014 no cross-file callers AND no same-file uses.
|
|
811
|
+
Safe to delete.`,m),d.length>0&&(u.length>0&&console.log(""),ul(d,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
|
|
808
812
|
single-use helper, an abstraction-in-progress, or a callback registered
|
|
809
813
|
through a framework path that static analysis cannot trace (signal
|
|
810
814
|
handlers, event listeners, dependency injection). NOT necessarily dead \u2014
|
|
811
|
-
review case by case.`,
|
|
812
|
-
\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(" + ")}`)})
|
|
813
|
-
${e.length} unused import(s)`)}),
|
|
814
|
-
${e.length} isolated symbol(s)`)}),
|
|
815
|
-
${
|
|
816
|
-
${
|
|
817
|
-
|
|
818
|
-
${
|
|
819
|
-
|
|
820
|
-
${e.
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
815
|
+
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(`
|
|
816
|
+
\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(" + ")}`)}),ah=Nt("unused-imports",{query:({db:e,args:t,budget:n})=>ta(e,V(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
|
|
817
|
+
${e.length} unused import(s)`)}),ch=Yo("isolated",{query:({db:e,opts:t,budget:n})=>ln(e,{scope:P(t,"scope"),minLoc:I(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${Se(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
|
|
818
|
+
${e.length} isolated symbol(s)`)}),lh=Q("extract-candidates",({db:e,args:t,opts:n,budget:i})=>{let r=hn(e,{scope:P(n,"scope"),minLoc:I(n,"minLoc",10),minCallees:I(n,"minCallees",6),limit:O(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic});if(R(n,"json")){$("extract-candidates",t,n,r);return}if(r.length===0)return D.empty("No extraction candidates found.");li("extraction candidates");for(let o of r){console.log(`
|
|
819
|
+
${fe(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(`
|
|
820
|
+
${r.length} extraction candidate(s) found.`)}),uh=Q("locality-candidates",({db:e,args:t,opts:n,budget:i})=>{let r=Pa(e,{target:ge(t,0)||void 0,scope:P(n,"scope"),minConsumers:I(n,"minConsumers",1),limit:O(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic,architecturalBoundarySegments:e.config.locality?.architecturalBoundarySegments});if(R(n,"json")){$("locality-candidates",t,n,r);return}if(r.length===0)return D.empty("No locality candidates found.");li("locality candidates");for(let o of r){let s=o.sourceUnit.kind==="symbol"&&o.sourceUnit.startLine!==void 0&&o.sourceUnit.endLine!==void 0?fe(o.sourceUnit.file,o.sourceUnit.startLine,o.sourceUnit.endLine):o.sourceUnit.file;if(console.log(`
|
|
821
|
+
${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(`
|
|
822
|
+
${r.length} locality candidate(s) found.`)}),dh=Nt("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>Rn(e,{scope:P(t,"scope"),maxLoc:I(t,"maxLoc",15),limit:O(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${fe(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
|
|
823
|
+
Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn}, tier: ${e.actionTier})`+(e.boundaryEvidence.length>0?`
|
|
824
|
+
Boundary evidence: ${e.boundaryEvidence.join("; ")}`:""),emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
|
|
825
|
+
${e.length} wrapper candidate(s).`)}),mh=Nt("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>Cn(e,{scope:P(t,"scope"),maxLoc:I(t,"maxLoc",15),limit:O(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${fe(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
|
|
826
|
+
Forwards to: ${e.forwardsToShort} (${e.forwardsToFile}, tier: ${e.actionTier})
|
|
827
|
+
Recommendation: ${e.recommendation}`+(e.boundaryEvidence.length>0?`
|
|
828
|
+
Boundary evidence: ${e.boundaryEvidence.join("; ")}`:"")+(e.publicFacadeEvidence.length>0?`
|
|
829
|
+
Public facade evidence: ${e.publicFacadeEvidence.join("; ")}`:""),emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
|
|
830
|
+
${e.length} passthrough candidate(s).`)}),ph=Nt("stale-abstractions",{query:({db:e,opts:t,budget:n})=>vn(e,{scope:P(t,"scope"),minLoc:I(t,"minLoc",3),limit:O(t,"limit",30),includeLowConfidence:R(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}] ${fe(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
|
|
831
|
+
${e.reason}
|
|
832
|
+
Kind: ${e.stalenessKind}; tier: ${e.actionTier}
|
|
833
|
+
Recommendation: ${e.recommendation}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
|
|
834
|
+
${e.length} stale abstraction(s).`)}),fh=Xo("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>rr(e,{scope:P(t,"scope"),minLoc:I(t,"minLoc",10),limit:O(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]}),gh=Ye("similar",{query:({db:e,args:t,opts:n,budget:i})=>{let r=ge(t,0);return r?{mode:"target",rows:Vi(e,r,{minSimilarity:I(n,"minSimilarity",.4),limit:O(n,"limit",20),scanLimit:i.scanLimit,semantic:i.semantic})}:{mode:"all",rows:Ct(e,{minSimilarity:I(n,"minSimilarity",.4),limit:O(n,"limit",20),scope:P(n,"scope"),minCallees:I(n,"minCallees",4),crossFileOnly:R(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"){D.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=[`
|
|
835
|
+
${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(`
|
|
836
|
+
`)});return}D.list(e.rows,t=>`
|
|
825
837
|
${Math.round(t.similarity*100)}% similar:
|
|
826
838
|
A: ${t.shortNameA} (${t.fileA})
|
|
827
839
|
B: ${t.shortNameB} (${t.fileB})
|
|
828
|
-
|
|
829
|
-
${
|
|
840
|
+
Evidence class: ${t.evidenceClass} (tier: ${t.actionTier})
|
|
841
|
+
Recommendation: ${t.recommendation}
|
|
842
|
+
`+(t.evidenceClassReasons.length?` Evidence reasons: ${t.evidenceClassReasons.join("; ")}
|
|
843
|
+
`:"")+` Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
|
|
844
|
+
${e.rows.length} similar pair(s) found.`)}}),hh=Dn({commandName:"similar-files",query:({db:e,args:t,opts:n})=>Ca(e,{minSimilarity:I(n,"minSimilarity",.5),limit:O(n,"limit",20),scope:P(n,"scope"),minDeps:Ne(n,"minDeps"),filePattern:ge(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{D.list(e,t=>{let n=[`
|
|
830
845
|
${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(`
|
|
831
846
|
`)}),console.log(`
|
|
832
|
-
${e.length} similar pair(s) found.`)}}),
|
|
847
|
+
${e.length} similar pair(s) found.`)}}),bh=Ye("react-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>un(e,{minSimilarity:I(n,"minSimilarity",.62),minTokens:I(n,"minTokens",8),limit:O(n,"limit",20),scope:P(n,"scope"),scanLimit:i.scanLimit,filePattern:ge(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React component structures found.":void 0,heuristicLabel:"React component duplicate candidates",render:e=>{D.list(e,t=>{let n=[`
|
|
833
848
|
${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(`
|
|
834
849
|
`)}),console.log(`
|
|
835
|
-
${e.length} duplicated React component pair(s) found.`)}}),
|
|
836
|
-
${Math.round(t.similarity*100)}% similar React behavior:`,` ${t.componentA} (${t.fileA})`,` ${t.componentB} (${t.fileB})`,` ${t.reason}`];return 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(`
|
|
850
|
+
${e.length} duplicated React component pair(s) found.`)}}),yh=Ye("react-hook-candidates",{query:({db:e,args:t,opts:n,budget:i})=>mn(e,{minSimilarity:I(n,"minSimilarity",.45),minSharedBehaviors:I(n,"minSharedBehaviors",6),limit:O(n,"limit",20),scope:P(n,"scope"),scanLimit:i.scanLimit,filePattern:ge(t,0)}),emptyMessage:e=>e.length===0?"No duplicated React hook behavior candidates found.":void 0,heuristicLabel:"React hook extraction candidates",render:e=>{D.list(e,t=>{let n=[`
|
|
851
|
+
${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(`
|
|
837
852
|
`)}),console.log(`
|
|
838
|
-
${e.length} React hook candidate pair(s) found.`)}}),
|
|
839
|
-
${t.componentLines} component line(s): ${t.component} (${t.file})`,` Dominant pressure: ${t.dominantPressure}`,` File lines: ${t.fileLines}; JSX tokens: ${t.jsxTokens}; behavior tokens: ${t.behaviorTokens}`,` Reasons: ${t.reasons.join("; ")}`].join(`
|
|
853
|
+
${e.length} React hook candidate pair(s) found.`)}}),Sh=Ye("react-large-component-pressure",{query:({db:e,args:t,opts:n,budget:i})=>Wi(e,{minComponentLines:I(n,"minComponentLines",300),minFileLines:I(n,"minFileLines",800),minJsxTokens:I(n,"minJsxTokens",80),minBehaviorTokens:I(n,"minBehaviorTokens",40),limit:O(n,"limit",20),scope:P(n,"scope"),scanLimit:i.scanLimit,filePattern:ge(t,0)}),emptyMessage:e=>e.length===0?"No large React component pressure found.":void 0,heuristicLabel:"large React component pressure candidates",render:e=>{D.list(e,t=>[`
|
|
854
|
+
${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(`
|
|
840
855
|
`)),console.log(`
|
|
841
|
-
${e.length} large React component(s) found.`)}}),
|
|
856
|
+
${e.length} large React component(s) found.`)}}),xh=Ye("vue-component-duplicates",{query:({db:e,args:t,opts:n,budget:i})=>pn(e,{minSimilarity:I(n,"minSimilarity",.62),minTokens:I(n,"minTokens",8),limit:O(n,"limit",20),scope:P(n,"scope"),scanLimit:i.scanLimit,filePattern:ge(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue component structures found.":void 0,heuristicLabel:"Vue component duplicate candidates",render:e=>{D.list(e,t=>{let n=[`
|
|
842
857
|
${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(`
|
|
843
858
|
`)}),console.log(`
|
|
844
|
-
${e.length} duplicated Vue component pair(s) found.`)}}),
|
|
845
|
-
${Math.round(t.similarity*100)}% similar Vue behavior:`,` ${t.fileA}`,` ${t.fileB}`,` ${t.reason}`];return 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(`
|
|
859
|
+
${e.length} duplicated Vue component pair(s) found.`)}}),Ch=Ye("vue-composable-candidates",{query:({db:e,args:t,opts:n,budget:i})=>gn(e,{minSimilarity:I(n,"minSimilarity",.45),minSharedBehaviors:I(n,"minSharedBehaviors",6),limit:O(n,"limit",20),scope:P(n,"scope"),scanLimit:i.scanLimit,filePattern:ge(t,0)}),emptyMessage:e=>e.length===0?"No duplicated Vue behavior candidates found.":void 0,heuristicLabel:"Vue composable extraction candidates",render:e=>{D.list(e,t=>{let n=[`
|
|
860
|
+
${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(`
|
|
846
861
|
`)}),console.log(`
|
|
847
|
-
${e.length} Vue composable candidate pair(s) found.`)}}),
|
|
848
|
-
${t.totalLines} total line(s): ${t.file}`,` Dominant pressure: ${t.dominantPressure}`,` Blocks: template ${t.templateLines}, script ${t.scriptLines}, style ${t.styleLines}, external script ${t.externalScriptLines}, custom ${t.customBlockLines}`];return t.externalScriptPaths.length&&n.push(` External scripts: ${t.externalScriptPaths.join(", ")}`),n.push(` Reasons: ${t.reasons.join("; ")}`),n.join(`
|
|
862
|
+
${e.length} Vue composable candidate pair(s) found.`)}}),vh=Ye("vue-large-view-pressure",{query:({db:e,args:t,opts:n,budget:i})=>Gi(e,{minTotalLines:R(n,"reviewThresholds")&&al(n,"minTotalLines")==="default"?300:I(n,"minTotalLines",800),minTemplateLines:I(n,"minTemplateLines",300),minScriptLines:I(n,"minScriptLines",300),minStyleLines:I(n,"minStyleLines",500),limit:O(n,"limit",20),scope:P(n,"scope"),scanLimit:i.scanLimit,filePattern:ge(t,0)}),emptyMessage:e=>e.length===0?"No large Vue view pressure found.":void 0,heuristicLabel:"large Vue view pressure candidates",render:e=>{D.list(e,t=>{let n=[`
|
|
863
|
+
${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(`
|
|
849
864
|
`)}),console.log(`
|
|
850
|
-
${e.length} large Vue view pressure file(s) found.`)}}),
|
|
851
|
-
\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
|
|
852
|
-
${e.length} similar chain pair(s) found.`)}}),
|
|
853
|
-
|
|
854
|
-
${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)`)}}),
|
|
865
|
+
${e.length} large Vue view pressure file(s) found.`)}}),Rh=Dn({commandName:"similar-chains",query:({db:e,opts:t})=>ka(e,{minSimilarity:I(t,"minSimilarity",.5),limit:O(t,"limit",15),scope:P(t,"scope"),minChainLength:I(t,"minLength",3),maxChainLength:I(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(`
|
|
866
|
+
\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(`
|
|
867
|
+
${e.length} similar chain pair(s) found.`)}}),Lh=Ye("drift",{query:({db:e,args:t,opts:n,budget:i})=>xn(e,{scope:ge(t,0),minDeviation:I(n,"minDeviation",5),semantic:i.semantic}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),D.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(`
|
|
868
|
+
`)},t=>t.file),console.log(`
|
|
869
|
+
${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)`)}}),wh=Ye("convergence",{query:({db:e,args:t,budget:n})=>dc(e,V(t,0),V(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols not found.",render:e=>{if(e){console.log(`
|
|
855
870
|
${Math.round(e.similarity*100)}% callee overlap
|
|
856
871
|
`),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)
|
|
857
872
|
`),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
|
|
858
873
|
Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
|
|
859
874
|
Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
|
|
860
|
-
Strategy: ${e.consolidationStrategy}`)}}}),
|
|
861
|
-
Signature: ${e.signature} (${e.functions.length} functions)`,n=e.functions.map(
|
|
875
|
+
Strategy: ${e.consolidationStrategy}`)}}}),kh=Nt("similar-signatures",{query:({db:e,opts:t,budget:n})=>hc(e,{scope:P(t,"scope"),minLoc:I(t,"minLoc",3),limit:O(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=`
|
|
876
|
+
Signature: ${e.signature} (${e.functions.length} functions)`,n=e.functions.map(i=>` ${fe(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)`).join(`
|
|
862
877
|
`);return`${t}
|
|
863
878
|
${n}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
|
|
864
|
-
${e.length} group(s) found.`)})
|
|
865
|
-
`);for(let d of
|
|
866
|
-
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}`)}}}),
|
|
867
|
-
`);for(let o of
|
|
868
|
-
${
|
|
869
|
-
`);for(let
|
|
870
|
-
Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),
|
|
879
|
+
${e.length} group(s) found.`)}),Dh=Q("cleanup-plan",({db:e,args:t,opts:n,budget:i})=>{let r=lo(e,{scope:P(n,"scope"),minLoc:I(n,"minLoc",1),maxDepth:I(n,"maxDepth",5),scanLimit:i.scanLimit}),o=ye(),s=R(n,"patch"),a=R(n,"json"),c=R(n,"verify")||s;if(s&&!R(n,"verify")){console.error("error: cleanup-plan --patch requires --verify."),process.exitCode=1;return}if(r.batches.length===0){if(a){$("cleanup-plan",t,n,r);return}return D.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.")}let l=il(r),u=c?el(o,r):void 0;if(a){$("cleanup-plan",t,n,{result:r,verification:u});return}if(s){let d=rl(u,l);if(d.length>0){for(let p of d)console.error(`error: ${p}`);process.exitCode=1;return}let m=yg(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.
|
|
880
|
+
`);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(`
|
|
881
|
+
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}`)}}}),Ih=Q("cleanup-apply",({db:e,opts:t,budget:n})=>{if(!R(t,"verified")){console.error("error: cleanup-apply requires --verified so deletions are checked before mutating files."),process.exitCode=1;return}let i=R(t,"all"),r=Ne(t,"batch");if(i===(r!==void 0)){console.error("error: choose exactly one of --all or --batch <n>."),process.exitCode=1;return}let o=lo(e,{scope:P(t,"scope"),minLoc:I(t,"minLoc",1),maxDepth:I(t,"maxDepth",5),scanLimit:n.scanLimit});if(o.batches.length===0){D.empty("Nothing deletable found \u2014 no graph-fact dead code to seed a cascade.");return}let s=il(o,{all:i,batch:r});if(s.length===0){console.error(`error: No cleanup batch ${r} exists.`),process.exitCode=1;return}let a=ye(),c=el(a,o),l=rl(c,s,{allowDirty:R(t,"forceDirty")});if(l.length>0){for(let m of l)console.error(`error: ${m}`);process.exitCode=1;return}nl(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.`)}),Nh=Q("recent-duplicates",({db:e,args:t,opts:n,budget:i})=>{let r=rc(e,{windowCommits:I(n,"window",100),minSimilarity:Ne(n,"minSimilarity"),limit:O(n,"limit",30),scope:P(n,"scope"),scanLimit:i.scanLimit,semantic:i.semantic});if(R(n,"json")){$("recent-duplicates",t,n,r);return}if(!r.available)return D.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return D.empty(`No recent re-implementations found (window: last ${r.windowCommits} commits).`);console.log(`Recent re-implementations (window: last ${r.windowCommits} commits):
|
|
882
|
+
`);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(`
|
|
883
|
+
${r.findings.length} finding(s). ECHO: prefer extending the established side and deleting the echo.`)}),Eh=z(({db:e,args:t,opts:n})=>{let i=Ka(e,{doc:t[0]===void 0?void 0:V(t,0),limit:O(n,"limit",20),minCoupling:I(n,"minCoupling",3)});if(R(n,"json")){$("doc-drift",t,n,i);return}if(!i.available)return D.empty("No git history available (not a repository, or git missing).");if(i.findings.length===0)return D.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):
|
|
884
|
+
`);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: ${$o(c)}`)}}console.log(`
|
|
885
|
+
Stale standards docs are worse than none \u2014 agents implement to a dead spec.`)}),Ph=Nt("unused-params",{query:({db:e,opts:t,budget:n})=>tr(e,{scope:P(t,"scope"),limit:O(t,"limit",30),scanLimit:n.scanLimit}),format:e=>` ${fe(e.file,e.startLine,e.endLine)} ${e.shortName}
|
|
871
886
|
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(`
|
|
872
|
-
${e.length} function(s) with trailing unused parameters.`)}),Af=[Qe({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",S,30),p("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:v("Cleanup",["scip-query unused-params -s src/services"]),handler:vE}),Qe({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",S,1),p("--max-depth <n>","Maximum cascade depth",S,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:v("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:yE}),Qe({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",S,1),p("--max-depth <n>","Maximum cascade depth",S,5),p("--verified","Required: verify the selected cleanup batch before applying it"),p("--batch <n>","Apply one batch depth",S),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:v("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:SE}),Qe({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"',S,100),p("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",ze),p("-n, --limit <n>","Maximum findings",S,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:v("Cleanup",["scip-query recent-duplicates --window 50"]),handler:xE}),Qe({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",S,20),p("--min-coupling <n>","Minimum historical co-changes to track a subject",S,3),p("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:v("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:CE}),Qe({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",S,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:v("Cleanup",["scip-query dead --min-loc 10"]),handler:Y_}),Qe({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:Z_}),Qe({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",S,3),p("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:eE}),Re({id:"similar",command:"similar [symbol]",description:"Find heuristic function similarity candidates from callee fingerprints",options:_([p("--min-similarity <n>","Minimum Jaccard similarity (0-1)",ze,.4),p("-n, --limit <n>","Number of results",S,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-callees <n>","Minimum callees to consider",S,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:sE}),Re({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)",ze,.5),p("-n, --limit <n>","Number of results",S,20),p("-s, --scope <path>","Limit to files matching path"),p("--min-deps <n>","Minimum dependencies to consider",S),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:aE}),Re({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)",ze,.62),p("--min-tokens <n>","Minimum structural tokens to consider",S,8),p("-n, --limit <n>","Number of results",S,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:cE}),Re({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)",ze,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",S,6),p("-n, --limit <n>","Number of results",S,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:lE}),Re({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",S,300),p("--min-file-lines <n>","Minimum file lines",S,800),p("--min-jsx-tokens <n>","Minimum JSX structure tokens",S,80),p("--min-behavior-tokens <n>","Minimum behavior tokens",S,40),p("-n, --limit <n>","Number of results",S,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:uE}),Re({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)",ze,.62),p("--min-tokens <n>","Minimum structural tokens to consider",S,8),p("-n, --limit <n>","Number of results",S,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:dE}),Re({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)",ze,.45),p("--min-shared-behaviors <n>","Minimum shared behavior tokens",S,6),p("-n, --limit <n>","Number of results",S,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:mE}),Re({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",S,800),p("--min-template-lines <n>","Minimum template lines",S,300),p("--min-script-lines <n>","Minimum script lines",S,300),p("--min-style-lines <n>","Minimum style lines",S,500),p("-n, --limit <n>","Number of results",S,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:pE}),Re({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)",ze,.5),p("-n, --limit <n>","Number of results",S,15),p("-s, --scope <path>","Limit to files matching path"),p("--min-length <n>","Minimum chain length",S,3),p("--max-length <n>","Maximum chain length",S,8),p("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:fE}),Re({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",S,10),p("--min-callees <n>","Minimum callees to analyze",S,6),p("-n, --limit <n>","Number of results",S,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:tE}),Re({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",yo,5),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:gE}),Re({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",S,15),p("-n, --limit <n>","Number of results",S,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:nE}),Re({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",S,15),p("-n, --limit <n>","Number of results",S,30),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:rE}),Re({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",S,3),p("-n, --limit <n>","Number of results",S,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:iE}),Re({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",S,10),p("-n, --limit <n>","Number of results",S,20),p("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:oE}),Qe({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:hE}),Ef({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",S,30),p("--full","Run unbounded analysis on large indexes")],docs:v("Cleanup"),query:({db:e,opts:t})=>Ia(e,{scope:P(t,"scope"),limit:O(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
|
|
873
|
-
barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s)
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
${
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
`),
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
`)
|
|
888
|
-
|
|
889
|
-
${
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
`).
|
|
894
|
-
|
|
895
|
-
`)
|
|
896
|
-
`);for(let o=
|
|
897
|
-
`)
|
|
898
|
-
|
|
899
|
-
\u2550\u2550\u2550
|
|
900
|
-
\u2550\u2550\u2550
|
|
901
|
-
`)
|
|
887
|
+
${e.length} function(s) with trailing unused parameters.`)});function Ze(e){return{docs:L("Cleanup"),...e}}function Ce({heuristicLabel:e,...t}){return Ze({...t,heuristic:{label:e}})}var ts=[Ze({id:"unused-params",command:"unused-params",description:"Speculative-generality candidates: trailing parameters no body ever uses (TS/JS)",options:T([f("-s, --scope <path>","Limit to files matching path"),f("-n, --limit <n>","Maximum findings",x,30),f("--full","Run unbounded analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"unused trailing parameter candidates"},renderShape:"list",docs:L("Cleanup",["scip-query unused-params -s src/services"]),handler:Ph}),Ze({id:"cleanup-plan",command:"cleanup-plan",description:"Ordered, batched deletion plan: graph-fact dead code plus the cascade candidates it unlocks",options:[f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Only include symbols >= N lines",x,1),f("--max-depth <n>","Maximum cascade depth",x,5),f("--verify","Apply batches in a throwaway worktree and run the project checker (tsc / cargo check)"),f("--patch","With --verify, print the compiler-verified deletion patch to stdout"),f("--json","Output as JSON for programmatic consumption"),f("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:L("Cleanup",["scip-query cleanup-plan --min-loc 3","scip-query cleanup-plan --verify"]),handler:Dh}),Ze({id:"cleanup-apply",command:"cleanup-apply",description:"Apply a compiler-verified cleanup-plan batch to the working tree",options:[f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Only include symbols >= N lines",x,1),f("--max-depth <n>","Maximum cascade depth",x,5),f("--verified","Required: verify the selected cleanup batch before applying it"),f("--batch <n>","Apply one batch depth",x),f("--all","Apply every compiler-verified batch in the plan"),f("--force-dirty","Allow applying when plan files already have working-tree edits"),f("--full","Run unbounded analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:L("Cleanup",["scip-query cleanup-apply --verified --batch 0"]),handler:Ih}),Ze({id:"recent-duplicates",command:"recent-duplicates",description:"Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code",options:T([f("--window <n>",'How many commits back counts as "recent"',x,100),f("--min-similarity <n>","Minimum similarity (0-1); omitted uses detector defaults",Xe),f("-n, --limit <n>","Maximum findings",x,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",heuristic:{label:"recent re-implementation candidates"},renderShape:"custom",docs:L("Cleanup",["scip-query recent-duplicates --window 50"]),handler:Nh}),Ze({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:T([f("-n, --limit <n>","Maximum docs to report",x,20),f("--min-coupling <n>","Minimum historical co-changes to track a subject",x,3),f("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"doc drift candidates"},renderShape:"custom",docs:L("Cleanup",["scip-query doc-drift","scip-query doc-drift AGENTS.md"]),handler:Eh}),Ze({id:"dead",command:"dead [scope]",description:"Find dead code and file-internal symbols (no cross-file consumers)",options:T([f("--min-loc <n>","Only show symbols >= N lines",x,1),f("--include-tests","Include test files"),f("--skip-barrels","Ignore refs from barrel re-export files"),f("--include-members","Include class members"),f("--only-dead","Show only [dead code] symbols (skip [file-internal only])"),f("--only-internal","Show only [file-internal only] symbols (skip [dead code])"),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"custom",docs:L("Cleanup",["scip-query dead --min-loc 10"]),handler:sh}),Ze({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:T([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",handler:ah}),Ze({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:T([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum lines of code",x,3),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"grouped-by-file",handler:ch}),Ce({id:"similar",command:"similar [symbol]",description:"Find heuristic function similarity candidates from callee fingerprints",options:T([f("--min-similarity <n>","Minimum Jaccard similarity (0-1)",Xe,.4),f("-n, --limit <n>","Number of results",x,20),f("-s, --scope <path>","Limit to files matching path"),f("--min-callees <n>","Minimum callees to consider",x,4),f("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:gh}),Ce({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:T([f("--min-similarity <n>","Minimum Jaccard similarity (0-1)",Xe,.5),f("-n, --limit <n>","Number of results",x,20),f("-s, --scope <path>","Limit to files matching path"),f("--min-deps <n>","Minimum dependencies to consider",x),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar file candidates",renderShape:"custom",handler:hh}),Ce({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:T([f("--min-similarity <n>","Minimum JSX structure similarity (0-1)",Xe,.62),f("--min-tokens <n>","Minimum structural tokens to consider",x,8),f("-n, --limit <n>","Number of results",x,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:bh}),Ce({id:"react-hook-candidates",command:"react-hook-candidates [file]",description:"Find heuristic React hook extraction candidates from shared state, effects, requests, and handlers",options:T([f("--min-similarity <n>","Minimum behavior similarity (0-1)",Xe,.45),f("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),f("-n, --limit <n>","Number of results",x,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"React hook extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:yh}),Ce({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:T([f("--min-component-lines <n>","Minimum component lines",x,300),f("--min-file-lines <n>","Minimum file lines",x,800),f("--min-jsx-tokens <n>","Minimum JSX structure tokens",x,80),f("--min-behavior-tokens <n>","Minimum behavior tokens",x,40),f("-n, --limit <n>","Number of results",x,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large React component pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:Sh}),Ce({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:T([f("--min-similarity <n>","Minimum template similarity (0-1)",Xe,.62),f("--min-tokens <n>","Minimum structural tokens to consider",x,8),f("-n, --limit <n>","Number of results",x,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue component duplicate candidates",budget:"candidate-scan",renderShape:"custom",handler:xh}),Ce({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:T([f("--min-similarity <n>","Minimum behavior similarity (0-1)",Xe,.45),f("--min-shared-behaviors <n>","Minimum shared behavior tokens",x,6),f("-n, --limit <n>","Number of results",x,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"Vue composable extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:Ch}),Ce({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:T([f("--min-total-lines <n>","Minimum total component lines",x,800),f("--min-template-lines <n>","Minimum template lines",x,300),f("--min-script-lines <n>","Minimum script lines",x,300),f("--min-style-lines <n>","Minimum style lines",x,500),f("--review-thresholds","Use lower review thresholds without changing health scoring"),f("-n, --limit <n>","Number of results",x,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"large Vue view pressure candidates",budget:"candidate-scan",renderShape:"custom",handler:vh}),Ce({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:T([f("--min-similarity <n>","Minimum chain similarity (0-1)",Xe,.5),f("-n, --limit <n>","Number of results",x,15),f("-s, --scope <path>","Limit to files matching path"),f("--min-length <n>","Minimum chain length",x,3),f("--max-length <n>","Maximum chain length",x,8),f("--full","Run unbounded analysis on large indexes")]),heuristicLabel:"similar chain candidates",renderShape:"custom",handler:Rh}),Ce({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:T([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum function LOC",x,10),f("--min-callees <n>","Minimum callees to analyze",x,6),f("-n, --limit <n>","Number of results",x,20),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:lh}),Ce({id:"locality-candidates",command:"locality-candidates [symbol-or-file]",description:"Find directory-locality and ancestry candidates from consumer ownership",options:T([f("-s, --scope <path>","Limit scan mode to files matching path"),f("--min-consumers <n>","Minimum consumers in scan mode",x,1),f("-n, --limit <n>","Number of results",x,20),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"locality candidates",budget:"candidate-scan",renderShape:"custom",docs:L("Cleanup",["scip-query locality-candidates","scip-query locality-candidates formatName --json","scip-query locality-candidates src/shared/date.ts"]),handler:uh}),Ce({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations",options:T([f("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",Bo,5),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:Lh}),Ce({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer",options:T([f("-s, --scope <path>","Limit to files matching path"),f("--max-loc <n>","Maximum LOC for candidates",x,15),f("-n, --limit <n>","Number of results",x,30),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:dh}),Ce({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:T([f("-s, --scope <path>","Limit to files matching path"),f("--max-loc <n>","Maximum LOC for candidates",x,15),f("-n, --limit <n>","Number of results",x,30),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:mh}),Ce({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers",options:T([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum LOC",x,3),f("-n, --limit <n>","Number of results",x,30),f("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:ph}),Ce({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:T([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum LOC",x,10),f("-n, --limit <n>","Number of results",x,20),f("--full","Run unbounded semantic analysis on large indexes")]),heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:fh}),Ze({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Show what a consolidated version of two similar functions would look like",options:T([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",handler:wh}),rh({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[f("-s, --scope <path>","Limit to files matching path"),f("-n, --limit <n>","Number of results",x,30),f("--full","Run unbounded analysis on large indexes")],docs:L("Cleanup"),query:({db:e,opts:t})=>pc(e,{scope:P(t,"scope"),limit:O(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
|
|
888
|
+
barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s) | tier: ${e.actionTier}
|
|
889
|
+
Recommendation: ${e.recommendation}`+(e.surfaceEvidence.length>0?`
|
|
890
|
+
Surface evidence: ${e.surfaceEvidence.join("; ")}`:""),key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
|
|
891
|
+
${e.length} redundant re-export(s).`)}),Ze({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:T([f("-s, --scope <path>","Limit to files matching path"),f("--min-loc <n>","Minimum LOC per function",x,3),f("-n, --limit <n>","Number of groups",x,20),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"list",handler:kh})];var Z$=z(({db:e,args:t,opts:n})=>{let i=Ae(e);if(R(n,"json")){$("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: ${ci(i.indexSizeBytes)}`),i.lastBuilt&&console.log(`Last built: ${i.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),_h=[{id:"stats",command:"stats",description:"Show index statistics",options:[Dc()],renderShape:"custom",docs:L("Core"),handler:Z$}];var eA=Xo("bottlenecks",{headers:["tier","risk","score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>ua(e,{limit:O(t,"limit",20),scope:P(t,"scope"),minFanIn:I(t,"minFanIn",2),minFanOut:I(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."}),tA=z(({db:e,args:t,opts:n})=>{let i=ge(t,0),r=O(n,"limit",30);if(i){let s=ra(e,i);if(R(n,"json")){$("fan-in",t,n,{mode:"symbol",symbol:i,rows:s});return}if(s.length===0)return D.empty(`No fan-in for ${i}.`);D.list(s,a=>` ${String(a.count).padStart(4)} files ${a.name}`);return}let o=sa(e,{limit:r,scope:P(n,"scope")});if(R(n,"json")){$("fan-in",t,n,{mode:"top",rows:o});return}D.table(["files","symbol"],o.map(s=>` ${String(s.count).padStart(5)} ${s.name}`))}),nA=z(({db:e,args:t,opts:n})=>{let i=ge(t,0),r=O(n,"limit",30);if(i){let s=oa(e,i);if(R(n,"json")){$("fan-out",t,n,{mode:"file",file:i,rows:s});return}if(s.length===0)return D.empty(`No fan-out for ${i}.`);D.list(s,a=>` ${String(a.count).padStart(4)} symbols ${a.name}`);return}let o=aa(e,{limit:r,scope:P(n,"scope")});if(R(n,"json")){$("fan-out",t,n,{mode:"top",rows:o});return}D.table(["symbols","file"],o.map(s=>` ${String(s.count).padStart(7)} ${s.name}`))}),iA=z(({db:e,args:t,opts:n})=>{let i=ge(t,0),r=ge(t,1),o=O(n,"limit",20);if(i&&r){let a=ca(e,i,r);if(R(n,"json")){$("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=la(e,{limit:o,scope:P(n,"scope")});if(R(n,"json")){$("coupling",t,n,{mode:"top",rows:s});return}D.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}`))}),rA=Dn({commandName:"cycles",query:({db:e,opts:t})=>cn(e,{scope:P(t,"scope"),maxDepth:I(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(`
|
|
892
|
+
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(`
|
|
893
|
+
${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.)`)}}),oA=Dn({commandName:"deep-chains",query:({db:e,opts:t})=>ga(e,{limit:O(t,"limit",10),scope:P(t,"scope"),minDepth:I(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(`
|
|
894
|
+
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("; ")}`)}}}),Th=[Zo({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[f("-n, --limit <n>","Number of results",x,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")],docs:L("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>Ys(e,{limit:O(t,"limit",30),scope:P(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:T([f("-n, --limit <n>","Number of results for top mode",x,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:L("Graph"),handler:tA},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:T([f("-n, --limit <n>","Number of results for top mode",x,30),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:L("Graph"),handler:nA},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:T([f("-n, --limit <n>","Number of results for top mode",x,20),f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:L("Graph"),handler:iA},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:T([f("-s, --scope <path>","Limit to files matching path"),f("--max-depth <n>","Maximum cycle depth",x,10)]),renderShape:"custom",docs:L("Graph"),handler:rA},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:T([f("-n, --limit <n>","Number of results",x,20),f("-s, --scope <path>","Limit to files matching path"),f("--min-fan-in <n>","Minimum fan-in",x,2),f("--min-fan-out <n>","Minimum fan-out",x,2),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"candidate-scan",renderShape:"table",docs:L("Graph"),handler:eA},{id:"deep-chains",command:"deep-chains",description:"Find the longest transitive dependency chains",options:T([f("-n, --limit <n>","Number of chains to show",x,10),f("-s, --scope <path>","Limit to files matching path"),f("--min-depth <n>","Minimum chain depth",x,3),f("--full","Run unbounded analysis on large indexes")]),renderShape:"custom",docs:L("Graph"),handler:oA},es({id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[f("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:L("Graph"),query:({db:e,args:t,budget:n})=>Bi(e,String(t[0]),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"Symbol not found.",before:e=>{e&&console.log(`Symbol: ${e.shortName}
|
|
895
|
+
`)},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 sA=Q("complexity",({db:e,args:t,opts:n,budget:i})=>{let r=nr(e,V(t,0),{semantic:i.semantic});if(R(n,"json")){$("complexity",t,n,r);return}if(!r)return D.empty("Symbol not found.");console.log(`${fe(r.relativePath,r.startLine,r.endLine)} ${r.shortName}
|
|
896
|
+
`),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}`)}),aA=z(({db:e,args:t,opts:n})=>{let i=gc(e,{samples:I(n,"samples",50),scope:P(n,"scope")});if(R(n,"json")){$("self-audit",t,n,i);return}if(!i.available)return D.empty("No semantic provider available to audit against (TypeScript projects only).");console.log(`Sampled ${i.sampleSize} symbols; oracle answered ${Math.round(i.oracleCoverage*100)}%.
|
|
897
|
+
`),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(`
|
|
898
|
+
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(", ")}`)}}),Fh=[{id:"self-audit",command:"self-audit",description:"Score the cheap evidence paths against the TypeScript compiler oracle on sampled symbols",options:T([f("--samples <n>","Number of symbols to sample",x,50),f("-s, --scope <path>","Limit sampling to files matching path")]),renderShape:"custom",docs:L("Health",["scip-query self-audit --samples 100"]),handler:aA},{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:T([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:L("Health"),handler:sA}];var cA=z(({db:e,args:t,opts:n})=>{let i=zi(e,V(t,0),{maxDepth:I(n,"maxDepth",5),scope:P(n,"scope")});if(R(n,"json")){$("affected",t,n,i);return}if(i.length===0)return D.empty("No affected symbols found.");let r=-1;for(let o of i)o.depth!==r&&(console.log(`
|
|
899
|
+
\u2500\u2500 Depth ${o.depth} \u2500\u2500`),r=o.depth),console.log(` ${o.file} ${o.shortName}`);console.log(`
|
|
900
|
+
${i.length} affected symbol(s) across ${new Set(i.map(o=>o.file)).size} files.`)}),lA=z(({db:e,args:t,opts:n})=>{let i=t[0]===void 0?void 0:V(t,0),r=yn(e,i,{minTogether:I(n,"minTogether",4),limit:O(n,"limit",30),includeLinked:n.all===!0});if(R(n,"json")){$("co-change",t,n,r);return}if(!r.available)return D.empty("No git history available (not a repository, or git missing).");if(r.findings.length===0)return D.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):
|
|
901
|
+
`:`Hidden coupling \u2014 pairs that co-change with no dependency edge (${r.commitsAnalyzed} commits analyzed):
|
|
902
|
+
`);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 ${uA(o.lastTogetherAt)}`),console.log(` subjects: ${dA(o.subjectContext)}`),o.declaredCouplingSuggestion&&console.log(` declare coupling: ${o.declaredCouplingSuggestion.name} (${o.declaredCouplingSuggestion.reason})`)}console.log(`
|
|
903
|
+
${r.findings.length} pair(s). Co-editing one side without the other is how drift starts.`)});function uA(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}function dA(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 mA=Q("change-surface",({db:e,args:t,opts:n,budget:i})=>{let r=Ki(e,V(t,0),{semantic:i.semantic});if(R(n,"json")){$("change-surface",t,n,r);return}if(!r)return D.empty("File not found in index.");console.log(`File: ${r.file}`),console.log(`External consumers: ${r.totalExternalConsumers}
|
|
904
|
+
`),D.list(r.symbols,o=>{let s=o.riskLevel==="high"?" *** HIGH RISK ***":o.riskLevel==="medium"?" * medium risk *":"";return` ${Se(o.startLine,o.endLine)} ${o.shortName} [${o.externalConsumers} consumers]${s}`})}),pA=z(({db:e,args:t,opts:n})=>{let i=er(e,{base:P(n,"base"),minContainment:I(n,"minContainment",.7),maxHelpers:Ne(n,"maxHelpers"),limit:O(n,"limit",20)});if(R(n,"json")){$("incomplete-migration",t,n,i),i.available&&i.findings.length>0&&(process.exitCode=1);return}if(!i.available)return D.empty("No git history available (not a repository, or git missing).");if(i.changedFiles.length===0)return D.empty(`No changes vs ${i.base}.`);console.log(`Incomplete migrations vs ${i.base}: ${i.changedFiles.length} changed file(s), ${i.helpersChecked} new helper(s) scored.`),i.note&&console.log(` note: ${i.note}`);for(let r of i.skipped)console.log(` skipped ${r.helperShortName} (${r.helperFile}): ${r.reason}`);if(i.findings.length===0){console.log(`
|
|
905
|
+
No incomplete migrations detected.`);return}for(let r of i.findings){console.log(`
|
|
906
|
+
${r.helperShortName} (${r.helperFile})`),console.log(` helper shape: ${r.helperShape} (${r.specificHelperCalleeCount}/${r.helperCalleeCount} specific callees)`),console.log(` wired into: ${r.migratedFiles.join(", ")}`);for(let o of r.leftovers)console.log(` un-migrated: ${Math.round(o.containment*100)}% helper / ${Math.round(o.siteCoverage*100)}% site [${o.migrationScope}] ${o.shortName} (${o.file})`),console.log(` scope: ${o.migrationScopeReasons.join("; ")}`),o.uniqueSiteCalleeCount>0&&console.log(` extra site callees: ${o.uniqueSiteCalleeCount}`),console.log(` shared: ${o.sharedCallees.join(", ")}`)}console.log(`
|
|
907
|
+
${i.findings.length} helper(s) with un-migrated sites. Finish the extraction or confirm the sites differ on purpose.`)});function fA(e){let t=Array.isArray(e)?e:[],n=t.filter(i=>!Lo.includes(i));return n.length>0&&(console.error(`error: unknown --skip check(s): ${n.join(", ")}. Valid checks: ${Lo.join(", ")}`),process.exit(1)),t}var gA=z(({db:e,opts:t})=>{let n=t.hook===!0;if(n&&kg(wg()))return;!n&&wc(e)&&Rl(e)===0&&console.error("Large index with a cold evidence cache: this first run computes semantic callee evidence for every production callable and can take minutes. Re-runs are incremental (evidence.db).");let i=ic(e,{base:P(t,"base"),minTogether:I(t,"minTogether",6),maxEchoChecks:Ne(t,"maxEchoChecks"),maxHelpers:Ne(t,"maxHelpers"),skip:fA(t.skip)});if(!n&&R(t,"json")){$("diff-gate",[],t,{exitCode:i.findings.length>0?1:0,...i}),i.findings.length>0&&(process.exitCode=1);return}if(n){if(i.findings.length===0)return;console.error(Dg(i)),process.exitCode=2;return}if(i.changedFiles.length===0)return D.empty(i.note??`No changes vs ${i.base}.`);console.log(`Diff gate vs ${i.base}: ${i.changedFiles.length} file(s), ${i.changedSymbols} symbol(s) changed.`),console.log(`Checks: ${i.checksRun.join(", ")}
|
|
908
|
+
`);for(let o of i.skipped)console.log(` skipped ${o.check}: ${o.reason}`);if(i.findings.length===0){console.log("PASS: this change introduces no gate findings.");return}let r=i.rootCauseGroups?.filter(o=>o.count>1)??[];if(r.length>0){console.log(`Root-cause groups (${r.length}):`);for(let o of r){console.log(` [${o.check}] ${o.count} finding(s), ${o.severity}${o.actionTier?`, tier: ${o.actionTier}`:""}`),(o.sourceAnalyzer||o.rootCauseKey)&&console.log(` source: ${o.sourceAnalyzer??o.check}${o.rootCauseKey?` root cause: ${o.rootCauseKey}`:""}`);let s=[...new Set([...o.files,...o.relatedFiles])].slice(0,6);s.length>0&&console.log(` files: ${s.join(", ")}`),console.log(` -> ${o.remediation}`)}console.log("")}for(let o of i.findings){if(console.log(` [${o.check}] ${o.message}`),o.partnerClass){console.log(` partner class: ${o.partnerClass}`);for(let s of o.partnerClassReasons??[])console.log(` reason: ${s}`)}o.citationKind&&console.log(` citation kind: ${o.citationKind}${o.actionTier?` (tier: ${o.actionTier})`:""}`);for(let s of o.citedClaims?.slice(0,2)??[])console.log(` cited claim: ${$o(s)}`);o.declaredCouplingSuggestion&&console.log(` declare coupling: ${o.declaredCouplingSuggestion.name} (${o.declaredCouplingSuggestion.reason})`),console.log(` -> ${o.remediation}`)}console.log(`
|
|
909
|
+
FAIL: ${i.findings.length} finding(s), ${i.rootCauseGroups?.length??i.findings.length} root-cause group(s). Fix or knowingly accept before merging.`),process.exitCode=1}),$h=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:T([f("--max-depth <n>","Maximum traversal depth",x,5),f("-s, --scope <path>","Limit to files matching path")]),renderShape:"custom",docs:L("Impact"),handler:cA},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:T([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"list",docs:L("Impact"),handler:mA},{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:[f("--base <ref>","Git ref to diff against (default: HEAD)"),f("--min-together <n>","Minimum historical co-changes for the partner check",x,6),f("--max-echo-checks <n>","Maximum changed symbols to test for echoes (default: all)",x),f("--max-helpers <n>","Maximum new helpers to score for incomplete-migration (default: all)",x),f("--skip <check>","Skip a check (repeatable): echo, incomplete-migration, co-change-partner, doc-reference, unused-params, new-dead, baseline",jo,[]),f("--hook","Agent Stop-hook mode: silent on pass, exit 2 with findings on stderr to block the stop"),f("--json","Output as JSON for programmatic consumption")],heuristic:{label:"diff gate candidates"},renderShape:"custom",docs:L("Impact",["scip-query diff-gate","scip-query diff-gate --base origin/main"]),handler:gA},{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:T([f("--base <ref>","Git ref to diff against (default: HEAD)"),f("--min-containment <n>","Minimum share of helper callees a site must contain (0-1)",Xe,.7),f("--max-helpers <n>","Maximum new helpers to score (default: all)",x),f("-n, --limit <n>","Maximum findings to report",x,20),f("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"incomplete migration candidates"},renderShape:"custom",docs:L("Impact",["scip-query incomplete-migration","scip-query incomplete-migration --base origin/main"]),handler:pA},{id:"co-change",command:"co-change [file]",description:"Files that change together in git history without a dependency edge \u2014 hidden coupling candidates",options:T([f("--min-together <n>","Minimum commits where both files changed",x,4),f("-n, --limit <n>","Maximum pairs to report",x,30),f("--all","Include pairs that already have a dependency edge"),f("--full","Run unbounded analysis on large indexes")]),heuristic:{label:"co-change candidates"},renderShape:"custom",docs:L("Impact",["scip-query co-change","scip-query co-change src/runtime/config.ts"]),handler:lA}];function hA(e){let t=[];for(let r of e.definitions){let o=r.signature?` \u2014 ${r.signature}`:"";t.push(` ${fe(r.relativePath,r.startLine,r.endLine)}${o}`),r.source&&t.push(r.source.split(`
|
|
910
|
+
`).map((s,a)=>` ${$e(r.startLine+a)} ${s}`).join(`
|
|
911
|
+
`))}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 ${$e(r.line)} in ${r.enclosingShort}`);return[{title:"DEFINITION",rows:t},{title:"REFERENCED BY",rows:n}]}var bA=z(({db:e,args:t,opts:n})=>{let i=V(t,0),r=R(n,"signatures"),o=na(e,i);if(R(n,"json")){$("outline",t,n,o);return}if(o.length===0)return D.empty(`No symbols found for "${i}".`);function s(a,c){for(let l of a){let u=" ".repeat(c),d=r&&l.signature?` - ${yA(l.signature)}`:"";console.log(`${u}${Se(l.startLine,l.endLine)} ${l.shortName}${d}`),s(l.children,c+1)}}s(o,0)});function yA(e){return e.length>120?`${e.slice(0,117)}...`:e}var SA=Nt("imports",{query:({db:e,args:t,budget:n})=>Zs(e,V(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)."}),xA=Yo("refs",{query:({db:e,args:t,budget:n})=>Gs(e,V(t,0),{semantic:n.semantic}),format:e=>` line ${$e(e.line)}`}),CA=z(({db:e,args:t,opts:n})=>{let i=mc(e,V(t,0),{context:I(n,"context",0)});if(R(n,"json")){$("code",t,n,i);return}if(!i)return D.empty("Symbol not found or file unreadable.");console.log(`${fe(i.relativePath,i.startLine,i.endLine)} ${i.shortName} [${i.language??"unknown"}]
|
|
912
|
+
`);let r=i.source.split(`
|
|
913
|
+
`);for(let o=0;o<r.length;o++)console.log(` ${String($e(i.startLine+o)).padStart(4)} ${r[o]}`)}),vA=Q("dataflow",({db:e,args:t,opts:n,budget:i})=>{let r=ir(e,V(t,0),{semantic:i.semantic});if(R(n,"json")){$("dataflow",t,n,r);return}if(!r)return D.empty("Symbol not found.");if(console.log(`${r.shortName} (${r.relativePath})
|
|
914
|
+
`),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let o of r.definitionSites)console.log(` ${o.file}:${$e(o.line)}`)}if(r.usageSites.length>0){console.log(`
|
|
915
|
+
\u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let o of r.usageSites)console.log(` ${o.file}:${$e(o.line)} in ${o.enclosingShort}`)}if(r.producers.length>0){console.log(`
|
|
916
|
+
\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(`
|
|
917
|
+
\u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let o of r.consumers)console.log(` ${o.file} ${o.shortName}`)}}),RA=Q("slice",({db:e,args:t,opts:n,budget:i})=>{let r=R(n,"forward")?"forward":"backward",o=oi(e,V(t,0),{direction:r,maxDepth:I(n,"depth",3),semantic:i.semantic});if(R(n,"json")){$("slice",t,n,o);return}if(!o)return D.empty("Symbol not found.");if(console.log(`${o.direction} slice of ${o.shortName}
|
|
918
|
+
`),o.connectedSymbols.length===0){console.log(" No connected symbols found.");return}D.list(o.connectedSymbols,s=>` ${s.file} ${s.shortName}
|
|
902
919
|
${s.relationship}`),console.log(`
|
|
903
|
-
${o.connectedSymbols.length} connected symbol(s).`)}),
|
|
904
|
-
${e.length} symbol(s)`)}),
|
|
905
|
-
`).map((o,s)=>` ${String(Ee(r.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(r=>` ${ve(r.startLine,r.endLine)} ${r.shortName}`)),jt(n,t).rows}function KE(e,t){let n=e.trace.referencedBy.map(r=>` ${r.relativePath}:${Ee(r.line)} in ${r.enclosingShort}`);return Rn(jt(n,t))}function QE(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 Rn(jt([...n,...r],t))}function XE(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}:${Ee(o.line)} in ${o.enclosingShort}`);return Rn(jt([...n,...r,...i],t))}function YE(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 Rn(jt(n,t))}function ZE(e,t){let n=[...e.system.files.map(r=>` file ${r}`),...e.system.symbols.map(r=>` export ${ve(r.startLine,r.endLine)} ${r.shortName}`),...e.surface.map(r=>` use ${r.consumer} -> ${r.shortName}`)];return Rn(jt(n,t))}function e0(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 Rn(jt(n,t))}function t0(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` ${ve(r.startLine,r.endLine)} ${r.shortName} [${r.externalConsumers} consumers]${i}`}))),e.complexity&&(n.push(` Complexity: ${ge(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}`)),Rn(jt(n,t))}function n0(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 r0(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 jt(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function Rn(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function xc(e){return e?"yes":"no"}var i0=["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","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"],o0=[$f,Bf,Mf,Af,jf,Vf,Of],Hf=o0.flat(),s0=new Map(Hf.map(e=>[e.id,e]));for(let e of Hf)if(!i0.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);function R(e){let t=s0.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var qf=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[p("-l, --language <lang>","Index only this language (can be repeated)",bo,[]),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",yo)],renderShape:"custom",docs:v("Indexing",["scip-query reindex"]),handler:df},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:v("Indexing"),handler:mf},{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:v("Indexing"),handler:pf},R("stats"),R("files"),R("methods"),R("refs"),R("trace"),R("deps"),R("rdeps"),R("system"),R("surface"),R("dead"),R("hotspots"),R("imports"),R("imported-by"),R("unused-imports"),R("outline"),R("members"),R("fan-in"),R("fan-out"),R("coupling"),R("cycles"),R("bottlenecks"),R("isolated"),R("by-kind"),R("kind-counts"),R("deep-chains"),R("hierarchy"),R("call-graph"),R("similar"),R("similar-files"),R("react-component-duplicates"),R("react-hook-candidates"),R("react-large-component-pressure"),R("vue-component-duplicates"),R("vue-composable-candidates"),R("vue-large-view-pressure"),R("similar-chains"),R("extract-candidates"),R("affected"),R("change-surface"),R("cleanup-plan"),R("cleanup-apply"),R("co-change"),R("recent-duplicates"),R("doc-drift"),R("unused-params"),R("diff-gate"),R("incomplete-migration"),R("plan-context"),{id:ho,command:ho,description:"Internal diff-impact batch worker",hidden:!0,options:[p("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:ff},{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:v("Impact"),handler:gf},R("drift"),R("wrapper-candidates"),R("passthrough-candidates"),R("stale-abstractions"),R("complexity-hotspots"),R("self-audit"),{id:go,command:go,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:hf},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[p("-s, --scope <path>","Limit to files matching path"),p("--full","Run unbounded candidate analyses on large indexes"),p("--json","Output as JSON for programmatic consumption"),p("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),p("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:v("Health",["scip-query health --json","scip-query health --baseline"]),handler:bf},R("convergence"),R("code"),R("complexity"),R("dataflow"),R("slice"),{id:"install-skills",command:"install-skills",description:`Install skills (${Ua.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:v("Maintenance"),handler:yf},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:v("Maintenance"),handler:Sf},{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:v("Maintenance"),handler:xf},{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:v("Maintenance"),handler:Cf},R("redundant-reexports"),R("similar-signatures"),{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:v("Maintenance"),handler:Rf},{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:v("Maintenance",["scip-query config-validate"]),handler:Lf},{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:v("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:If},{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:v("Maintenance"),handler:Df},{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:v("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:wf},{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:v("Maintenance",["scip-query setup-ci"]),handler:Nf},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[p("--debounce <ms>","Ms to wait after last change (default: 30000)",Ma),p("--cooldown <ms>","Min ms between reindexes (default: 60000)",Ma)],renderShape:"custom",docs:v("Maintenance"),handler:Pf},{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:v("Maintenance"),handler:_f}];function Wf(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){a0(o)}}),{descriptor:n,command:r}})}function a0(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${t}`),process.exitCode=1}import{existsSync as c0,mkdirSync as l0,readFileSync as u0,writeFileSync as d0}from"fs";import{homedir as m0}from"os";import{join as Fo}from"path";var p0=1440*60*1e3,Jf="update-check.json",f0="https://registry.npmjs.org/scip-query/latest";async function Gf(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let n=e.cacheDir??b0(t),r=e.now??Date.now(),i=e.currentVersion??fo,o=y0(n),s=o&&r-o.checkedAt<p0?o.latestVersion:await S0(n,e.fetchLatestVersion??C0,r);if(!s||!h0(s,i))return;(e.writeNotice??(c=>console.error(c)))(g0(i,s))}function g0(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
|
|
906
|
-
`)}function
|
|
907
|
-
`)}catch{}}async function
|
|
920
|
+
${o.connectedSymbols.length} connected symbol(s).`)}),Ah=[pt({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:L("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>ss(e,V(t,0)),format:e=>e.relativePath}),pt({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:L("Navigation"),query:({db:e,args:t})=>Ws(e,V(t,0)),format:e=>` ${Se(e.startLine,e.endLine)} ${e.name}`}),{id:"refs",command:"refs <symbol>",description:"Find all files referencing a symbol",options:[f("--full","Run unbounded semantic analysis on large indexes"),f("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"grouped-by-file",docs:L("Navigation",["scip-query refs login"]),handler:xA},es({id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[f("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",docs:L("Navigation",["scip-query trace parseSymbol"]),query:({db:e,args:t,budget:n})=>Fi(e,V(t,0),{semantic:n.semantic}),sections:hA}),pt({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:L("Navigation"),query:({db:e,args:t})=>$i(e,V(t,0)),format:e=>e.relativePath}),pt({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:L("Navigation"),query:({db:e,args:t})=>Ai(e,V(t,0)),format:e=>e.relativePath}),oh({id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",docs:L("Navigation",["scip-query system queries"]),query:({db:e,args:t})=>Mi(e,V(t,0)),sections:e=>[{title:"FILES",rows:e.files},{title:"EXPORTED SYMBOLS",rows:e.symbols.map(t=>` ${Se(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:L("Navigation"),query:({db:e,args:t})=>Oi(e,V(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[f("--full","Run unbounded semantic analysis on large indexes"),f("--json","Output as JSON for programmatic consumption")],budget:"semantic",renderShape:"list",docs:L("Navigation"),handler:SA},pt({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:L("Navigation"),query:({db:e,args:t})=>ea(e,V(t,0)),format:e=>` ${e.fromFile}`}),{id:"outline",command:"outline <file>",description:"Tree view of symbols in a file, with line ranges",options:T([f("--signatures","Show trimmed symbol signatures")]),renderShape:"custom",docs:L("Navigation"),handler:bA},pt({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:L("Navigation"),query:({db:e,args:t})=>ia(e,V(t,0)),format:e=>` ${Se(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:[f("-s, --scope <path>","Limit to files matching path"),f("-n, --limit <n>","Number of results",x,100),f("--full","Run unbounded analysis on large indexes")],docs:L("Navigation"),query:({db:e,args:t,opts:n})=>pa(e,V(t,0),{scope:P(n,"scope"),limit:O(n,"limit",100)}),format:e=>` ${fe(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${V(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
|
|
921
|
+
${e.length} symbol(s)`)}),Zo({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[f("-s, --scope <path>","Limit to files matching path")],docs:L("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>fa(e,{scope:P(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:L("Navigation"),query:({db:e,args:t})=>ha(e,V(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:T([f("-C, --context <n>","Extra lines of context above/below",x,0)]),renderShape:"custom",docs:L("Navigation"),handler:CA},{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:T([f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:L("Navigation"),handler:vA},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:T([f("--forward","Forward slice (what does this affect). Default is backward."),f("--depth <n>","Max transitive depth for backward slice",x,3),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:L("Navigation"),handler:RA}];var LA=Q("plan-context",({db:e,args:t,opts:n,budget:i})=>{let r=O(n,"limit",20),o=oc(e,V(t,0),{semantic:i.semantic,impactDepth:I(n,"impactDepth",3),sliceDepth:I(n,"sliceDepth",3),scope:P(n,"scope")});if(o.warnings.length===1&&o.warnings[0]==="No symbol, file, or module matched target."){if(R(n,"json")){$("plan-context",t,n,o);return}return D.empty(o.warnings[0])}if(R(n,"json")){$("plan-context",t,n,o);return}let s=[{title:"TARGET",rows:wA(o)},{title:"DEFINITIONS",rows:kA(o,r),skipIfEmpty:!0},{title:"REFERENCES",rows:DA(o,r),skipIfEmpty:!0},{title:"CALL GRAPH",rows:IA(o,r),skipIfEmpty:!0},{title:"DATAFLOW",rows:NA(o,r),skipIfEmpty:!0},{title:"DEPENDENCIES",rows:EA(o,r),skipIfEmpty:!0},{title:"SURFACE",rows:PA(o,r),skipIfEmpty:!0},{title:"DOWNSTREAM IMPACT",rows:_A(o,r),skipIfEmpty:!0},{title:"CHANGE RISK",rows:TA(o,r),skipIfEmpty:!0},{title:"HISTORY",rows:FA(o),skipIfEmpty:!0},{title:"PLANNING NOTES",rows:$A(o),skipIfEmpty:!0}];D.sectionedReport(s)}),Mh=[{id:"plan-context",command:"plan-context <target>",description:"Pre-edit planning context for a symbol, file, or module",options:T([f("--impact-depth <n>","Maximum affected traversal depth",x,3),f("--slice-depth <n>","Maximum backward slice depth",x,3),f("-s, --scope <path>","Limit downstream impact to files matching path"),f("-n, --limit <n>","Rows per section",x,20),f("--full","Run unbounded semantic analysis on large indexes")]),budget:"semantic",renderShape:"custom",docs:L("Planning",["scip-query plan-context parseSymbol"]),handler:LA}];function wA(e){return[`Target: ${e.target}`,`Matched: symbol=${dl(e.matched.symbol)} file=${dl(e.matched.file)} module=${dl(e.matched.module)}`]}function kA(e,t){let n=[];for(let i of e.trace.definitions){let r=i.signature?` -- ${i.signature}`:"";n.push(` ${fe(i.relativePath,i.startLine,i.endLine)}${r}`),i.source&&n.push(...i.source.split(`
|
|
922
|
+
`).map((o,s)=>` ${String($e(i.startLine+s)).padStart(4)} ${o}`))}return n.length===0&&n.push(...e.system.symbols.map(i=>` ${Se(i.startLine,i.endLine)} ${i.shortName}`)),qt(n,t).rows}function DA(e,t){let n=e.trace.referencedBy.map(i=>` ${i.relativePath}:${$e(i.line)} in ${i.enclosingShort}`);return In(qt(n,t))}function IA(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 In(qt([...n,...i],t))}function NA(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}:${$e(o.line)} in ${o.enclosingShort}`);return In(qt([...n,...i,...r],t))}function EA(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 In(qt(n,t))}function PA(e,t){let n=[...e.system.files.map(i=>` file ${i}`),...e.system.symbols.map(i=>` export ${Se(i.startLine,i.endLine)} ${i.shortName}`),...e.surface.map(i=>` use ${i.consumer} -> ${i.shortName}`)];return In(qt(n,t))}function _A(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 In(qt(n,t))}function TA(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` ${Se(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${r}`}))),e.complexity&&(n.push(` Complexity: ${fe(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}`)),In(qt(n,t))}function FA(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 $A(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 qt(e,t){let n=Math.max(1,t);return{rows:e.slice(0,n),omitted:Math.max(0,e.length-n)}}function In(e){return e.omitted>0?[...e.rows,` ... ${e.omitted} more`]:e.rows}function dl(e){return e?"yes":"no"}var AA=["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"],MA=[_h,Ah,Th,ts,$h,Mh,Fh],Oh=MA.flat(),OA=new Map(Oh.map(e=>[e.id,e]));for(let e of Oh)if(!AA.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);function k(e){let t=OA.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var jh=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[f("-l, --language <lang>","Index only this language (can be repeated)",jo,[]),f("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),f("--force","Rebuild even if source inputs are unchanged"),f("--allow-partial","Write an incomplete index when one or more detected languages fail"),f("--indexer-concurrency <n>","Number of language indexers to run at once",Bo)],renderShape:"custom",docs:L("Indexing",["scip-query reindex"]),handler:Mg},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:L("Indexing"),handler:Og},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[f("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:L("Indexing"),handler:jg},k("stats"),k("files"),k("methods"),k("refs"),k("trace"),k("deps"),k("rdeps"),k("system"),k("surface"),k("dead"),k("hotspots"),k("imports"),k("imported-by"),k("unused-imports"),k("outline"),k("members"),k("fan-in"),k("fan-out"),k("coupling"),k("cycles"),k("bottlenecks"),k("isolated"),k("by-kind"),k("kind-counts"),k("deep-chains"),k("hierarchy"),k("call-graph"),k("similar"),k("similar-files"),k("react-component-duplicates"),k("react-hook-candidates"),k("react-large-component-pressure"),k("vue-component-duplicates"),k("vue-composable-candidates"),k("vue-large-view-pressure"),k("similar-chains"),k("extract-candidates"),k("locality-candidates"),k("affected"),k("change-surface"),k("cleanup-plan"),k("cleanup-apply"),k("co-change"),k("recent-duplicates"),k("doc-drift"),k("unused-params"),k("diff-gate"),k("incomplete-migration"),k("plan-context"),{id:Oo,command:Oo,description:"Internal diff-impact batch worker",hidden:!0,options:[f("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:Bg},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:[f("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",docs:L("Impact"),handler:Hg},k("drift"),k("wrapper-candidates"),k("passthrough-candidates"),k("stale-abstractions"),k("complexity-hotspots"),k("self-audit"),{id:Mo,command:Mo,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[f("-s, --scope <path>","Limit to files matching path"),f("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:Vg},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[f("-s, --scope <path>","Limit to files matching path"),f("--full","Compatibility flag; health already runs unbounded candidate analyses by default"),f("--json","Output as JSON for programmatic consumption"),f("--baseline","Compare findings against the committed baseline; exit 1 on new findings"),f("--write-baseline","Snapshot current finding identities to the baseline file")],renderShape:"custom",docs:L("Health",["scip-query health --json","scip-query health --baseline"]),handler:qg},k("convergence"),k("code"),k("complexity"),k("dataflow"),k("slice"),{id:"install-skills",command:"install-skills",description:`Install skills (${Fc.join(", ")}) into Claude Code, Codex, and shared agent roots`,renderShape:"custom",docs:L("Maintenance"),handler:Ug},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:L("Maintenance"),handler:Wg},{id:"capabilities",command:"capabilities",description:"Report which evidence and verification capabilities are available in this project",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:L("Maintenance"),handler:Gg},{id:"capability-matrix",command:"capability-matrix",description:"Report the evidence and verification capability matrix by language",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:L("Maintenance"),handler:zg},k("redundant-reexports"),k("similar-signatures"),{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:L("Maintenance"),handler:Jg},{id:"config-validate",command:"config-validate",description:"Validate .scipquery.json, including structured suppressions and declared coupling groups",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:L("Maintenance",["scip-query config-validate"]),handler:Qg},{id:"suppress",command:"suppress <id>",description:"Record an accepted finding in .scipquery.json with a required reason",options:T([f("--reason <text>","Required human reason for accepting the finding"),f("--check <check>","Optional detector/check name to narrow the suppression"),f("--file <path>","Optional file path to narrow the suppression"),f("--expires-at <iso>","Optional ISO date after which the suppression expires")]),renderShape:"custom",docs:L("Maintenance",['scip-query suppress SQABC123DEF456 --reason "intentional boundary"']),handler:Xg},{id:"doctor",command:"doctor",description:"Diagnose config, index freshness, dependency readiness, and project capabilities",options:[f("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:L("Maintenance"),handler:Yg},{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:[f("--git-hook","Also install a git pre-commit hook that runs diff-gate")],renderShape:"custom",docs:L("Maintenance",["scip-query setup-agent","scip-query setup-agent --git-hook"]),handler:eh},{id:"setup-ci",command:"setup-ci",description:"Write a GitHub Actions workflow that runs scip-query reindex and diff-gate on pull requests",options:[f("--force","Overwrite an existing workflow"),f("--dry-run","Print the workflow without writing it")],renderShape:"custom",docs:L("Maintenance",["scip-query setup-ci"]),handler:th},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[f("--debounce <ms>","Ms to wait after last change (default: 30000)",kc),f("--cooldown <ms>","Min ms between reindexes (default: 60000)",kc)],renderShape:"custom",docs:L("Maintenance"),handler:nh},{id:"status",command:"status",description:"Show index status for this project",options:[f("--json","Output as JSON for programmatic consumption"),f("--capabilities","Include the project capability matrix")],renderShape:"custom",docs:L("Maintenance"),handler:ih}];function Bh(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){jA(o)}}),{descriptor:n,command:i}})}function jA(e){let t=e instanceof Error?e.message:String(e);console.error(`error: ${t}`),process.exitCode=1}import{existsSync as BA,mkdirSync as HA,readFileSync as VA,writeFileSync as qA}from"fs";import{homedir as UA}from"os";import{join as ns}from"path";var WA=1440*60*1e3,Vh="update-check.json",GA="https://registry.npmjs.org/scip-query/latest";async function qh(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let n=e.cacheDir??JA(t),i=e.now??Date.now(),r=e.currentVersion??Ao,o=QA(n),s=o&&i-o.checkedAt<WA?o.latestVersion:await XA(n,e.fetchLatestVersion??ZA,i);if(!s||!KA(s,r))return;(e.writeNotice??(c=>console.error(c)))(zA(r,s))}function zA(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
|
|
923
|
+
`)}function KA(e,t){let n=Hh(e),i=Hh(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 JA(e){let t=e.XDG_CACHE_HOME||ns(UA(),".cache");return ns(t,"scip-query")}function QA(e){let t=ns(e,Vh);if(!BA(t))return null;try{let n=JSON.parse(VA(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 XA(e,t,n){let i;try{i=await t()}catch{i=null}return YA(e,{checkedAt:n,latestVersion:i}),i}function YA(e,t){try{HA(e,{recursive:!0}),qA(ns(e,Vh),`${JSON.stringify(t,null,2)}
|
|
924
|
+
`)}catch{}}async function ZA(){let e=await fetch(GA,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function Hh(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}is.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(Ao);Bh(is,jh);is.hook("preAction",async()=>{await qh()});tM()&&await is.parseAsync();function tM(){if(!process.argv[1])return!1;let e=eM(import.meta.url);try{return Uh(e)===Uh(process.argv[1])}catch{return e===process.argv[1]}}export{is as program,li as renderHeuristicNotice};
|
|
908
925
|
//# sourceMappingURL=cli.js.map
|