scip-query 0.19.1 → 0.19.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/CHANGELOG.md +25 -0
- package/README.md +17 -1
- package/dist/{chunk-ESNRT7QN.js → chunk-26JI77AY.js} +108 -108
- package/dist/{chunk-XZXUMGAA.js → chunk-2E7QY4B5.js} +2 -2
- package/dist/{chunk-JBZXJXIS.js → chunk-2ROSOG2I.js} +2 -2
- package/dist/{chunk-NTOBQK5H.js → chunk-33RLKB6L.js} +2 -2
- package/dist/{chunk-XCPE3G75.js → chunk-4BUMNEYQ.js} +2 -2
- package/dist/{chunk-HCS5LB6U.js → chunk-5FUAFNMP.js} +2 -2
- package/dist/chunk-5GCAM4JE.js +122 -0
- package/dist/{chunk-SSXEYWN3.js → chunk-5OR4QRPR.js} +2 -2
- package/dist/{chunk-CKFMZE77.js → chunk-5TZ2MQBG.js} +2 -2
- package/dist/{chunk-Q2WEWIKX.js → chunk-6EWBPAA3.js} +2 -2
- package/dist/{chunk-4BU54UJG.js → chunk-6FIA5BEB.js} +2 -2
- package/dist/{chunk-DFQNE73Y.js → chunk-77IOFJVY.js} +2 -2
- package/dist/{chunk-WCZAABYF.js → chunk-AD7WUFFT.js} +2 -2
- package/dist/{chunk-V7J4A3AH.js → chunk-AFVU2GB2.js} +2 -2
- package/dist/{chunk-ZNK6K3LB.js → chunk-B26UX7ZD.js} +2 -2
- package/dist/{chunk-SYGAA54M.js → chunk-C3VQZFP2.js} +2 -2
- package/dist/{chunk-B2WQKQKP.js → chunk-EGKWRX5I.js} +2 -2
- package/dist/{chunk-3WLRW5TC.js → chunk-EHU4TZJJ.js} +2 -2
- package/dist/{chunk-KMUFGAIK.js → chunk-EII5ZHL2.js} +2 -2
- package/dist/{chunk-BBBKPOIT.js → chunk-EYF5HOUZ.js} +2 -2
- package/dist/{chunk-PYMZU5EG.js → chunk-FYE4PWWP.js} +2 -2
- package/dist/{chunk-V5WBVF6K.js → chunk-HAC5EI2T.js} +2 -2
- package/dist/{chunk-5W2VAEVR.js → chunk-HCSTQGQE.js} +2 -2
- package/dist/{chunk-JJZRS2OP.js → chunk-HHOJH3RJ.js} +2 -2
- package/dist/{chunk-6PKO2TNZ.js → chunk-HNTLCR4F.js} +2 -2
- package/dist/{chunk-BMTBVMA3.js → chunk-IICQP2DY.js} +2 -2
- package/dist/{chunk-OOUJBAKJ.js → chunk-IXAALOUP.js} +2 -2
- package/dist/{chunk-LF5CIKWZ.js → chunk-JFO2UVQP.js} +2 -2
- package/dist/{chunk-5TEUKVSM.js → chunk-JRCJEHRG.js} +2 -2
- package/dist/{chunk-FHLYJVXF.js → chunk-LSJDKJIB.js} +2 -2
- package/dist/{chunk-RPEA7P5Z.js → chunk-MRYPDVOS.js} +2 -2
- package/dist/{chunk-E3KWOHH7.js → chunk-NLNZK7RL.js} +5 -5
- package/dist/{chunk-7TJJY2C3.js → chunk-OAM22BCR.js} +2 -2
- package/dist/{chunk-LQUDSHLB.js → chunk-PCIFZHWS.js} +2 -2
- package/dist/{chunk-WFRET75Z.js → chunk-PJENL245.js} +2 -2
- package/dist/{chunk-EMIIOOTM.js → chunk-PLDIXTKR.js} +2 -2
- package/dist/{chunk-YCSTKIYU.js → chunk-PTYQQHZM.js} +2 -2
- package/dist/{chunk-BCMOTIB6.js → chunk-QKW7ISEW.js} +2 -2
- package/dist/{chunk-63P42UR6.js → chunk-QNO3QIMN.js} +2 -2
- package/dist/{chunk-6O5JOS7T.js → chunk-SOS256TP.js} +2 -2
- package/dist/{chunk-QHKXGMOI.js → chunk-TDUU63FC.js} +2 -2
- package/dist/chunk-TOIS2VAI.js +4 -0
- package/dist/chunk-V27BEQJN.js +7 -0
- package/dist/{chunk-KC2IFAAU.js → chunk-WFWQWQK6.js} +2 -2
- package/dist/{chunk-US44MEVU.js → chunk-XAMVIPE2.js} +2 -2
- package/dist/{chunk-DCDOGW32.js → chunk-XWE7PZQH.js} +2 -2
- package/dist/{chunk-GIHVWNKQ.js → chunk-XWJ3JYRG.js} +2 -2
- package/dist/{chunk-AGTATREV.js → chunk-XYNWAZ6J.js} +2 -2
- package/dist/{chunk-DZXFZAZO.js → chunk-YGBHQOB2.js} +2 -2
- package/dist/{chunk-7SGOWD2Y.js → chunk-Z7M7X3ZG.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{command-descriptors-3EJHQLQZ.js → command-descriptors-QJEYYND2.js} +168 -166
- package/dist/direct-navigation-TT23TDBS.js +3 -0
- package/dist/index.js +1 -1
- package/dist/queries/affected.js +1 -1
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/drift.js +1 -1
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/health.js +1 -1
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/surface.js +1 -1
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +24 -24
- package/dist/reindex.js +38 -38
- package/dist/runtime.d.ts +6 -1
- package/dist/runtime.js +2 -2
- package/dist/watch-server.js +5 -5
- package/package.json +1 -1
- package/dist/chunk-2NA6TYP4.js +0 -120
- package/dist/chunk-DRH3AD7W.js +0 -4
- package/dist/chunk-IOOCKVUA.js +0 -6
- package/dist/direct-navigation-C2A44KFT.js +0 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createHash as Wv}from"crypto";import{existsSync as Gv,mkdirSync as zv,readFileSync as Vv}from"fs";import{dirname as Rc,join as Vm}from"path";import vc from"better-sqlite3";var Gm=[];function
|
|
2
|
+
import{createHash as Wv}from"crypto";import{existsSync as Gv,mkdirSync as zv,readFileSync as Vv}from"fs";import{dirname as Rc,join as Vm}from"path";import vc from"better-sqlite3";var Gm=[];function dn(e){e.groups.length>0&&Gm.push(e)}function xc(e,t){let n=new Set(t.groups);for(let r of Gm)r.groups.some(i=>n.has(i))&&(t.file!==void 0&&r.clearFile?r.clearFile(e,t.file):r.clearAll(e))}function zm(){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 j(e,t){let{cache:n,ensure:r}=zm(),i={get(o,s,a){let c=r(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 dn({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}function J(e,t){let n=new WeakMap,r={get(i,o){let s=n.get(i);if(s)return s.value;let a=o();return n.set(i,{value:a}),a},invalidate(i){n.delete(i)},has(i){return n.has(i)}};return dn({name:e,groups:t.clearGroups,clearAll:i=>r.invalidate(i)}),r}var Uv={clearGroups:["whole-project","source-file"]};function mn(e){return An(e,Uv)}function An(e,t){let{cache:n,ensure:r}=zm(),i={get(o,s,a,c){let l=r(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 dn({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}var qv="evidence.db";var Kv=["source-facts","definition-exclusions","doc-path-tokens","react-component-behavior-profiles"],Ic=new Set(Kv),Jv=25e4,Yv=512*1024*1024,Xv=5e3,Oo=new WeakMap,Qv=j("evidence-content-hash",{clearGroups:["whole-project","source-file"]}),Zv=j("evidence-project-fingerprint",{clearGroups:["whole-project"]}),nt="evidence-v1",mr="version NOT LIKE 'evidence-%'";function he(e){return Wv("sha256").update(e).digest("hex")}function ce(e,t,n){return Qv.get(e,t,()=>he(n))}function Te(e){return Zv.get(e,"current",()=>{try{let t=JSON.parse(Vv(Vm(Rc(e.config.dbPath),"meta.json"),"utf-8"));if(t.version!==2&&t.version!==3||t.status!=="complete"&&t.status!=="partial"||t.fingerprint===void 0)return null;let n=Array.isArray(t.indexedLanguages)?[...t.indexedLanguages].sort():[];return he(JSON.stringify({fingerprint:t.fingerprint,indexedLanguages:n,status:t.status}))}catch(t){return fr("project fingerprint unavailable",t),null}})}function fr(e,t){process.env.SCIP_QUERY_DEBUG&&console.error(`evidence-cache: ${e}: ${t instanceof Error?t.message:String(t)}`)}function ht(e){if(Oo.has(e))return Oo.get(e)??null;let t=null;try{let n=new vc(Vm(Rc(e.config.dbPath),qv));n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),n.pragma("synchronous = NORMAL"),n.exec(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS file_evidence (
|
|
4
4
|
kind TEXT NOT NULL,
|
|
5
5
|
relative_path TEXT NOT NULL,
|
|
@@ -65,7 +65,7 @@ import{createHash as Wv}from"crypto";import{existsSync as Gv,mkdirSync as zv,rea
|
|
|
65
65
|
WHERE relative_path = ? AND project_fingerprint = ? AND ${mr}
|
|
66
66
|
ORDER BY symbol, version DESC`),writeReferences:n.prepare(`INSERT OR REPLACE INTO semantic_references
|
|
67
67
|
(relative_path, symbol, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)`),dropStaleReferences:n.prepare("DELETE FROM semantic_references WHERE relative_path = ? AND project_fingerprint != ?"),readFindingOutcomeLedger:n.prepare("SELECT check_name, finding_id, first_seen, last_seen, times_shown, outcome FROM finding_outcome_ledger"),deleteFindingOutcomeLedgerForCheck:n.prepare("DELETE FROM finding_outcome_ledger WHERE check_name = ?"),writeFindingOutcomeLedgerRow:n.prepare(`INSERT INTO finding_outcome_ledger
|
|
68
|
-
(check_name, finding_id, first_seen, last_seen, times_shown, outcome) VALUES (?, ?, ?, ?, ?, ?)`)}}catch(n){fr("disabled (open failed)",n)}return Oo.set(e,t),t}function
|
|
68
|
+
(check_name, finding_id, first_seen, last_seen, times_shown, outcome) VALUES (?, ?, ?, ?, ?, ?)`)}}catch(n){fr("disabled (open failed)",n)}return Oo.set(e,t),t}function yt(e,t,n){fr(`disabled (${t})`,n),Oo.set(e,null)}function eI(e){if(!e)return null;try{zv(Rc(e),{recursive:!0});let t=new vc(e);return t.pragma("journal_mode = WAL"),t.pragma("busy_timeout = 250"),t.pragma("synchronous = NORMAL"),t.exec(`
|
|
69
69
|
CREATE TABLE IF NOT EXISTS file_evidence (
|
|
70
70
|
kind TEXT NOT NULL,
|
|
71
71
|
relative_path TEXT NOT NULL,
|
|
@@ -78,39 +78,39 @@ import{createHash as Wv}from"crypto";import{existsSync as Gv,mkdirSync as zv,rea
|
|
|
78
78
|
`),{evidence:t,readFileEvidence:t.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),writeFileEvidence:t.prepare(`INSERT INTO file_evidence (kind, relative_path, content_hash, version, payload, last_accessed_at)
|
|
79
79
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
80
80
|
ON CONFLICT(kind, relative_path, content_hash, version)
|
|
81
|
-
DO UPDATE SET payload = excluded.payload, last_accessed_at = excluded.last_accessed_at`)}}catch(t){return fr("shared cache disabled (open failed)",t),null}}function wc(e,t,n){fr(`shared cache disabled (${t})`,n);try{e.shared?.evidence.close()}catch{}e.shared=null}function
|
|
81
|
+
DO UPDATE SET payload = excluded.payload, last_accessed_at = excluded.last_accessed_at`)}}catch(t){return fr("shared cache disabled (open failed)",t),null}}function wc(e,t,n){fr(`shared cache disabled (${t})`,n);try{e.shared?.evidence.close()}catch{}e.shared=null}function BY(e,t={}){if(!Gv(e))return null;let n;try{n=new vc(e),n.pragma("busy_timeout = 50"),n.pragma("wal_checkpoint(TRUNCATE)");let r=n.prepare("SELECT COUNT(*) AS count FROM file_evidence").get().count,i=t.maxRows??Jv,o=t.budgetBytes??Yv,s=Number(n.pragma("page_size",{simple:!0})),a=Number(n.pragma("page_count",{simple:!0})),c=Number(n.pragma("freelist_count",{simple:!0})),l=Math.max(0,a-c)*s,u=r>0&&l>o?Math.min(r,Math.ceil((l-o)/Math.max(1,l/r))):0,d=Math.max(r-i,u);return d>0&&(n.prepare(`DELETE FROM file_evidence WHERE rowid IN (
|
|
82
82
|
SELECT rowid FROM file_evidence ORDER BY last_accessed_at ASC, rowid ASC LIMIT ?
|
|
83
|
-
)`).run(d),n.pragma("wal_checkpoint(TRUNCATE)")),{deletedRows:d,remainingRows:r-d}}catch(r){return fr("shared cache maintenance skipped",r),null}finally{try{n?.close()}catch{}}}function qm(e,t,n,r){let i=
|
|
83
|
+
)`).run(d),n.pragma("wal_checkpoint(TRUNCATE)")),{deletedRows:d,remainingRows:r-d}}catch(r){return fr("shared cache maintenance skipped",r),null}finally{try{n?.close()}catch{}}}function qm(e,t,n,r){let i=ht(e);if(!i)return null;try{let o=i.readFileEvidence.get(t,n,r,nt)??i.readLegacyFileEvidence.get(t,n,r);if(o?.payload!==void 0)return o.payload;if(!Ic.has(t)||!i.shared)return null;try{return i.shared.readFileEvidence.get(t,n,r,nt)?.payload??null}catch(s){return wc(i,"file_evidence read",s),null}}catch(o){return yt(e,"file_evidence read",o),null}}function Km(e,t,n,r,i){let o=ht(e);if(o)try{if(o.writeFileEvidence.run(t,n,r,nt,i),Ic.has(t)&&o.shared)try{o.shared.writeFileEvidence.run(t,n,r,nt,i,Date.now())}catch(s){wc(o,"file_evidence write",s)}}catch(s){yt(e,"file_evidence write",s)}}function Jm(e,t){if(t.length===0)return;let n=ht(e);if(n)try{n.evidence.transaction(()=>{for(let i of t)n.writeFileEvidence.run(i.kind,i.relativePath,i.contentHash,nt,i.payload)})();let r=t.filter(i=>Ic.has(i.kind));if(r.length>0&&n.shared)try{n.shared.evidence.transaction(()=>{for(let i of r)n.shared.writeFileEvidence.run(i.kind,i.relativePath,i.contentHash,nt,i.payload,Date.now())})()}catch(i){wc(n,"file_evidence batch write",i)}}catch(r){yt(e,"file_evidence batch write",r)}}function Ym(e,t,n,r){let i=ht(e);if(!i)return null;try{return(i.readProjectEvidence.get(t,n,r,nt)??i.readLegacyProjectEvidence.get(t,n,r))?.payload??null}catch(o){return yt(e,"project_evidence read",o),null}}function Xm(e,t,n,r,i){let o=ht(e);if(o)try{o.writeProjectEvidence.run(t,n,r,nt,i)}catch(s){yt(e,"project_evidence write",s)}}function Qm(e,t,n,r){let i=ht(e);if(!i)return new Map;try{let o=i.readCalleesForFile.all(t,n,r,nt),s=i.readLegacyCalleesForFile.all(t,n,r);return ef([...s,...o])}catch(o){return yt(e,"semantic_callees bulk read",o),new Map}}function Zm(e,t,n){let r=ht(e);if(!r)return new Map;try{let i=r.readReferencesForFile.all(t,n,nt),o=r.readLegacyReferencesForFile.all(t,n);return ef([...o,...i])}catch(i){return yt(e,"semantic_references bulk read",i),new Map}}function ef(e){let t=new Map;for(let n of e)t.set(n.symbol,n.payload);return t}function Dc(e,t){if(t.length===0)return;let n=ht(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,nt,i.payload)}})()}catch(r){yt(e,"semantic_callees write",r)}}function tf(e,t){if(t.length===0)return;let n=ht(e);if(n)try{n.evidence.transaction(()=>{let r=new Set;for(let i of t){let o=`${i.relativePath}\0${i.projectFingerprint}`;r.has(o)||(r.add(o),n.dropStaleReferences.run(i.relativePath,i.projectFingerprint)),n.writeReferences.run(i.relativePath,i.symbol,i.projectFingerprint,nt,i.payload)}})()}catch(r){yt(e,"semantic_references write",r)}}function nf(e){let t=ht(e);if(!t)return[];try{return t.readFindingOutcomeLedger.all().map(r=>({check:r.check_name,findingId:r.finding_id,firstSeen:r.first_seen,lastSeen:r.last_seen,timesShown:r.times_shown,outcome:r.outcome}))}catch(n){return yt(e,"finding_outcome_ledger read",n),[]}}function rf(e,t){let n=ht(e);if(n)try{let r=new Map;for(let i of t){let o=r.get(i.check)??[];o.push(i),r.set(i.check,o)}n.evidence.transaction(()=>{for(let[i,o]of r){n.deleteFindingOutcomeLedgerForCheck.run(i);let s=[...o].sort((a,c)=>c.lastSeen-a.lastSeen).slice(0,Xv);for(let a of s)n.writeFindingOutcomeLedgerRow.run(a.check,a.findingId,a.firstSeen,a.lastSeen,a.timesShown,a.outcome)}})()}catch(r){yt(e,"finding_outcome_ledger write",r)}}import{appendFileSync as tI,mkdirSync as nI}from"fs";import{createHash as rI,randomUUID as iI}from"crypto";import{dirname as oI}from"path";import{performance as pr}from"perf_hooks";var cf="SCIP_QUERY_PROFILE",lf="SCIP_QUERY_PROFILE_OUT",uf="SCIP_QUERY_PROFILE_COMMAND",df="SCIP_QUERY_PROFILE_CACHE_STATE",Ec="SCIP_QUERY_PROFILE_RUN_ID",kc="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY",Pc="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND",mf=[cf,lf,uf,df,Ec,kc,Pc],zY=new Set(mf),of=new Set,sf=new Map,af=!1;function U(){let e=process.env[cf];return e==="1"||e==="true"}function sI(){return process.env[lf]}function ff(){return process.env[uf]}function aI(){return process.env[df]}function pf(){let e=process.env[Ec];if(e)return e;if(!U())return;let t=iI();return process.env[Ec]=t,t}function gf(){return process.env[kc]}function cI(e){let t=gf();if(t)return t;if(!U())return;let n=pf();if(!n)return;let r=e.projectFingerprint?"published-project":"run-only",i=ai(["profile-workload-v1",e.toolVersion,e.command,e.projectFingerprint??n]);return process.env[kc]=i,process.env[Pc]=r,i}function ai(e){return rI("sha256").update(JSON.stringify(e)).digest("hex").slice(0,24)}function hf(){return Object.fromEntries(mf.flatMap(e=>{let t=process.env[e];return t===void 0?[]:[[e,t]]}))}function w(e,t,n){if(!U())return t();let r=pr.now();try{let i=t();return fn({type:"span",name:e,durationMs:Math.round(pr.now()-r),ok:!0,...jo(n)??{}}),i}catch(i){throw fn({type:"span",name:e,durationMs:Math.round(pr.now()-r),ok:!1,error:i instanceof Error?i.message:String(i),...jo(n)??{}}),i}}async function VY(e,t,n){if(!U())return t();let r=pr.now();try{let i=await t();return fn({type:"span",name:e,durationMs:Math.round(pr.now()-r),ok:!0,...jo(n)??{}}),i}catch(i){throw fn({type:"span",name:e,durationMs:Math.round(pr.now()-r),ok:!1,error:i instanceof Error?i.message:String(i),...jo(n)??{}}),i}}function fn(e,t=sI()){let n=lI(e),r={timestamp:new Date().toISOString(),pid:process.pid,runId:pf(),command:ff(),cacheState:aI(),...n,...e},i=`${JSON.stringify(r)}
|
|
84
84
|
`;if(t)try{let o=oI(t);of.has(o)||(nI(o,{recursive:!0}),of.add(o)),tI(t,i);return}catch(o){af||(af=!0,process.stderr.write(`[profile] failed to write ${t}: ${o instanceof Error?o.message:String(o)}
|
|
85
|
-
`));return}U()&&process.stderr.write(i)}function lI(e){let t=gf()??cI({command:ff()??"unknown",toolVersion:"unknown",projectFingerprint:null});if(!t)return{};let n=process.env[Pc],r=typeof e.name=="string"?e.name:void 0;if(!r)return{workloadIdentity:t,workloadIdentityKind:n};let i=r.split(/[.:]/,1)[0]??r,o=`${t}\0${r}`,s=sf.get(o);return s||(s=ai(["profile-subsystem-v1",t,r]),sf.set(o,s)),{workloadIdentity:t,workloadIdentityKind:n,subsystem:i,subsystemWorkIdentity:s}}function jo(e){return typeof e=="function"?e():e}import{spawnSync as uI}from"child_process";import{createHash as dI}from"crypto";import{existsSync as mI,lstatSync as fI,realpathSync as pI}from"fs";import{dirname as gI,isAbsolute as hI,join as yI,resolve as $o}from"path";var ci={run(e,t){let n=bf(e,t);return n.kind==="success"?n.output:void 0},runResult:bf},bI=["rev-parse","--show-toplevel","--absolute-git-dir","--git-common-dir","HEAD","HEAD^{tree}"],yf=/^[0-9a-f]{40,64}$/;function
|
|
86
|
-
`).map(c=>c.trim());if(t.length!==5)return;let[n,r,i,o,s]=t;if(!n||!r||!i||!o||!s||!yf.test(o)||!yf.test(s))return;let a=
|
|
87
|
-
`):[]})}var HI=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar|twin))?\b/i;function di(e){let t=HI.exec(e);return t?t[1]??"":null}function Ho(e,t,n){return Ef(e,t,n).length>0}function Uo(e,t,n,r){let i=r.toLowerCase();return Ef(e,t,n).some(o=>o.toLowerCase()===i)}function Ef(e,t,n){if(n<=0)return[];let r=Ce(e,t);if(r.length===0)return[];let i=[];for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(r[o]??"").trim();if(s==="")continue;let a=di(s);if(a!==null){i.push(a);continue}if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return i}return i}import{posix as Ac}from"path";import{parse as UI}from"@vue/compiler-sfc";var WI=
|
|
85
|
+
`));return}U()&&process.stderr.write(i)}function lI(e){let t=gf()??cI({command:ff()??"unknown",toolVersion:"unknown",projectFingerprint:null});if(!t)return{};let n=process.env[Pc],r=typeof e.name=="string"?e.name:void 0;if(!r)return{workloadIdentity:t,workloadIdentityKind:n};let i=r.split(/[.:]/,1)[0]??r,o=`${t}\0${r}`,s=sf.get(o);return s||(s=ai(["profile-subsystem-v1",t,r]),sf.set(o,s)),{workloadIdentity:t,workloadIdentityKind:n,subsystem:i,subsystemWorkIdentity:s}}function jo(e){return typeof e=="function"?e():e}import{spawnSync as uI}from"child_process";import{createHash as dI}from"crypto";import{existsSync as mI,lstatSync as fI,realpathSync as pI}from"fs";import{dirname as gI,isAbsolute as hI,join as yI,resolve as $o}from"path";var ci={run(e,t){let n=bf(e,t);return n.kind==="success"?n.output:void 0},runResult:bf},bI=["rev-parse","--show-toplevel","--absolute-git-dir","--git-common-dir","HEAD","HEAD^{tree}"],yf=/^[0-9a-f]{40,64}$/;function QY(e,t=ci){let n=t.run(e,["rev-parse","--show-toplevel"])?.trim();return n?vt(n):void 0}function gr(e,t=ci){let n=t.runResult(e,bI);if(n.kind==="success"){let r=SI(n.output);if(r)return CI(r,t)}return xI(e,t)}function SI(e){let t=e.split(`
|
|
86
|
+
`).map(c=>c.trim());if(t.length!==5)return;let[n,r,i,o,s]=t;if(!n||!r||!i||!o||!s||!yf.test(o)||!yf.test(s))return;let a=vt(n);return{root:a,gitDir:vt(Bo(a,r)),commonDir:vt(Bo(a,i)),headCommit:o,treeOid:s}}function CI(e,t){let n=t.run(e.root,["status","--porcelain=v1","-z","--untracked-files=all"]);return n===void 0?void 0:{...Sf(e.root,e.gitDir),commonDir:e.commonDir,repositoryId:_c("repository",e.commonDir),headCommit:e.headCommit,treeOid:e.treeOid,clean:n.length===0}}function xI(e,t){let n=RI(e,t);if(n.kind!=="worktree")return;let r=n.identity,i=r.projectRoot,o=t.run(i,["rev-parse","--git-common-dir"])?.trim();if(!o)return;let s=vt(Bo(i,o)),a=Tc(t.run(i,["rev-parse","--verify","HEAD"])),c=Tc(t.run(i,["rev-parse","--verify","HEAD^{tree}"])),l=t.run(i,["status","--porcelain=v1","-z","--untracked-files=all"]);if(l!==void 0)return{...r,commonDir:s,repositoryId:_c("repository",s),headCommit:a,treeOid:c,clean:l.length===0}}function RI(e,t=ci){let n=t.runResult(e,["rev-parse","--show-toplevel"]);if(n.kind==="not-repository")return{kind:"non-git"};if(n.kind==="error")return n;let r=n.output.trim();if(!r)return{kind:"error",message:"Git returned an empty worktree root."};let i=vt(r),o=t.run(i,["rev-parse","--absolute-git-dir"])?.trim();if(!o)return{kind:"error",message:"Git did not return an absolute worktree directory."};let s=vt(Bo(i,o));return{kind:"worktree",identity:Sf(i,s)}}function Sf(e,t){return{projectRoot:e,gitDir:t,worktreeId:_c("worktree",`${e}\0${t}`)}}function Cf(e,t=ci){let n=t.run(e,["worktree","list","--porcelain","-z"]);return n===void 0?[]:vI(n)}function vI(e){let t=[],n;for(let r of e.split("\0")){if(r===""){n&&t.push(n),n=void 0;continue}let i=r.indexOf(" "),o=i<0?r:r.slice(0,i),s=i<0?"":r.slice(i+1);if(o==="worktree"){n&&t.push(n),n={path:vt(s),detached:!1,bare:!1,prunable:!1,locked:!1};continue}n&&(o==="HEAD"?n.head=s:o==="branch"?n.branch=s:o==="detached"?n.detached=!0:o==="bare"?n.bare=!0:o==="prunable"?n.prunable=!0:o==="locked"&&(n.locked=!0))}return n&&t.push(n),t}function ZY(e,t,n=ci){return Tc(n.run(e,t))}function Bo(e,t){return hI(t)?t:$o(e,t)}function vt(e){try{return pI(e)}catch{return $o(e)}}function _c(e,t){return dI("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24)}function Tc(e){return e?.trim()||void 0}function bf(e,t){let n=uI("git",["-C",e,...t],{encoding:"utf-8",env:{...process.env,LC_ALL:"C"},maxBuffer:52428800,stdio:["ignore","pipe","pipe"]});if(n.status===0)return{kind:"success",output:n.stdout.trimEnd()};let i=(typeof n.stderr=="string"?n.stderr.trim():"")||n.error?.message||`git exited with status ${n.status??"unknown"}`,o=n.error?.code;return(/not a git repository/i.test(i)||o==="ENOENT"&&mI($o(e)))&&!II(e)?{kind:"not-repository"}:{kind:"error",message:i}}function II(e){if(process.env.GIT_DIR||process.env.GIT_COMMON_DIR)return!0;let t=$o(e);for(;;){try{return fI(yI(t,".git")),!0}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTDIR")return!0}let n=gI(t);if(n===t)return!1;t=n}}var wI={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function ye(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=DI(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function It(e){let t=ye(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 DI(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||xf(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&&!xf(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=wI[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function xf(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function I(e){let t=ye(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=EI(i);o&&r.push(o)}return r.join(":")}function EI(e){let t=e.suffix==="namespace"?kI(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function kI(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 T(e){let t=ye(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 ue(e){let t=ye(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function le(e){return e.endsWith("().")||ue(e)==="method"}function ee(e){let t=ue(e);return t==="method"?!0:t!=="term"?!1:e.endsWith("().")?!0:e.startsWith("rust-analyzer ")&&e.includes("#")?!1:e.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(e):!0}function pn(e){return ue(e)==="namespace"}var PI=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function Ie(e){return PI.test(e)}var TI=new Set(["test","tests","_tests"]);function hr(e){let t=ye(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&&TI.has(r.name))return!0}return!1}function Rf(e,t){let n=ye(e),r=ye(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 vf(e,t){let n=ye(e),r=ye(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}import{extname as If}from"path";var _I={".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",".clj":"clojure",".cljs":"clojure",".cljc":"clojure"};function M(e){return _I[If(e).toLowerCase()]??null}function Ht(e){return If(e).toLowerCase()===".vue"}import{createRequire as FI}from"module";var Ae=FI(import.meta.url),li=null,Fc=!1;function wf(){if(Fc)return null;if(li)return li;try{return li=Ae("tree-sitter"),li}catch{return Fc=!0,null}}function o5(e){if(e==="clojure")return"reader";let t=wf();if(!t)return"unavailable";let n=Df(e);if(!n)return"unavailable";try{return new t().setLanguage(n),"ast"}catch{return yr.add(e),"unavailable"}}var Lc=new Map,yr=new Set;function Df(e){if(yr.has(e))return null;let t=Lc.get(e);if(t)return t;let n;try{switch(e){case"rust":n=Ae("tree-sitter-rust");break;case"typescript":n=Ae("tree-sitter-typescript").typescript;break;case"tsx":n=Ae("tree-sitter-typescript").tsx;break;case"javascript":n=Ae("tree-sitter-javascript");break;case"python":n=Ae("tree-sitter-python");break;case"java":n=Ae("tree-sitter-java");break;case"kotlin":n=Ae("tree-sitter-kotlin");break;case"scala":n=Ae("tree-sitter-scala");break;case"ruby":n=Ae("tree-sitter-ruby");break;case"c":n=Ae("tree-sitter-c");break;case"cpp":n=Ae("tree-sitter-cpp");break;case"csharp":n=Ae("tree-sitter-c-sharp");break;case"php":n=Ae("tree-sitter-php").php;break;case"vb":{let r=Ae("tree-sitter-vb-dotnet");n=r.language??r;break}case"clojure":return yr.add(e),null}}catch{return yr.add(e),null}return Lc.set(e,n),n}var Nc=new Map;function s5(){li=null,Fc=!1,Lc.clear(),yr.clear(),Nc.clear(),AI.clear()}function LI(e){let t=Nc.get(e);if(t)return t;let n=Df(e);if(!n)return null;let r=wf();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return yr.add(e),null}return Nc.set(e,i),i}function NI(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function ui(e,t){let n=LI(e);if(!n)return null;try{return NI(n,t)}catch{return null}}var AI=new Map;import{readFileSync as MI}from"fs";import{join as OI}from"path";var jI=j("source-text",{clearGroups:["whole-project","source-file"]}),BI=j("source-lines",{clearGroups:["whole-project","source-file"]});function P(e,t){let n=t.replace(/\\/g,"/");return jI.get(e,n,()=>{let r=OI(e.config.projectRoot,n);try{return MI(r,"utf-8")}catch(i){if($I(i))return"";throw i}})}function $I(e){return typeof e=="object"&&e!==null&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function Ce(e,t){let n=t.replace(/\\/g,"/");return BI.get(e,n,()=>{let r=P(e,n);return r?r.split(`
|
|
87
|
+
`):[]})}var HI=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar|twin))?\b/i;function di(e){let t=HI.exec(e);return t?t[1]??"":null}function Ho(e,t,n){return Ef(e,t,n).length>0}function Uo(e,t,n,r){let i=r.toLowerCase();return Ef(e,t,n).some(o=>o.toLowerCase()===i)}function Ef(e,t,n){if(n<=0)return[];let r=Ce(e,t);if(r.length===0)return[];let i=[];for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(r[o]??"").trim();if(s==="")continue;let a=di(s);if(a!==null){i.push(a);continue}if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return i}return i}import{posix as Ac}from"path";import{parse as UI}from"@vue/compiler-sfc";var WI=mn("vue-sfc-units");function br(e,t){let n=Tf(t),r=P(e,n);return WI.get(e,n,r,()=>Mc(e,n,r))}function Tf(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function GI(e){let t=e?.toLowerCase();return!t||t==="js"||t==="javascript"||t==="jsx"?"javascript":t==="ts"||t==="typescript"?"typescript":t==="tsx"?"tsx":null}function Mn(e){return!e||e.body.length===0?0:e.body.split(`
|
|
88
88
|
`).length}function Mc(e,t,n){let r={relativePath:t,template:null,scripts:[],styles:[],customBlocks:[],errors:[]};if(!n)return r;let i;try{i=UI(n,{filename:t})}catch(s){return r.errors.push(Pf(s)),r}r.errors.push(...i.errors.map(Pf));let{descriptor:o}=i;return o.template&&(r.template=Wo(e,t,"template",o.template)),o.script&&r.scripts.push(kf(e,t,o.script,!1)),o.scriptSetup&&r.scripts.push(kf(e,t,o.scriptSetup,!0)),r.styles=o.styles.map(s=>Wo(e,t,"style",s)),r.customBlocks=o.customBlocks.map(s=>Wo(e,t,"custom",s)),r.errors.push(...[r.template,...r.scripts,...r.styles,...r.customBlocks].flatMap(s=>s?.errors??[])),r}function kf(e,t,n,r){let i=Wo(e,t,"script",n);return{...i,kind:"script",setup:r,astLanguage:GI(i.lang)}}function Wo(e,t,n,r){let i=VI(r.attrs),o=typeof i.lang=="string"?i.lang:null,s=typeof i.src=="string"?i.src:typeof r.src=="string"?r.src:void 0;if(s){let c=zI(t,s);if(!c)return{kind:n,ownerPath:t,sourcePath:t,external:!0,src:s,attrs:i,lang:o,body:"",startLine:0,endLine:0,errors:[`Could not resolve Vue ${n} block source: ${s}`]};let l=P(e,c),u=l?Math.max(0,l.split(`
|
|
89
89
|
`).length-1):0;return{kind:n,ownerPath:t,sourcePath:c,external:!0,src:s,attrs:i,lang:o,body:l,startLine:0,endLine:u,errors:l?[]:[`Vue ${n} block source not found: ${c}`]}}let a=Math.max(0,r.loc.start.line-1);return{kind:n,ownerPath:t,sourcePath:t,external:!1,attrs:i,lang:o,body:r.content,startLine:a,endLine:Math.max(a,r.loc.end.line-1),errors:[]}}function zI(e,t){let n=t.split(/[?#]/,1)[0];if(!n||n.startsWith("/")||n.includes("://"))return null;let r=Tf(Ac.normalize(Ac.join(Ac.dirname(e),n)));return r===".."||r.startsWith("../")?null:r}function VI(e){return{...e}}function Pf(e){return e instanceof Error?e.message:String(e)}function Go(e,t,n){let i=Mc(e,t,n).scripts.filter(s=>s.astLanguage&&s.body.length>0),o=i[0]?.astLanguage;return o?{body:i.map(s=>`${`
|
|
90
90
|
`.repeat(s.startLine)}${s.body}`).join(`
|
|
91
|
-
`),startLine:0,language:o}:null}var _f=
|
|
92
|
-
`.repeat(r.startLine)+r.body;return ui(r.language,i)}):null}function Sr(e,t){let n=KI(e,t);if(!n)return null;let r=Mn(n);return r?{calleeLeaf:r,memberAccess:JI(n),line:e.startPosition.row}:null}function KI(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 JI(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function Mn(e){switch(e.type){case"identifier":case"type_identifier":case"field_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?Mn(t):null}case"generic_function":{let t=e.childForFieldName("function")??e.namedChild(0);return t?Mn(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?Mn(t):null}case"super":case"self":case"this":return null;default:return null}}var YI=[Be("source-facts",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/source/source-facts.ts"}),Be("file-definitions",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/symbols/definition-catalog.ts"}),Be("definition-exclusions",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/analysis/framework-patterns.ts"}),Be("doc-path-tokens",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-products.test.ts",owner:"tests/storage/evidence-cache.test.ts"}),Be("doc-path-evidence",{dependsOn:["content-hash","git-history","git-head","tool-version"],keyParts:["kind","relativePath","contentHash","trackedFiles","historyWindow","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/queries/cleanup/doc-drift.ts"}),Be("source-imports",{dependsOn:["content-hash","import-resolution-fingerprint","config","tool-version"],keyParts:["kind","relativePath","contentHash","importResolutionFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/language-parsers/index.ts"}),Be("source-reexports",{dependsOn:["content-hash","import-resolution-fingerprint","config","tool-version"],keyParts:["kind","relativePath","contentHash","importResolutionFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/language-parsers/index.ts"}),Be("source-fingerprints",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/symbols/definition-catalog.test.ts",owner:"src/queries/cleanup/similar.ts"}),Be("consumer-file-usage",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/queries/internal/consumer-evidence.ts"}),Be("react-component-behavior-profiles",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/source/react-profile.ts"}),Be("git-file-adds",{dependsOn:["git-head","git-history","tool-version"],keyParts:["kind","cacheKey","head","historyWindow","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/analysis/git-history.ts"}),Be("typescript-reference-fragments",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-reference-fragments.test.ts",owner:"src/semantic/typescript/reference-fragment-shadow.ts"}),Be("typescript-import-usage",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-semantic-provider.test.ts",owner:"src/semantic/shared-primitives.ts"}),Be("typescript-signatures",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-semantic-provider.test.ts",owner:"src/semantic/shared-primitives.ts"}),zo("file-dependency-graph",{dependsOn:["project-fingerprint","indexed-language-set","import-resolution-fingerprint","tool-version"],keyParts:["kind","scope","projectFingerprint","payloadVersion"],stalenessTest:"tests/symbols/file-dep-graph.test.ts",owner:"src/symbols/graph/file-dep-graph.ts"}),zo("semantic-import-usage",{dependsOn:["project-fingerprint","indexed-language-set","import-resolution-fingerprint","tool-version"],keyParts:["kind","relativePath","projectFingerprint","language","semanticEngine","payloadVersion"],stalenessTest:"tests/semantic/rust/rust-semantic-cache-gate.test.ts",owner:"src/semantic/shared-primitives.ts"}),zo("semantic-signatures",{dependsOn:["project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","symbol","projectFingerprint","language","semanticEngine","payloadVersion"],stalenessTest:"tests/semantic/rust/rust-semantic-cache-gate.test.ts",owner:"src/semantic/shared-primitives.ts"}),zo("health-semantic-prewarm",{dependsOn:["project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","scope","cliVersion","projectFingerprint","payloadVersion"],stalenessTest:"tests/runtime/cli-support.test.ts",owner:"src/runtime/cli-support.ts"})];function oe(e){let t=new Map;return{kind:e.kind,read(n,r,i){let o=!1,s=0,a;if(U()){let c=Te(n);if(c){let l=`${c}\0${r}\0${i}`;a=t.get(l),a||(a=ai(["evidence-product-file-read-v1",e.kind,c,r,i]),t.set(l,a))}}return w("evidence-product.file.read",()=>{let c=qm(n,e.kind,r,i);if(c===null)return null;s=c.length;try{let l=e.deserialize(c);return o=l!==null,l}catch{return null}},()=>({...a?{workIdentity:a,workOutcome:"computed"}:{},scope:"file",kind:e.kind,available:!0,hit:o,payloadBytes:s}))},write(n,r,i,o){Km(n,e.kind,r,i,e.serialize(o))},writeBatch(n,r){Jm(n,r.map(i=>({kind:e.kind,relativePath:i.relativePath,contentHash:i.contentHash,payload:e.serialize(i.value)})))}}}function On(e){let t=new Map;return{kind:e.kind,read(n,r,i){let o=!1,s=0,a;if(U()){let c=`${i}\0${r}`;a=t.get(c),a||(a=ai(["evidence-product-project-read-v1",e.kind,i,r]),t.set(c,a))}return w("evidence-product.project.read",()=>{let c=Ym(n,e.kind,r,i);if(c===null)return null;s=c.length;try{let l=e.deserialize(c);return o=l!==null,l}catch{return null}},()=>({...a?{workIdentity:a,workOutcome:"computed"}:{},scope:"project",kind:e.kind,available:!0,hit:o,payloadBytes:s}))},write(n,r,i,o){Xm(n,e.kind,r,i,e.serialize(o))}}}function K(e){let t=YI.find(n=>n.kind===e);if(!t)throw new Error(`missing evidence product manifest entry for ${e}`);return t.invalidation}function Be(e,t){return{scope:"file",kind:e,invalidation:{scope:"file",...t}}}function zo(e,t){return{scope:"project",kind:e,invalidation:{scope:"project",...t}}}function mi(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var XI=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function Vo(e,t){let n=ZI(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:Nf(n.functionNode),params:Ff(n.functionNode),paramsEndLine:Lf(n.functionNode),isLiteralPassthrough:Af(n.functionNode,t)};if(!QI(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:Nf(e),params:Ff(e),paramsEndLine:Lf(e),isLiteralPassthrough:Af(e,t)}:null}function Mf(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function Ff(e){let t=Mf(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(mi(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 Lf(e){let t=Mf(e);return t?t.endPosition.row:e.startPosition.row}function QI(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?XI.has(e):!1}function ZI(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 Nf(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)mi(r)||(n+=1);return n}function Af(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=>!mi(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=>!mi(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 ew=new Set(["identifier","type_identifier","field_identifier"]),tw=new Set(["identifier"]),nw=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),rw=new Set(["rust","python"]),iw=/\{([^{}]*)\}/g,ow=/\b([A-Za-z_][\w]*)\b/g;function Of(e,t){return sw(t).has(e.type)}function jf(e,t){return rw.has(t)&&e.type==="string_content"}function Oc(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 sw(e){return e==="rust"?ew:e==="python"?tw:nw}function Bf(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(iw)){let i=r[1]??"";for(let o of i.matchAll(ow))o[1]&&t(o[1],n)}}var aw=[/\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],cw=/^#!?\[\s*serde\s*\(/,lw=/^#!?\[\s*schemars\s*\(/,uw=/^#!?\[\s*validate\s*\(/,dw=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function $f(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=Mn(r);if(!i||!dw.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 Hf(e,t){let n=cw.test(e),r=lw.test(e),i=uw.test(e);if(!(!n&&!r&&!i))for(let o of aw){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 Uf(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(u=>u.type==="identifier")?.text;if(!a)continue;let c=s.childForFieldName("superclasses");c&&o(c,a);let l=s.namedChildren.find(u=>u.type==="block");if(l)for(let u of l.descendantsOfType("type"))for(let d of u.descendantsOfType("identifier"))d.text!==a&&r(d.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 mw=new Map([["defn","function"],["defn-","function"],["defmacro","macro"],["defmacro-","macro"],["defmethod","method"]]),jc=new Set(["catch","comment","def","defprotocol","defrecord","deftype","defmethod","defmacro","defmacro-","defn","defn-","do","doseq","dotimes","fn","for","if","let","loop","ns","quote","recur","throw","try","extend-protocol","extend-type","when","when-let","when-not"]);function Wf(e){let t=[],n=[],r=[],i=new Map,o=[],s=0,a=0,c=(l,u)=>{let d=i.get(l);if(!d){i.set(l,[u]);return}d[d.length-1]!==u&&d.push(u)};for(;a<e.length;){let l=e[a];if(l===`
|
|
93
|
-
`){s+=1,a+=1;continue}if(/\s|,/.test(l)){a+=1;continue}if(l===";"){a=Ko(e,a);continue}if(l==='"'){let p=pi(e,a,s);s=p.line,a=p.index;continue}if(l==="("||l==="["||l==="{"){o.push({kind:l,startLine:s,endLine:s,headTokens:[],tokens:[],children:[]}),a+=1;continue}if(l===")"||l==="]"||l==="}"){let p=o.pop();p&&(p.endLine=s,fw(p,{callables:t,callSites:n,clojureMembers:r,recordIdentifier:c}),o[o.length-1]?.children.push(p)),a+=1;continue}if(Bc(l)){a+=1;continue}let u=s,d=a;for(;a<e.length&&!$c(e[a]);)a+=1;let m=e.slice(d,a);if(!m)continue;let f={text:m,line:u};pw(o[o.length-1],f),c(
|
|
91
|
+
`),startLine:0,language:o}:null}var _f=An("ast-trees",{clearGroups:["whole-project","source-file"]});function q(e,t){if(Ht(t))return qI(e,t);let n=M(t);if(!n)return null;let r=P(e,t);return r?_f.get(e,t,r,()=>ui(n,r)):null}function qI(e,t){let n=P(e,t);return n?_f.get(e,t,n,()=>{let r=Go(e,t,n);if(!r)return null;let i=`
|
|
92
|
+
`.repeat(r.startLine)+r.body;return ui(r.language,i)}):null}function Sr(e,t){let n=KI(e,t);if(!n)return null;let r=On(n);return r?{calleeLeaf:r,memberAccess:JI(n),line:e.startPosition.row}:null}function KI(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 JI(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function On(e){switch(e.type){case"identifier":case"type_identifier":case"field_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?On(t):null}case"generic_function":{let t=e.childForFieldName("function")??e.namedChild(0);return t?On(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?On(t):null}case"super":case"self":case"this":return null;default:return null}}var YI=[Be("source-facts",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/source/source-facts.ts"}),Be("file-definitions",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/symbols/definition-catalog.ts"}),Be("definition-exclusions",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/analysis/framework-patterns.ts"}),Be("doc-path-tokens",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-products.test.ts",owner:"tests/storage/evidence-cache.test.ts"}),Be("doc-path-evidence",{dependsOn:["content-hash","git-history","git-head","tool-version"],keyParts:["kind","relativePath","contentHash","trackedFiles","historyWindow","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/queries/cleanup/doc-drift.ts"}),Be("source-imports",{dependsOn:["content-hash","import-resolution-fingerprint","config","tool-version"],keyParts:["kind","relativePath","contentHash","importResolutionFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/language-parsers/index.ts"}),Be("source-reexports",{dependsOn:["content-hash","import-resolution-fingerprint","config","tool-version"],keyParts:["kind","relativePath","contentHash","importResolutionFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/language-parsers/index.ts"}),Be("source-fingerprints",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/symbols/definition-catalog.test.ts",owner:"src/queries/cleanup/similar.ts"}),Be("consumer-file-usage",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/queries/internal/consumer-evidence.ts"}),Be("react-component-behavior-profiles",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/source/react-profile.ts"}),Be("git-file-adds",{dependsOn:["git-head","git-history","tool-version"],keyParts:["kind","cacheKey","head","historyWindow","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/analysis/git-history.ts"}),Be("typescript-reference-fragments",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-reference-fragments.test.ts",owner:"src/semantic/typescript/reference-fragment-shadow.ts"}),Be("typescript-import-usage",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-semantic-provider.test.ts",owner:"src/semantic/shared-primitives.ts"}),Be("typescript-signatures",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-semantic-provider.test.ts",owner:"src/semantic/shared-primitives.ts"}),zo("file-dependency-graph",{dependsOn:["project-fingerprint","indexed-language-set","import-resolution-fingerprint","tool-version"],keyParts:["kind","scope","projectFingerprint","payloadVersion"],stalenessTest:"tests/symbols/file-dep-graph.test.ts",owner:"src/symbols/graph/file-dep-graph.ts"}),zo("semantic-import-usage",{dependsOn:["project-fingerprint","indexed-language-set","import-resolution-fingerprint","tool-version"],keyParts:["kind","relativePath","projectFingerprint","language","semanticEngine","payloadVersion"],stalenessTest:"tests/semantic/rust/rust-semantic-cache-gate.test.ts",owner:"src/semantic/shared-primitives.ts"}),zo("semantic-signatures",{dependsOn:["project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","symbol","projectFingerprint","language","semanticEngine","payloadVersion"],stalenessTest:"tests/semantic/rust/rust-semantic-cache-gate.test.ts",owner:"src/semantic/shared-primitives.ts"}),zo("health-semantic-prewarm",{dependsOn:["project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","scope","cliVersion","projectFingerprint","payloadVersion"],stalenessTest:"tests/runtime/cli-support.test.ts",owner:"src/runtime/cli-support.ts"})];function oe(e){let t=new Map;return{kind:e.kind,read(n,r,i){let o=!1,s=0,a;if(U()){let c=Te(n);if(c){let l=`${c}\0${r}\0${i}`;a=t.get(l),a||(a=ai(["evidence-product-file-read-v1",e.kind,c,r,i]),t.set(l,a))}}return w("evidence-product.file.read",()=>{let c=qm(n,e.kind,r,i);if(c===null)return null;s=c.length;try{let l=e.deserialize(c);return o=l!==null,l}catch{return null}},()=>({...a?{workIdentity:a,workOutcome:"computed"}:{},scope:"file",kind:e.kind,available:!0,hit:o,payloadBytes:s}))},write(n,r,i,o){Km(n,e.kind,r,i,e.serialize(o))},writeBatch(n,r){Jm(n,r.map(i=>({kind:e.kind,relativePath:i.relativePath,contentHash:i.contentHash,payload:e.serialize(i.value)})))}}}function jn(e){let t=new Map;return{kind:e.kind,read(n,r,i){let o=!1,s=0,a;if(U()){let c=`${i}\0${r}`;a=t.get(c),a||(a=ai(["evidence-product-project-read-v1",e.kind,i,r]),t.set(c,a))}return w("evidence-product.project.read",()=>{let c=Ym(n,e.kind,r,i);if(c===null)return null;s=c.length;try{let l=e.deserialize(c);return o=l!==null,l}catch{return null}},()=>({...a?{workIdentity:a,workOutcome:"computed"}:{},scope:"project",kind:e.kind,available:!0,hit:o,payloadBytes:s}))},write(n,r,i,o){Xm(n,e.kind,r,i,e.serialize(o))}}}function K(e){let t=YI.find(n=>n.kind===e);if(!t)throw new Error(`missing evidence product manifest entry for ${e}`);return t.invalidation}function Be(e,t){return{scope:"file",kind:e,invalidation:{scope:"file",...t}}}function zo(e,t){return{scope:"project",kind:e,invalidation:{scope:"project",...t}}}function mi(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var XI=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function Vo(e,t){let n=ZI(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:Nf(n.functionNode),params:Ff(n.functionNode),paramsEndLine:Lf(n.functionNode),isLiteralPassthrough:Af(n.functionNode,t)};if(!QI(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:Nf(e),params:Ff(e),paramsEndLine:Lf(e),isLiteralPassthrough:Af(e,t)}:null}function Mf(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function Ff(e){let t=Mf(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(mi(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 Lf(e){let t=Mf(e);return t?t.endPosition.row:e.startPosition.row}function QI(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?XI.has(e):!1}function ZI(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 Nf(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)mi(r)||(n+=1);return n}function Af(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=>!mi(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=>!mi(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 ew=new Set(["identifier","type_identifier","field_identifier"]),tw=new Set(["identifier"]),nw=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),rw=new Set(["rust","python"]),iw=/\{([^{}]*)\}/g,ow=/\b([A-Za-z_][\w]*)\b/g;function Of(e,t){return sw(t).has(e.type)}function jf(e,t){return rw.has(t)&&e.type==="string_content"}function Oc(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 sw(e){return e==="rust"?ew:e==="python"?tw:nw}function Bf(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(iw)){let i=r[1]??"";for(let o of i.matchAll(ow))o[1]&&t(o[1],n)}}var aw=[/\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],cw=/^#!?\[\s*serde\s*\(/,lw=/^#!?\[\s*schemars\s*\(/,uw=/^#!?\[\s*validate\s*\(/,dw=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function $f(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=On(r);if(!i||!dw.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 Hf(e,t){let n=cw.test(e),r=lw.test(e),i=uw.test(e);if(!(!n&&!r&&!i))for(let o of aw){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 Uf(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(u=>u.type==="identifier")?.text;if(!a)continue;let c=s.childForFieldName("superclasses");c&&o(c,a);let l=s.namedChildren.find(u=>u.type==="block");if(l)for(let u of l.descendantsOfType("type"))for(let d of u.descendantsOfType("identifier"))d.text!==a&&r(d.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 mw=new Map([["defn","function"],["defn-","function"],["defmacro","macro"],["defmacro-","macro"],["defmethod","method"]]),jc=new Set(["catch","comment","def","defprotocol","defrecord","deftype","defmethod","defmacro","defmacro-","defn","defn-","do","doseq","dotimes","fn","for","if","let","loop","ns","quote","recur","throw","try","extend-protocol","extend-type","when","when-let","when-not"]);function Wf(e){let t=[],n=[],r=[],i=new Map,o=[],s=0,a=0,c=(l,u)=>{let d=i.get(l);if(!d){i.set(l,[u]);return}d[d.length-1]!==u&&d.push(u)};for(;a<e.length;){let l=e[a];if(l===`
|
|
93
|
+
`){s+=1,a+=1;continue}if(/\s|,/.test(l)){a+=1;continue}if(l===";"){a=Ko(e,a);continue}if(l==='"'){let p=pi(e,a,s);s=p.line,a=p.index;continue}if(l==="("||l==="["||l==="{"){o.push({kind:l,startLine:s,endLine:s,headTokens:[],tokens:[],children:[]}),a+=1;continue}if(l===")"||l==="]"||l==="}"){let p=o.pop();p&&(p.endLine=s,fw(p,{callables:t,callSites:n,clojureMembers:r,recordIdentifier:c}),o[o.length-1]?.children.push(p)),a+=1;continue}if(Bc(l)){a+=1;continue}let u=s,d=a;for(;a<e.length&&!$c(e[a]);)a+=1;let m=e.slice(d,a);if(!m)continue;let f={text:m,line:u};pw(o[o.length-1],f),c(rt(m),u)}return{language:"clojure",callables:t,callSites:n,clojureMembers:r,typeContainerMap:new Map,identifierLineMap:i,identifiersByLine:Sw(i),fileIdentifiers:new Set(i.keys()),rustAttrReferencedNames:new Set,crossLanguageDispatchNames:new Set}}function fw(e,t){if(e.kind!=="("||e.headTokens.length===0)return;let n=e.headTokens[0],r=rt(n.text),i=mw.get(n.text);if(i){let s=e.headTokens[1];if(s){let a=rt(s.text);t.recordIdentifier(a,s.line),t.callables.push({name:a,startLine:e.startLine,endLine:e.endLine,paramCount:0,params:[],paramsEndLine:s.line,isLiteralPassthrough:!1,clojureKind:i})}}if(gw(e,t),!r||jc.has(n.text)||jc.has(r)||r.startsWith(":"))return;let o=bw(n.text);t.callSites.push({calleeLeaf:o.leaf,calleeQualifier:o.qualifier,calleeText:o.text,memberAccess:!1,line:n.line})}function pw(e,t){e&&(e.headTokens.length<2&&e.headTokens.push(t),e.tokens.length<200&&e.tokens.push(t))}function gw(e,t){let n=rt(e.tokens[0]?.text??"");if(n==="defprotocol"){let r=rt(e.tokens[1]?.text??"");if(!r)return;for(let i of qo(e))fi(t,r,"protocol",i,"protocol-method");return}if(n==="defrecord"||n==="deftype"){let r=rt(e.tokens[1]?.text??"");if(!r)return;let i=n==="defrecord"?"record":"type",o=n==="defrecord"?"record-method":"type-method";for(let s of qo(e))fi(t,r,i,s,o);return}if(n==="extend-type"){let r=rt(e.tokens[1]?.text??"");if(!r)return;for(let i of qo(e))fi(t,r,"extension",i,"extension-method");return}if(n==="extend-protocol"){let r=rt(e.tokens[1]?.text??"");for(let i of qo(e)){r&&fi(t,r,"extension",i,"extension-method");let o=yw(e,i.startLine);o&&o!==r&&fi(t,o,"extension",i,"extension-method")}}}function qo(e){return e.children.filter(hw)}function hw(e){if(e.kind!=="(")return!1;let t=rt(e.tokens[0]?.text??"");return!!(t&&!jc.has(t)&&!t.startsWith(":"))}function fi(e,t,n,r,i){let o=r.tokens[0],s=rt(o?.text??"");!o||!s||(e.recordIdentifier(s,o.line),e.clojureMembers.push({ownerName:t,ownerKind:n,memberName:s,memberKind:i,startLine:r.startLine,endLine:r.endLine}))}function yw(e,t){let n=null;for(let r=2;r<e.tokens.length;r+=1){let i=e.tokens[r];if(i.line>t)break;let o=rt(i.text);o&&!o.startsWith(":")&&(n=o)}return n}function rt(e){return e.replace(/^#?['`~@]+/,"").split("/").pop()?.replace(/^\./,"")??""}function bw(e){let t=e.replace(/^#?['`~@]+/,""),n=t.lastIndexOf("/"),r=rt(t);if(n<=0)return{leaf:r,text:t};let i=t.slice(0,n);return{leaf:r,qualifier:i,text:t}}function Ko(e,t){let n=t;for(;n<e.length&&e[n]!==`
|
|
94
94
|
`;)n+=1;return n}function pi(e,t,n){let r=t+1,i=n;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o===`
|
|
95
|
-
`&&(i+=1),r+=1,o==='"')break}return{index:r,line:i}}function Bc(e){return e==="'"||e==="`"||e==="~"||e==="@"||e==="^"||e==="#"}function $c(e){return/\s|,/.test(e)||e==="("||e===")"||e==="["||e==="]"||e==="{"||e==="}"||e==='"'||e===";"}function Sw(e){let t=[];for(let[n,r]of e)for(let i of r)t[i]??=new Set,t[i].add(n);return t}var Gf=3,Cw=
|
|
95
|
+
`&&(i+=1),r+=1,o==='"')break}return{index:r,line:i}}function Bc(e){return e==="'"||e==="`"||e==="~"||e==="@"||e==="^"||e==="#"}function $c(e){return/\s|,/.test(e)||e==="("||e===")"||e==="["||e==="]"||e==="{"||e==="}"||e==='"'||e===";"}function Sw(e){let t=[];for(let[n,r]of e)for(let i of r)t[i]??=new Set,t[i].add(n);return t}var Gf=3,Cw=An("source-facts",{clearGroups:["whole-project","source-file"]}),Hc=oe({kind:"source-facts",invalidation:K("source-facts"),serialize:vw,deserialize:Iw});function G(e,t){return Uc(e,t).facts}function Uc(e,t){let n=P(e,t);if(!n)return{facts:null};let r=xw(e,t,n);return r?Cw.get(e,t,n,()=>Rw(e,t,r,n)):{facts:null}}function xw(e,t,n){return Ht(t)?Go(e,t,n)?.language??null:M(t)}function Rw(e,t,n,r){let i=ce(e,t,r),o=Hc.read(e,t,i);if(o&&o.language===n)return{facts:o};if(n==="clojure"){let c=Wf(r);return Hc.write(e,t,i,c),{facts:c}}let s=q(e,t);if(!s)return{facts:null,unavailable:{language:n,reason:"parser-unavailable"}};let a=Dw(s,n);return Hc.write(e,t,i,a),{facts:a}}function vw(e){let t={version:Gf,language:e.language,callables:e.callables,callSites:e.callSites,clojureMembers:e.clojureMembers,typeContainerMap:[...e.typeContainerMap.entries()].map(([n,r])=>[n,[...r]]),identifierLineMap:[...e.identifierLineMap.entries()],rustAttrReferencedNames:[...e.rustAttrReferencedNames],crossLanguageDispatchNames:[...e.crossLanguageDispatchNames]};return JSON.stringify(t)}function Iw(e){try{let t=JSON.parse(e);if(t.version!==Gf||t.language==="clojure"&&(t.clojureMembers===void 0||t.callSites.some(r=>r.calleeText===void 0)))return null;let n=new Map(t.identifierLineMap);return{language:t.language,callables:t.callables,callSites:t.callSites,clojureMembers:t.clojureMembers??[],typeContainerMap:new Map(t.typeContainerMap.map(([r,i])=>[r,new Set(i)])),identifierLineMap:n,identifiersByLine:Oc(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function Wc(e,t,n,r){let i=G(e,t);return i?ww(i,n,r)?.isLiteralPassthrough??!0:!0}function gi(e,t){return t.relativePath.includes(".clj-kondo/hooks/")?!0:G(e,t.relativePath)?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine)?.clojureKind==="macro"}function ww(e,t,n){return e.callables.find(r=>r.startLine===t&&r.endLine===n)??null}function Dw(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=Vo(l,t);u&&n.push(u);let d=Sr(l,t);d&&r.push(d),$f(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&Hf(l.text,i),Of(l,t)&&a(l.text,l.startPosition.row),jf(l,t)&&Bf(l,a);for(let m of l.children)c(m)};return c(e.rootNode),{language:t,callables:n,callSites:r,clojureMembers:[],typeContainerMap:Uf(e,t),identifierLineMap:s,identifiersByLine:Oc(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:i,crossLanguageDispatchNames:o}}var zf=new Set(["rust","typescript","tsx","javascript","python","clojure"]);function Gc(e,t){let n=G(e,t);return!n||!zf.has(n.language)?null:n.callables.map(r=>({name:r.name,startLine:r.startLine,endLine:r.endLine}))}function gn(e,t){let n=G(e,t);return!n||!zf.has(n.language)?null:n.callSites}function zc(e,t){return G(e,t)?.typeContainerMap??new Map}import{ElementTypes as kw,NodeTypes as Vc,parse as Pw}from"@vue/compiler-dom";import{parse as oX}from"@vue/compiler-sfc";var Ew=new Set(["children","className","data","e","err","error","ev","event","false","id","idx","index","item","key","null","props","res","result","state","style","true","undefined","val","value"]);function Jo(e){return e.length<=2||Ew.has(e)}function Yo(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var Tw=mn("vue-template-facts"),_w=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),Fw=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"]),Lw=new Set(["div","span","template"]),Nw=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 Xo(e,t){let n=t.replace(/\\/g,"/"),r=P(e,n);return Tw.get(e,n,r,()=>Aw(n,br(e,n).template))}function Aw(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=Pw(t.body,{comments:!1})}catch{return n}let i=new Set,o=s=>{s.trim()&&i.add(s)};return qf(r.children,t.startLine,n,o),n.structuralTokens=[...i].sort(),n}function qf(e,t,n,r){for(let i of e)if(i.type===Vc.ELEMENT)Mw(i,t,n,r),qf(i.children,t,n,r);else if(i.type===Vc.INTERPOLATION){r("interpolation");let o=qc(i.content);o&&Kf(o,t,i.loc.start.line,n,r)}}function Mw(e,t,n,r){let i=Ww(e.tag),o={tag:e.tag,normalized:i,kind:Uw(e),startLine:Cr(t,e.loc.start.line),endLine:Cr(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),Lw.has(e.tag)||r(`native:${e.tag}`));for(let s of e.props)Ow(s,t,n,r)}function Ow(e,t,n,r){if(e.type===Vc.ATTRIBUTE){let a=e.value?.content??null,c=Vf("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),r(`prop:${e.name}`);return}let i=Bw(e),o=qc(e.exp),s=Vf(jw(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&&Kf(o,t,e.loc.start.line,n,r)}function Vf(e,t,n,r,i,o){return{kind:e,name:t,value:n,startLine:Cr(r,i),endLine:Cr(r,o)}}function jw(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function Bw(e){let t=qc(e.arg);return t||e.name}function qc(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function Kf(e,t,n,r,i){for(let o of $w(e)){let s={name:o,startLine:Cr(t,n),endLine:Cr(t,n)};r.expressionIdentifiers.push(s),i(`id:${o}`)}}function $w(e){let t=new Set,n=Hw(e),r=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,i;for(;i=r.exec(n);){let o=i[0];Nw.has(o)||Jo(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function Hw(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 Uw(e){let t=e.tag;return e.tagType===kw.COMPONENT?"component":_w.has(t)?"builtin":Fw.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function Ww(e){return Yo(e,/[-_:]/)}function Cr(e,t){return e+Math.max(0,t-1)}import{createRequire as tD}from"module";import{existsSync as Hn}from"fs";import{basename as Jf,dirname as qe,extname as Ut,join as it,relative as Bn,resolve as we,sep as nD}from"path";function N(e,t={}){let n=t.scope?"AND relative_path LIKE ?":"",r=t.like?"AND relative_path LIKE ?":"",i=[...t.scope?[`%${t.scope}%`]:[],...t.like?[t.like]:[]],o=e.all(`SELECT relative_path
|
|
96
96
|
FROM documents
|
|
97
97
|
WHERE 1 = 1
|
|
98
98
|
${e.pathExclusionsFor("documents")}
|
|
99
99
|
${n}
|
|
100
100
|
${r}
|
|
101
|
-
ORDER BY relative_path`,...i).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}import{isAbsolute as Gw,relative as zw}from"path";function
|
|
102
|
-
`)))}import{readdirSync as BD}from"fs";import{execFileSync as $D}from"child_process";import{extname as ss,join as HD}from"path";var UD=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".clj",".cljs",".cljc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],
|
|
103
|
-
`)){let o=i.trim();o&&(YD(o)||t.has(ss(o).toLowerCase())&&r.add(o))}return r}catch{return null}}function YD(e){return e.split("/").some(t=>sp.has(t))}function XD(e,t){let n=new Set,r=i=>{let o=i?HD(e,i):e,s;try{s=BD(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!sp.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(ss(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}var QD=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),ZD=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),eE=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),tE=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),nE=new Set(["catch","for","function","if","return","switch","while"]);function ls(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+=
|
|
104
|
-
`).length:0,u=
|
|
105
|
-
`).length:0)},0),paths:i}}function fE(e){let t=pE(e.scriptFacts);return{...e,scriptFacts:t,templateTokens:new Set(e.templateTokens),behaviorTokens:new Set(e.behaviorTokens),templateBindingNames:[...e.templateBindingNames],templateLocalNames:[...e.templateLocalNames],componentNames:[...e.componentNames],externalScriptPaths:t.externalScriptPaths,delegatedComposablePaths:[...e.delegatedComposablePaths]}}function pE(e){return{...e,imports:e.imports.map(t=>({...t})),functions:e.functions.map(t=>({...t})),calls:e.calls.map(t=>({...t,categories:[...t.categories]})),composables:[...e.composables],stores:[...e.stores],reactivity:[...e.reactivity],lifecycle:[...e.lifecycle],requests:[...e.requests],macros:[...e.macros],externalScriptPaths:[...e.externalScriptPaths],unresolvedScripts:e.unresolvedScripts.map(t=>({...t}))}}function gE(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(lE.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 hE(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let r of yE(n.value))t.add(r);for(let n of e.slots)if(n.value)for(let r of up(n.value))t.add(r);return[...t].sort()}function yE(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?up(t[1]??""):[]}function up(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];cE.has(r)||t.push(r)}return t}import{extname as bE}from"path";function It(e){return typeof e=="object"&&e!==null}function Me(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")?e:null}var SE=[".tsx",".jsx"],dp=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),CE=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),xE=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),RE=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),vE=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),IE=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),wE=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]),DE=dn("react-component-behavior-profiles"),mp=oe({kind:"react-component-behavior-profiles",invalidation:K("react-component-behavior-profiles"),serialize:TE,deserialize:_E});function hp(e,t={}){let n=$e(e,{extensions:SE}).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=>ll(e,i)).filter(i=>(t.minJsxTokens===void 0||i.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function ll(e,t){let n=t.replace(/\\/g,"/"),r=P(e,n);return DE.get(e,n,r,()=>EE(e,n,r)).map(PE)}function EE(e,t,n){let r=ce(e,t,n),i=mp.read(e,t,r);if(i)return i;let o=kE(e,t);return mp.write(e,t,r,o),o}function kE(e,t){let n=LE(t);if(!n)return[];let r=q(e,t);if(!r)return[];let i=Ce(e,t).length;return NE(r.rootNode,n).filter(s=>s.kind==="hook"||ul(s.bodyNode)).map(s=>{let a=HE(s.bodyNode),c=VE(s.bodyNode,n);return{file:t,name:s.name,kind:s.kind,startLine:s.node.startPosition.row,endLine:s.node.endPosition.row,loc:Math.max(1,s.node.endPosition.row-s.node.startPosition.row+1),fileLines:i,jsxTokens:a.tokens,behaviorTokens:c.tokens,componentNames:zt(a.componentNames),nativeTags:zt(a.nativeTags),propNames:zt(a.propNames),eventNames:zt(a.eventNames),hookNames:zt(c.hookNames),requestNames:zt(c.requestNames),stateNames:zt(c.stateNames),effectNames:zt(c.effectNames),handlerNames:zt(c.handlerNames)}})}function PE(e){return{...e,jsxTokens:new Set(e.jsxTokens),behaviorTokens:new Set(e.behaviorTokens),componentNames:[...e.componentNames],nativeTags:[...e.nativeTags],propNames:[...e.propNames],eventNames:[...e.eventNames],hookNames:[...e.hookNames],requestNames:[...e.requestNames],stateNames:[...e.stateNames],effectNames:[...e.effectNames],handlerNames:[...e.handlerNames]}}function TE(e){return JSON.stringify(e.map(t=>({...t,jsxTokens:[...t.jsxTokens],behaviorTokens:[...t.behaviorTokens]})))}function _E(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=[];for(let r of t){let i=FE(r);if(!i)return null;n.push(i)}return n}catch{return null}}function FE(e){if(!It(e))return null;let{file:t,name:n,kind:r,startLine:i,endLine:o,loc:s,fileLines:a,jsxTokens:c,behaviorTokens:l,componentNames:u,nativeTags:d,propNames:m,eventNames:f,hookNames:p,requestNames:g,stateNames:y,effectNames:h,handlerNames:C}=e;if(typeof t!="string"||typeof n!="string"||r!=="component"&&r!=="hook"||!us(i)||!us(o)||!us(s)||!us(a))return null;let x={jsxTokens:Me(c),behaviorTokens:Me(l),componentNames:Me(u),nativeTags:Me(d),propNames:Me(m),eventNames:Me(f),hookNames:Me(p),requestNames:Me(g),stateNames:Me(y),effectNames:Me(h),handlerNames:Me(C)};return Object.values(x).some(S=>S===null)?null:{file:t,name:n,kind:r,startLine:i,endLine:o,loc:s,fileLines:a,jsxTokens:new Set(x.jsxTokens),behaviorTokens:new Set(x.behaviorTokens),componentNames:x.componentNames,nativeTags:x.nativeTags,propNames:x.propNames,eventNames:x.eventNames,hookNames:x.hookNames,requestNames:x.requestNames,stateNames:x.stateNames,effectNames:x.effectNames,handlerNames:x.handlerNames}}function us(e){return typeof e=="number"&&Number.isFinite(e)}function LE(e){let t=bE(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:M(e)}function NE(e,t){let n=[],r=new Set,i=o=>{let s=AE(o);if(s&&(!BE(o)||s.kind==="component")){let a=`${s.name}:${s.node.startIndex}:${s.node.endIndex}`;r.has(a)||(r.add(a),n.push(s))}for(let a of o.namedChildren)i(a)};return(t==="tsx"||t==="javascript")&&i(e),n}function AE(e){if(e.type==="class_declaration"){let o=cl(e);if(!o||!/^[A-Z]/.test(o))return null;let s=ME(e);return!s||!OE(e)&&!ul(s)?null:{name:o,kind:"component",node:e,bodyNode:s}}if(e.type==="function_declaration"){let o=cl(e);return!o||!fp(o)?null:{name:o,kind:pp(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=yi(t);if(!r||!n||!fp(r))return null;let i=jE(n);return i?{name:r,kind:pp(r),node:e,bodyNode:i}:null}function ME(e){for(let t of e.namedChildren)if(t.type==="class_body")for(let n of t.namedChildren){if(n.type!=="method_definition")continue;if((n.childForFieldName("name")??n.namedChild(0))?.text==="render")return n}return null}function OE(e){return/\b(?:React\.)?(?:Pure)?Component\b/.test(e.text)}function fp(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function pp(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function jE(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=$E(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 BE(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 yi(e.childForFieldName("name")??e.namedChild(0))}function $E(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function ul(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(ul)}function HE(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"?UE(r,t):r.type==="jsx_element"&&r.text.trimStart().startsWith("<>")?t.tokens.add("jsx:fragment"):r.type==="jsx_expression"?WE(r,t):r.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let i of r.children)n(i)};return n(e),t}function UE(e,t){let n=GE(e),r=!1;if(n){let i=gp(n),o=i==="Fragment"||i==="React.Fragment";r=XE(i)&&!o,o?t.tokens.add("jsx:fragment"):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=zE(i);if(!o)continue;let s=gp(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 wE.has(s)||(t.propNames.add(s),t.tokens.add(`${r?"prop":"native-prop"}:${s}`))}else i.type==="jsx_spread_attribute"&&t.tokens.add(yp(i))}function WE(e,t){let n=e.text;/^\{\s*\.\.\./.test(n)&&t.tokens.add(yp(e)),bp(e)&&t.tokens.add("jsx:conditional"),(n.includes(".map(")||n.includes(".flatMap("))&&t.tokens.add("jsx:list");for(let r of QE(n))Jo(r)||t.tokens.add(`binding:${r}`)}function yp(e){let t=/^\{\s*\.\.\.\s*([^}]+)\s*\}$/.exec(e.text)?.[1],n=e.namedChildren.find(o=>o.type!=="comment"),r=t??n?.text??"",i=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.exec(r.trim())?.[0];return i?`prop:spread:${i}`:"prop:spread"}function bp(e){return e.type==="ternary_expression"||e.type==="conditional_expression"?!0:e.namedChildren.some(bp)}function GE(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 zE(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 VE(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=Sr(i,t);o&&qE(o.calleeLeaf,n)}else if(i.type==="variable_declarator")JE(i,n);else if(i.type==="function_declaration"){let o=cl(i);o&&Sp(o,n)}for(let o of i.namedChildren)r(o)};return r(e),n}function qE(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!dp.has(e)&&!RE.has(e)&&t.tokens.add(`hook:${e}`)),dp.has(e)&&t.tokens.add(`react-hook:${e}`),CE.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),xE.has(e)&&t.tokens.add(`state-hook:${e}`),KE(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function KE(e){if(vE.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function JE(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=>yi(a)),s=yi(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let i=yi(n);i&&Sp(i,t)}function Sp(e,t){let n=YE(e);!n||!IE.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function YE(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 XE(e){return/^[A-Z]/.test(e)||e.includes(".")}function gp(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function yi(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 QE(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 zt(e){return[...e].sort()}function nt(e){return{capability:(t,n)=>ZE(t,n),reactProfiles:(t={})=>hp(e,t),reactProfilesForFile:t=>ll(e,t),vueProfiles:(t={})=>lp(e,t),vueProfileForFile:t=>al(e,t),vueTemplateFacts:t=>Xo(e,t),vueScriptFacts:t=>ls(br(e,t))}}function ZE(e,t){let n=e.startsWith("react-")?"react":"vue";if(t===void 0)return{slot:e,available:!0,framework:n};let r=t.replace(/\\/g,"/").toLowerCase();return n==="react"&&!r.endsWith(".tsx")&&!r.endsWith(".jsx")?{slot:e,available:!1,framework:n,reason:"React behavior profiles are only available for .tsx and .jsx files"}:n==="vue"&&!r.endsWith(".vue")?{slot:e,available:!1,framework:n,reason:"Vue behavior facts are only available for .vue files"}:{slot:e,available:!0,framework:n}}function Un(e,t,n={}){let r=G(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}import{basename as Rp}from"path";function $(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(e){return e.replace(/'''[\s\S]*?'''/g,yn).replace(/"""[\s\S]*?"""/g,yn).replace(/#.*$/gm,yn).replace(/\/\/.*$/gm,yn).replace(/\/\*[\s\S]*?\*\//g,yn).replace(/`(?:\\[\s\S]|[^`])*`/g,yn).replace(/'(?:\\.|[^'\\\r\n])*'/g,yn).replace(/"(?:\\.|[^"\\\r\n])*"/g,yn)}function Si(e){return xp(e,{maskStrings:!1})}function Cp(e){return xp(e,{maskStrings:!0})}function xp(e,t){let n="",r=0,i=e.length;for(;r<i;){if(e[r]==="/"&&e[r+1]==="/"){let s=e.indexOf(`
|
|
101
|
+
ORDER BY relative_path`,...i).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}import{isAbsolute as Gw,relative as zw}from"path";function hn(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function te(e){return e.replace(/\\/g,"/")}function Ve(e,t){return hn(e)===hn(t)}function pX(e,t){let n=zw(e,t);return n===""||!n.startsWith("..")&&!Gw(n)}import{existsSync as Jc,readFileSync as Yc,readdirSync as Vw,statSync as qw}from"fs";import{join as xr,relative as Kw}from"path";function Rr(e){let t=Jw(e)??Zw(e);if(!t||t.length===0)return[];let n=[],r=new Set;for(let i of t)for(let o of Xc(e,i)){if(r.has(o))continue;r.add(o);let s=eD(e,o);s&&n.push(s)}return n}function Jw(e){let t=xr(e,"pnpm-workspace.yaml");if(!Jc(t))return null;try{return Yw(Yc(t,"utf8"))}catch{return null}}function Yw(e){let t=[],n=!1;for(let r of e.split(/\r?\n/)){let i=Xw(r);if(!n){/^packages\s*:\s*$/.test(i.trim())&&(n=!0);continue}let o=/^\s+-\s*(.+)$/.exec(i);if(o){let s=Qw(o[1].trim());s&&t.push(s);continue}if(i.trim()!=="")break}return t}function Xw(e){let t=e.indexOf("#");return t===-1?e:e.slice(0,t)}function Qw(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Zw(e){let t=xr(e,"package.json");if(!Jc(t))return null;try{let n=JSON.parse(Yc(t,"utf8"));return n.workspaces?Array.isArray(n.workspaces)?n.workspaces:n.workspaces.packages??[]:null}catch{return null}}function Xc(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=xr(e,t);return Kc(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=xr(e,r||".");return Kc(o)?Vw(o).map(s=>xr(o,s,i)).filter(Kc):[]}function Kc(e){try{return qw(e).isDirectory()}catch{return!1}}function eD(e,t){let n=xr(t,"package.json");if(!Jc(n))return null;try{let r=JSON.parse(Yc(n,"utf8"));return typeof r.name!="string"||r.name.length===0?null:{name:r.name,relativeDir:Kw(e,t).replace(/\\/g,"/"),exports:r.exports}}catch{return null}}var rD=J("indexed-paths",{clearGroups:[]}),iD=J("indexed-path-digest",{clearGroups:[]}),oD=j("tsconfig-alias-config",{clearGroups:["whole-project"]}),sD=j("tsconfig-alias-config-for-dir",{clearGroups:["whole-project"]}),aD=tD(import.meta.url),hi;function cD(){if(hi!==void 0)return hi;try{hi=aD("typescript")}catch{hi=null}return hi}var lD=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"],uD=J("workspace-packages",{clearGroups:["whole-project"]}),$n=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],Qo=[".py",".pyi"],Ke=[".java",".scala",".kt",".kts"],Zo=[".rs"],es=[".rb"],ts=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],yn=[".cs",".vb"],ns=[".dart"],Un=[".php"],vr=[".clj",".cljs",".cljc"],dD=new Set($n),Qc=new Set(Qo),Yf=new Set(Ke),Zc=new Set(Zo),el=new Set(es),Xf=new Set(ts),Qf=new Set(yn),tl=new Set(ns),Zf=new Set(Un),ep=new Set(vr),mD=[{extensions:$n,lookup:dD},{extensions:Qo,lookup:Qc},{extensions:Ke,lookup:Yf},{extensions:Zo,lookup:Zc},{extensions:es,lookup:el},{extensions:ts,lookup:Xf},{extensions:yn,lookup:Qf},{extensions:ns,lookup:tl},{extensions:Un,lookup:Zf},{extensions:vr,lookup:ep}];function Wt(e,t){return t.has(Ut(e).toLowerCase())}function fD(e){return Wt(e,Qc)}function pD(e){return Wt(e,Yf)}function gD(e){return Wt(e,Zc)}function hD(e){return Wt(e,el)}function yD(e){return Wt(e,Xf)}function bD(e){return Wt(e,Qf)}function tp(e){return Ut(e).toLowerCase()===".vb"}function SD(e){return Wt(e,tl)}function CD(e){return Wt(e,Zf)}function xD(e){return Wt(e,ep)}function nl(e){let t=Ut(e).toLowerCase();for(let n of mD)if(n.lookup.has(t))return n.extensions;return $n}function RD(e){return pD(e)||bD(e)||CD(e)}function Je(e,t,n){return fD(t)?Ir(e,t,n):gD(t)?Gt(e,t,n):hD(t)?rs(e,t,n):yD(t)?is(e,t,n):RD(t)?be(e,n.replace(/\\/g,"."),nl(t)):SD(t)?os(e,t,n):xD(t)?rl(e,n):vD(e,t,n)}function vD(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return ID(e,t,n)??DD(e,n);let r=qe(it(e.config.projectRoot,t)),i=we(r,n),o=zt(e);for(let s of ol(i)){let a=te(Bn(e.config.projectRoot,s));if(o.has(a)||Hn(s))return a}return te(Bn(e.config.projectRoot,i))}function ID(e,t,n){let r=FD(e,t);if(!r)return null;let i=zt(e);for(let o of wD(r,n)){let s=we(r.baseUrl,o);for(let a of ol(s)){let c=te(Bn(e.config.projectRoot,a));if(i.has(c)||Hn(a))return c}}return null}function wD(e,t){let n=[];for(let[r,i]of Object.entries(e.paths)){let o=r.indexOf("*");if(o===-1){if(t!==r)continue;n.push(...i);continue}let s=r.slice(0,o),a=r.slice(o+1);if(!t.startsWith(s)||!t.endsWith(a)||t.length<s.length+a.length)continue;let c=t.slice(s.length,t.length-a.length);for(let l of i)n.push(l.includes("*")?l.replace("*",c):l)}return n}function DD(e,t){let n=kD(ED(e),t);if(!n)return null;let r=zt(e);for(let i of PD(n)){let o=we(e.config.projectRoot,n.pkg.relativeDir,i);for(let s of ol(o)){let a=te(Bn(e.config.projectRoot,s));if(r.has(a)||Hn(s))return a}}return null}function ED(e){return uD.get(e,()=>Rr(e.config.projectRoot))}function kD(e,t){let n=null;for(let r of e){let i=null;t===r.name?i="":t.startsWith(`${r.name}/`)&&(i=t.slice(r.name.length+1)),i!==null&&(!n||r.name.length>n.pkg.name.length)&&(n={pkg:r,subpath:i})}return n}function PD(e){let t=[],n=TD(e.pkg.exports,e.subpath);if(n){let r=_D(n);r&&t.push(r)}return t.push(e.subpath?`src/${e.subpath}`:"src/index"),t}function TD(e,t){if(!e||typeof e!="object")return null;let n=t===""?".":`./${t}`;return np(e[n])}function np(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return null;let t=e;for(let n of["types","import","default","require","node"]){let r=np(t[n]);if(r)return r}return null}function _D(e){let t=e.replace(/^\.\//,"");return t.startsWith("dist/")?`src/${t.slice(5)}`:null}function FD(e,t){let n=te(qe(t));return sD.get(e,n,()=>LD(e,n))}function LD(e,t){let n=cD();if(!n)return null;let r=we(e.config.projectRoot),i=we(r,t);for(;i===r||i.startsWith(r+nD);){for(let s of lD){let a=it(i,s);if(!Hn(a))continue;let c=oD.get(e,a,()=>ND(n,a));if(c)return c}let o=qe(i);if(o===i)break;i=o}return null}function ND(e,t){try{let n=e.readConfigFile(t,e.sys.readFile);if(n.error||!n.config)return null;let r=e.parseJsonConfigFileContent(n.config,e.sys,qe(t)),i=r.options.paths;return!i||Object.keys(i).length===0?null:{baseUrl:r.options.baseUrl?we(qe(t),r.options.baseUrl):qe(t),paths:i}}catch{return null}}function Ir(e,t,n){let r=zt(e),i;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=qe(it(e.config.projectRoot,t));for(let l=1;l<s;l++)c=qe(c);i=a?we(c,a.replace(/\./g,"/")):c}else i=we(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of AD(i)){let s=te(Bn(e.config.projectRoot,o));if(r.has(s)||Hn(o))return s}return null}function Gt(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=qe(it(e.config.projectRoot,t)),o;return r.startsWith("crate::")?o=we(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?o=we(i,r.slice(6).replace(/::/g,"/")):o=we(qe(i),r.slice(7).replace(/::/g,"/")),il(e,MD(o))}function rs(e,t,n){let r=qe(it(e.config.projectRoot,t)),i=we(r,n);return il(e,OD(i))}function is(e,t,n){let r=qe(it(e.config.projectRoot,t)),i=[we(r,n),we(e.config.projectRoot,n),we(e.config.projectRoot,"include",n),we(e.config.projectRoot,"src",n)];return il(e,i)}function be(e,t,n){let r=zt(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=>Jf(u)===`${s}${c}`);if(l)return l}let a=[...r].filter(c=>n.includes(Ut(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function os(e,t,n){let r=zt(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=te(c.startsWith("lib/")?c:`lib/${c}`);return r.has(l)?l:null}let i=qe(it(e.config.projectRoot,t)),o=we(i,n);for(let s of jD(o)){let a=te(Bn(e.config.projectRoot,s));if(r.has(a)||Hn(s))return a}return null}function rl(e,t){let n=t.replace(/-/g,"_").replace(/\./g,"/"),r=zt(e);for(let i of vr){let o=`${n}${i}`,s=[...r].find(a=>a.endsWith(o));if(s)return s}for(let i of vr){let o=[...r].find(s=>Jf(s)===`${n.split("/").pop()}${i}`);if(o)return o}return null}function AD(e){let t=Ut(e);return Qc.has(t)?[e]:[`${e}.py`,`${e}.pyi`,it(e,"__init__.py"),it(e,"__init__.pyi")]}function il(e,t){let n=zt(e);for(let r of t){let i=te(Bn(e.config.projectRoot,r));if(n.has(i)||Hn(r))return i}return null}function MD(e){let t=Ut(e);return Zc.has(t)?[e]:[`${e}.rs`,it(e,"mod.rs")]}function OD(e){let t=Ut(e);return el.has(t)?[e]:[`${e}.rb`,it(e,"index.rb")]}function jD(e){let t=Ut(e);return tl.has(t)?[e]:[`${e}.dart`,e]}function ol(e){let t=Ut(e),n=new Set;if(t){n.add(e);for(let r of $n)n.add(e.slice(0,-t.length)+r)}else for(let r of $n)n.add(`${e}${r}`),n.add(it(e,`index${r}`));return[...n]}function zt(e){return rD.get(e,()=>new Set(N(e,{includeIgnored:!1}).map(te)))}function sl(e){return iD.get(e,()=>he([...zt(e)].sort().join(`
|
|
102
|
+
`)))}import{readdirSync as BD}from"fs";import{execFileSync as $D}from"child_process";import{extname as ss,join as HD}from"path";var UD=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".clj",".cljs",".cljc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],LX=[".vue"],rp=[".tsx",".jsx"],ip=[".vue"],WD=[...rp,...ip],GD=new Set(rp),zD=new Set(ip),op=new Set(UD.map(e=>e.toLowerCase())),VD=[...op].sort().join(","),sp=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo",".nbb",".cpcache",".shadow-cljs","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function $e(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(c=>c.toLowerCase()),o=i?new Set(i):op,s=i?[...o].sort().join(","):VD,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return qD.get(e,a,()=>{let c=new Set;if(n)for(let l of N(e,{includeIgnored:!1}))o.has(ss(l).toLowerCase())&&c.add(l);if(r)for(let l of KD(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}function as(e,t={}){let n=!1,r=!1;for(let i of $e(e,{extensions:WD})){if(t.scope&&!i.includes(t.scope))continue;let o=ss(i).toLowerCase();if(n||=GD.has(o),r||=zD.has(o),n&&r)break}return{react:n,vue:r}}var qD=j("source-files",{clearGroups:[]});function KD(e,t){return JD(e,t)??XD(e,t)}function JD(e,t){try{let n=$D("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(`
|
|
103
|
+
`)){let o=i.trim();o&&(YD(o)||t.has(ss(o).toLowerCase())&&r.add(o))}return r}catch{return null}}function YD(e){return e.split("/").some(t=>sp.has(t))}function XD(e,t){let n=new Set,r=i=>{let o=i?HD(e,i):e,s;try{s=BD(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!sp.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(ss(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}var QD=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),ZD=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),eE=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),tE=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),nE=new Set(["catch","for","function","if","return","switch","while"]);function ls(e){let t={imports:[],functions:[],calls:[],composables:[],stores:[],reactivity:[],lifecycle:[],requests:[],macros:[],lineCount:0,externalLineCount:0,externalScriptPaths:[],unresolvedScripts:[]};for(let n of e.scripts){t.lineCount+=Mn(n),n.external&&(t.externalLineCount+=Mn(n),t.externalScriptPaths.push(n.sourcePath));for(let 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(...sE(n));let r=ui(n.astLanguage,n.body);r?iE(n,r.rootNode,t):oE(n,t)}return rE(t),t.externalScriptPaths=cp(t.externalScriptPaths),t}function rE(e){e.composables=wr(e,"composable"),e.stores=wr(e,"store"),e.reactivity=wr(e,"reactivity"),e.lifecycle=wr(e,"lifecycle"),e.requests=wr(e,"request"),e.macros=wr(e,"macro")}function wr(e,t){return cp(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function iE(e,t,n){let r=new Set,i=new Set,o=s=>{let a=Vo(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=Sr(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:ap(c.calleeLeaf),setup:e.setup}))}for(let l of s.children)o(l)};o(t)}function oE(e,t){for(let n of e.body.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)){let r=n[1];!r||nE.has(r)||t.calls.push({name:r,sourcePath:e.sourcePath,line:e.startLine+cs(e.body,n.index??0),categories:ap(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+cs(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+cs(e.body,n.index??0);t.functions.push({name:r,sourcePath:e.sourcePath,startLine:i,endLine:i,setup:e.setup})}}function sE(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+cs(e.body,n.index??0);for(let s of aE(r))t.push({local:s,source:i,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function aE(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 ap(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),QD.has(e)&&t.push("reactivity"),ZD.has(e)&&t.push("lifecycle"),eE.has(e)&&t.push("request"),tE.has(e)&&t.push("macro"),t}function cs(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 cp(e){return[...new Set(e)].sort()}var cE=new Set(["in","key","of"]),lE=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]),uE=mn("vue-component-behavior-profiles");function lp(e,t={}){let n=$e(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=>al(e,i)).filter(i=>(t.minTemplateTokens===void 0||i.templateTokens.size>=t.minTemplateTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function al(e,t){let n=t.replace(/\\/g,"/"),r=P(e,n),i=uE.get(e,n,r,()=>dE(e,n,r));return fE(i)}function dE(e,t,n){let r=br(e,t),i=Xo(e,t),o=ls(r),s=hE(i),a=i.expressionIdentifiers.map(y=>y.name).filter(y=>!s.includes(y)).filter((y,h,C)=>C.indexOf(y)===h).sort(),c=i.componentTags.map(y=>y.normalized).filter((y,h,C)=>C.indexOf(y)===h).sort(),l=n?n.split(`
|
|
104
|
+
`).length:0,u=Mn(r.template),d=o.lineCount,m=r.styles.reduce((y,h)=>y+Mn(h),0),f=r.customBlocks.reduce((y,h)=>y+Mn(h),0),{lines:p,paths:g}=mE(e,t,o);return{file:t,sfc:r,templateFacts:i,scriptFacts:o,templateTokens:new Set(i.structuralTokens),behaviorTokens:gE(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,delegatedComposableLines:p,delegatedComposablePaths:g}}function mE(e,t,n){let r=new Set;for(let s of n.composables){let a=n.imports.find(l=>l.local===s);if(!a)continue;let c=Je(e,a.sourcePath,a.source);!c||c===t||r.add(c)}let i=[...r].sort();return{lines:i.reduce((s,a)=>{let c=P(e,a);return s+(c?c.split(`
|
|
105
|
+
`).length:0)},0),paths:i}}function fE(e){let t=pE(e.scriptFacts);return{...e,scriptFacts:t,templateTokens:new Set(e.templateTokens),behaviorTokens:new Set(e.behaviorTokens),templateBindingNames:[...e.templateBindingNames],templateLocalNames:[...e.templateLocalNames],componentNames:[...e.componentNames],externalScriptPaths:t.externalScriptPaths,delegatedComposablePaths:[...e.delegatedComposablePaths]}}function pE(e){return{...e,imports:e.imports.map(t=>({...t})),functions:e.functions.map(t=>({...t})),calls:e.calls.map(t=>({...t,categories:[...t.categories]})),composables:[...e.composables],stores:[...e.stores],reactivity:[...e.reactivity],lifecycle:[...e.lifecycle],requests:[...e.requests],macros:[...e.macros],externalScriptPaths:[...e.externalScriptPaths],unresolvedScripts:e.unresolvedScripts.map(t=>({...t}))}}function gE(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(lE.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 hE(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let r of yE(n.value))t.add(r);for(let n of e.slots)if(n.value)for(let r of up(n.value))t.add(r);return[...t].sort()}function yE(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?up(t[1]??""):[]}function up(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];cE.has(r)||t.push(r)}return t}import{extname as bE}from"path";function wt(e){return typeof e=="object"&&e!==null}function Me(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")?e:null}var SE=[".tsx",".jsx"],dp=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),CE=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),xE=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),RE=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),vE=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),IE=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),wE=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]),DE=mn("react-component-behavior-profiles"),mp=oe({kind:"react-component-behavior-profiles",invalidation:K("react-component-behavior-profiles"),serialize:TE,deserialize:_E});function hp(e,t={}){let n=$e(e,{extensions:SE}).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=>ll(e,i)).filter(i=>(t.minJsxTokens===void 0||i.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function ll(e,t){let n=t.replace(/\\/g,"/"),r=P(e,n);return DE.get(e,n,r,()=>EE(e,n,r)).map(PE)}function EE(e,t,n){let r=ce(e,t,n),i=mp.read(e,t,r);if(i)return i;let o=kE(e,t);return mp.write(e,t,r,o),o}function kE(e,t){let n=LE(t);if(!n)return[];let r=q(e,t);if(!r)return[];let i=Ce(e,t).length;return NE(r.rootNode,n).filter(s=>s.kind==="hook"||ul(s.bodyNode)).map(s=>{let a=HE(s.bodyNode),c=VE(s.bodyNode,n);return{file:t,name:s.name,kind:s.kind,startLine:s.node.startPosition.row,endLine:s.node.endPosition.row,loc:Math.max(1,s.node.endPosition.row-s.node.startPosition.row+1),fileLines:i,jsxTokens:a.tokens,behaviorTokens:c.tokens,componentNames:Vt(a.componentNames),nativeTags:Vt(a.nativeTags),propNames:Vt(a.propNames),eventNames:Vt(a.eventNames),hookNames:Vt(c.hookNames),requestNames:Vt(c.requestNames),stateNames:Vt(c.stateNames),effectNames:Vt(c.effectNames),handlerNames:Vt(c.handlerNames)}})}function PE(e){return{...e,jsxTokens:new Set(e.jsxTokens),behaviorTokens:new Set(e.behaviorTokens),componentNames:[...e.componentNames],nativeTags:[...e.nativeTags],propNames:[...e.propNames],eventNames:[...e.eventNames],hookNames:[...e.hookNames],requestNames:[...e.requestNames],stateNames:[...e.stateNames],effectNames:[...e.effectNames],handlerNames:[...e.handlerNames]}}function TE(e){return JSON.stringify(e.map(t=>({...t,jsxTokens:[...t.jsxTokens],behaviorTokens:[...t.behaviorTokens]})))}function _E(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=[];for(let r of t){let i=FE(r);if(!i)return null;n.push(i)}return n}catch{return null}}function FE(e){if(!wt(e))return null;let{file:t,name:n,kind:r,startLine:i,endLine:o,loc:s,fileLines:a,jsxTokens:c,behaviorTokens:l,componentNames:u,nativeTags:d,propNames:m,eventNames:f,hookNames:p,requestNames:g,stateNames:y,effectNames:h,handlerNames:C}=e;if(typeof t!="string"||typeof n!="string"||r!=="component"&&r!=="hook"||!us(i)||!us(o)||!us(s)||!us(a))return null;let x={jsxTokens:Me(c),behaviorTokens:Me(l),componentNames:Me(u),nativeTags:Me(d),propNames:Me(m),eventNames:Me(f),hookNames:Me(p),requestNames:Me(g),stateNames:Me(y),effectNames:Me(h),handlerNames:Me(C)};return Object.values(x).some(S=>S===null)?null:{file:t,name:n,kind:r,startLine:i,endLine:o,loc:s,fileLines:a,jsxTokens:new Set(x.jsxTokens),behaviorTokens:new Set(x.behaviorTokens),componentNames:x.componentNames,nativeTags:x.nativeTags,propNames:x.propNames,eventNames:x.eventNames,hookNames:x.hookNames,requestNames:x.requestNames,stateNames:x.stateNames,effectNames:x.effectNames,handlerNames:x.handlerNames}}function us(e){return typeof e=="number"&&Number.isFinite(e)}function LE(e){let t=bE(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:M(e)}function NE(e,t){let n=[],r=new Set,i=o=>{let s=AE(o);if(s&&(!BE(o)||s.kind==="component")){let a=`${s.name}:${s.node.startIndex}:${s.node.endIndex}`;r.has(a)||(r.add(a),n.push(s))}for(let a of o.namedChildren)i(a)};return(t==="tsx"||t==="javascript")&&i(e),n}function AE(e){if(e.type==="class_declaration"){let o=cl(e);if(!o||!/^[A-Z]/.test(o))return null;let s=ME(e);return!s||!OE(e)&&!ul(s)?null:{name:o,kind:"component",node:e,bodyNode:s}}if(e.type==="function_declaration"){let o=cl(e);return!o||!fp(o)?null:{name:o,kind:pp(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=yi(t);if(!r||!n||!fp(r))return null;let i=jE(n);return i?{name:r,kind:pp(r),node:e,bodyNode:i}:null}function ME(e){for(let t of e.namedChildren)if(t.type==="class_body")for(let n of t.namedChildren){if(n.type!=="method_definition")continue;if((n.childForFieldName("name")??n.namedChild(0))?.text==="render")return n}return null}function OE(e){return/\b(?:React\.)?(?:Pure)?Component\b/.test(e.text)}function fp(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function pp(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function jE(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=$E(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 BE(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 yi(e.childForFieldName("name")??e.namedChild(0))}function $E(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function ul(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(ul)}function HE(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"?UE(r,t):r.type==="jsx_element"&&r.text.trimStart().startsWith("<>")?t.tokens.add("jsx:fragment"):r.type==="jsx_expression"?WE(r,t):r.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let i of r.children)n(i)};return n(e),t}function UE(e,t){let n=GE(e),r=!1;if(n){let i=gp(n),o=i==="Fragment"||i==="React.Fragment";r=XE(i)&&!o,o?t.tokens.add("jsx:fragment"):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=zE(i);if(!o)continue;let s=gp(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 wE.has(s)||(t.propNames.add(s),t.tokens.add(`${r?"prop":"native-prop"}:${s}`))}else i.type==="jsx_spread_attribute"&&t.tokens.add(yp(i))}function WE(e,t){let n=e.text;/^\{\s*\.\.\./.test(n)&&t.tokens.add(yp(e)),bp(e)&&t.tokens.add("jsx:conditional"),(n.includes(".map(")||n.includes(".flatMap("))&&t.tokens.add("jsx:list");for(let r of QE(n))Jo(r)||t.tokens.add(`binding:${r}`)}function yp(e){let t=/^\{\s*\.\.\.\s*([^}]+)\s*\}$/.exec(e.text)?.[1],n=e.namedChildren.find(o=>o.type!=="comment"),r=t??n?.text??"",i=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.exec(r.trim())?.[0];return i?`prop:spread:${i}`:"prop:spread"}function bp(e){return e.type==="ternary_expression"||e.type==="conditional_expression"?!0:e.namedChildren.some(bp)}function GE(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 zE(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 VE(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=Sr(i,t);o&&qE(o.calleeLeaf,n)}else if(i.type==="variable_declarator")JE(i,n);else if(i.type==="function_declaration"){let o=cl(i);o&&Sp(o,n)}for(let o of i.namedChildren)r(o)};return r(e),n}function qE(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!dp.has(e)&&!RE.has(e)&&t.tokens.add(`hook:${e}`)),dp.has(e)&&t.tokens.add(`react-hook:${e}`),CE.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),xE.has(e)&&t.tokens.add(`state-hook:${e}`),KE(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function KE(e){if(vE.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function JE(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=>yi(a)),s=yi(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let i=yi(n);i&&Sp(i,t)}function Sp(e,t){let n=YE(e);!n||!IE.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function YE(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 XE(e){return/^[A-Z]/.test(e)||e.includes(".")}function gp(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function yi(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 QE(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 Vt(e){return[...e].sort()}function ot(e){return{capability:(t,n)=>ZE(t,n),reactProfiles:(t={})=>hp(e,t),reactProfilesForFile:t=>ll(e,t),vueProfiles:(t={})=>lp(e,t),vueProfileForFile:t=>al(e,t),vueTemplateFacts:t=>Xo(e,t),vueScriptFacts:t=>ls(br(e,t))}}function ZE(e,t){let n=e.startsWith("react-")?"react":"vue";if(t===void 0)return{slot:e,available:!0,framework:n};let r=t.replace(/\\/g,"/").toLowerCase();return n==="react"&&!r.endsWith(".tsx")&&!r.endsWith(".jsx")?{slot:e,available:!1,framework:n,reason:"React behavior profiles are only available for .tsx and .jsx files"}:n==="vue"&&!r.endsWith(".vue")?{slot:e,available:!1,framework:n,reason:"Vue behavior facts are only available for .vue files"}:{slot:e,available:!0,framework:n}}function Wn(e,t,n={}){let r=G(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}import{basename as Rp}from"path";function $(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function st(e){return e.replace(/'''[\s\S]*?'''/g,bn).replace(/"""[\s\S]*?"""/g,bn).replace(/#.*$/gm,bn).replace(/\/\/.*$/gm,bn).replace(/\/\*[\s\S]*?\*\//g,bn).replace(/`(?:\\[\s\S]|[^`])*`/g,bn).replace(/'(?:\\.|[^'\\\r\n])*'/g,bn).replace(/"(?:\\.|[^"\\\r\n])*"/g,bn)}function Si(e){return xp(e,{maskStrings:!1})}function Cp(e){return xp(e,{maskStrings:!0})}function xp(e,t){let n="",r=0,i=e.length;for(;r<i;){if(e[r]==="/"&&e[r+1]==="/"){let s=e.indexOf(`
|
|
106
106
|
`,r),a=s===-1?i:s;n+=dl(e,r,a),r=a;continue}if(e[r]==="/"&&e[r+1]==="*"){let s=e.indexOf("*/",r+2),a=s===-1?i:s+2;n+=dl(e,r,a),r=a;continue}let o=e[r];if(o==="`"||o==="'"||o==='"'){let s=o,a=r+1;for(;a<i;){if(e[a]==="\\"){a+=2;continue}if(e[a]===s){a+=1;break}if(s!=="`"&&e[a]===`
|
|
107
107
|
`)break;a+=1}n+=t.maskStrings?dl(e,r,a):e.slice(r,a),r=a;continue}n+=o,r+=1}return n}function dl(e,t,n){let r="";for(let i=t;i<n;i+=1)r+=e[i]===`
|
|
108
108
|
`?`
|
|
109
|
-
`:" ";return r}function
|
|
109
|
+
`:" ";return r}function bn(e){return e.replace(/[^\r\n]/g," ")}var EQ=An("stripped-lines",{clearGroups:["whole-project","source-file"]});dn({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{ds=null,bi=""},clearFile:()=>{ds=null,bi=""}});var ds=null,bi="";function ek(e){return ds===e||(ds=e,bi=st(e)),bi}function Sn(e,t,n){let r=ek(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function He(e,t){return new RegExp(`\\b${$(t)}\\b`,"m").test(e)}function Dr(e,t){let n=new Set,r=new RegExp(`\\b${$(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 Ci(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var tk=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function Ue(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 Ye(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function Se(e,t){let n=new Set,r=(i,o)=>{let s=o||t.has(i.type);!s&&tk.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,s)};return r(e.rootNode,!1),n}function bt(e,t,n,r,i,o,s){return{importedName:i,localName:o,sourcePath:s??be(e,r,nl(t)),kind:"named",used:He(n,o),usedMembers:[]}}function pe(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 qt(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 Gn(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function zn(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 at(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=Sn(e,i.index,i.index+o.length);for(let a of n(i,s))r.push(a)}return r}function ct(e,t,n,r){let i=q(e,t);if(i){let o=n(i);if(o)return o}return r()}function ms(e,t,n,r){let i=q(e,t),o=M(t),s=o?n[o]:void 0;return i&&s?s(i):r()}function vp(e,t,n){return ct(e,t,r=>rk(e,t,r),()=>nk(e,t,n))}function nk(e,t,n){return at(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=Rp(o).replace(/\.[^.]+$/,"");return[qt(o,s,is(e,t,o),He(i,s))]})}function rk(e,t,n){let r=Se(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=Rp(s).replace(/\.[^.]+$/,"");i.push(pe(s,a,is(e,t,s),r))}return i}var ik=new Set([":require",":require-macros",":use"]),pl=String.raw`A-Za-z0-9_$*+!?.<>=-`;function wp(e,t,n){let r=gk(n);if(!r)return[];let i=pk(n,r.start,r.end),o=[];for(let s of r.children.slice(2)){if(s.type!=="list"||s.children.length===0)continue;let a=lt(s.children[0]);if(a){if(ik.has(a)){for(let c of ak(s.children.slice(1)))o.push(...sk(e,c,i));continue}if(a===":import")for(let c of lk(s.children.slice(1)))o.push(c)}}return o}function ok(e){return e.type==="list"&<(e.children[0])==="ns"}function sk(e,t,n){let r=rl(e,t.namespace),i=t.alias??t.namespace,o=dk(n,i),s=[{importedName:t.namespace,localName:i,sourcePath:r,kind:"namespace",used:t.refers.length>0||t.referAll||o.length>0||mk(n,t.namespace),usedMembers:o}];t.referAll&&s.push({importedName:"*",localName:null,sourcePath:r,kind:"side-effect",used:!0,usedMembers:[]});for(let a of t.refers)s.push({importedName:a,localName:a,sourcePath:r,kind:"named",used:fk(n,a),usedMembers:[]});return s}function ak(e){return e.flatMap(t=>fs(t,null))}function fs(e,t){if(e.type==="atom")return e.text.startsWith(":")?[]:[{namespace:fl(t,e.text),alias:null,refers:[],referAll:!1}];if(e.type==="vector")return e.children.length>0&<(e.children[0])===null?e.children.flatMap(n=>fs(n,t)):ck(e,t);if(e.type==="list"&&e.children.length>0){let n=lt(e.children[0]);return n?!n||n.startsWith(":")?[]:e.children.slice(1).flatMap(r=>fs(r,fl(t,n))):e.children.flatMap(r=>fs(r,t))}return[]}function ck(e,t){let n=lt(e.children[0]);if(!n||n.startsWith(":"))return[];let r={namespace:fl(t,n),alias:null,refers:[],referAll:!1};for(let i=1;i<e.children.length;i+=1){let o=lt(e.children[i]);if(!o?.startsWith(":"))continue;let s=e.children[i+1];if((o===":as"||o===":as-alias")&&s){r.alias=lt(s),i+=1;continue}o===":refer"&&s&&(lt(s)===":all"?r.referAll=!0:(s.type==="vector"||s.type==="list")&&r.refers.push(...s.children.map(lt).filter(uk)),i+=1)}return[r]}function lk(e){let t=[];for(let n of e){if(n.type==="atom"){let i=n.text.split(".").pop()??n.text;t.push(qt(i,i,null,!0));continue}if(n.type!=="vector")continue;let r=lt(n.children[0]);if(r)for(let i of n.children.slice(1)){let o=lt(i);o&&t.push(qt(`${r}.${o}`,o,null,!0))}}return t}function fl(e,t){return e?`${e}.${t}`:t}function lt(e){return e?.type==="atom"?e.text:null}function uk(e){return!!(e&&!e.startsWith(":"))}function dk(e,t){let n=new Set,r=new RegExp(`${gl()}${$(t)}\\s*/\\s*([${pl}]+)`,"g");for(let i of e.matchAll(r)){let o=i[1];o&&n.add(o)}return[...n]}function mk(e,t){return new RegExp(`${gl()}${$(t)}\\s*/`,"m").test(e)}function fk(e,t){return new RegExp(`${gl()}${$(t)}(?![${pl}])`,"m").test(e)}function gl(){return`(?<![${pl}])`}function pk(e,t,n){let r="",i=0;for(;i<e.length;){if(i>=t&&i<n){r+=e[i]===`
|
|
110
110
|
`?`
|
|
111
|
-
`:" ",i+=1;continue}let o=e[i];if(o===";"){let s=Ko(e,i);r+=Ip(e.slice(i,s)),i=s;continue}if(o==='"'){let s=pi(e,i,0).index;r+=Ip(e.slice(i,s)),i=s;continue}r+=o,i+=1}return r}function gk(e){let t=0;for(;t<e.length&&(t=hl(e,t),!(t>=e.length));){let n=ps(e,t);if(!n){t+=1;continue}if(ok(n.form))return n.form;t=n.index}return null}function ps(e,t){let n=hl(e,t);if(e.startsWith("#?@",n)||e.startsWith("#?",n))return hk(e,n);if(e.startsWith("#_",n)){let i=ps(e,n+2);return i?{form:{type:"atom",text:"",start:n,end:i.index},index:i.index}:null}for(;Bc(e[n]);)n+=1;let r=e[n];return r?r==="("?ml(e,n,"list",")"):r==="["?ml(e,n,"vector","]"):r==="{"?ml(e,n,"map","}"):r==='"'?{form:{type:"atom",text:"",start:n,end:pi(e,n,0).index},index:pi(e,n,0).index}:bk(e,n):null}function hk(e,t){let n=e.startsWith("#?@",t)?3:2,r=ps(e,t+n);return r?{form:{type:"list",children:r.form.type==="list"||r.form.type==="vector"||r.form.type==="map"?yk(r.form.children):[],start:t,end:r.index},index:r.index}:null}function yk(e){let t=[];for(let n=0;n<e.length;n+=2){let r=st(e[n]),i=e[n+1];r?.startsWith(":")&&i&&t.push(i)}return t}function ml(e,t,n,r){let i=[],o=t+1;for(;o<e.length;){if(o=hl(e,o),e[o]===r)return{form:{type:n,children:i,start:t,end:o+1},index:o+1};let s=ps(e,o);if(!s){o+=1;continue}s.form.type==="atom"&&s.form.text===""||i.push(s.form),o=s.index}return{form:{type:n,children:i,start:t,end:e.length},index:e.length}}function bk(e,t){let n=t;for(;n<e.length&&!$c(e[n]);)n+=1;return{form:{type:"atom",text:e.slice(t,n),start:t,end:n},index:n}}function hl(e,t){let n=t;for(;n<e.length;){let r=e[n];if(/\s|,/.test(r)){n+=1;continue}if(r===";"){n=Ko(e,n);continue}break}return n}function Ip(e){return e.replace(/[^\r\n]/g," ")}function Dp(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=bn(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:os(e,t,o),kind:s?"namespace":"side-effect",used:s?He(c,s):!0,usedMembers:s?Dr(c,s):[]})}return r}function Ep(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:os(e,t,o)})}return r}function kp(e,t,n){return ms(e,t,{csharp:r=>Ck(e,t,r),vb:r=>Sk(e,t,r)},()=>{let r=tp(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return it(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[ht(e,t,o,u,d,m,be(e,u,hn))]})})}function Sk(e,t,n){let r=Se(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(pe(u,d,be(e,l,hn),r,c?"namespace":"named"))}return i}function Ck(e,t,n){let r=Se(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(pe(u,d,be(e,l,hn),r,a?"namespace":"named"))}return i}var xk=j("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function Pp(e,t){return xk.get(e,t,()=>{let n=new Set,r=P(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 yl(e,t,n){return ot(e,t,r=>vk(e,t,r),()=>Rk(e,t,n))}function Rk(e,t,n){return Nk(n).flatMap(r=>Ak(e,t,r.clause,r.specifier,r.start,r.end,n))}function vk(e,t,n){let r=Ik(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...wk(e,t,n,o,r));return i}function Ik(e,t,n){let r=Se(n,new Set(["import_statement"]));if($t(t))for(let i of Pp(e,t))r.add(i);return r}function wk(e,t,n,r,i){let o=Tk(r);if(!o)return[];let s=Je(e,t,o),a=Ye(r,"import_clause");return a?Dk(n,a,s,i,_k(r.text)):[Wn("*",s)]}function Dk(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(Ek(s.text,n,r,i));else if(s.type==="namespace_import"){let a=kk(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...Pk(s,n,r,i));return o}function Ek(e,t,n,r){return pe("default",e,t,n,"default",{isTypeOnly:r})}function kk(e,t,n,r,i){let s=Ye(t,"identifier")?.text??"";if(!s)return null;let a=Lk(e,s);return Gn("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function Pk(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(pe(c,l,t,n,"named",{isTypeOnly:r||Fk(o.text)}))}return i}function Tk(e){let t=Ye(e,"string");if(!t)return null;let n=Ye(t,"string_fragment");return n?n.text:null}function _k(e){return/^\s*import\s+type\b/.test(e)}function Fk(e){return/^\s*type\b/.test(e.trim())}function Lk(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 Nk(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 Ak(e,t,n,r,i,o,s){let a=Je(e,t,r),c=bn(s,i,o);return n?Mk(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=Dr(c,u.localName);return Gn(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||He(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?Wn(u.importedName,u.sourcePath):Vt(u.importedName,u.localName??"",u.sourcePath,u.localName?He(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[Wn("*",a)]}function Mk(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=Ok(r),s=[];return i&&s.push(...Tp(i,n)),o&&s.push(...Tp(o,n)),s}function Tp(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?Ue(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 Ok(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 bl(e,t,n){let r=q(e,t);return r?Wk(e,t,r):jk(e,t,n)}function jk(e,t,n){return[...Bk(e,t,n),...$k(e,t,n),...Hk(e,t,n)]}function Bk(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=Ue(s).map(d=>Uk(d.trim())).filter(d=>!!d),l=Er(n,o.index),u=Er(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 $k(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=Er(n,o.index),c=Er(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 Hk(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=Er(n,o.index),c=Er(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:Je(e,t,s),names:[],startLine:a,endLine:c})}return r}function Uk(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 Er(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Wk(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=Gk(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=zk(i,o,s,a);r.push(c)}return r}function Gk(e,t,n){let r=Ye(n,"string");if(!r)return;let i=Ye(r,"string_fragment");if(i)return Je(e,t,i.text)}function zk(e,t,n,r){let i=Ye(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 Ye(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function _p(e,t,n){return ms(e,t,{java:r=>Vk(e,t,r),kotlin:r=>qk(e,t,r),scala:r=>Kk(e,t,r)},()=>it(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?Jk(e,t,o,i):[]}))}function Vk(e,t,n){let r=Se(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(Gn("*",be(e,l,Ke)));continue}let u=l.split(".").pop()??l;i.push(pe(u,u,be(e,l,Ke),r))}return i}function qk(e,t,n){let r=Se(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(Gn("*",be(e,s.text,Ke)));continue}let l=s.text,u=l.split(".").pop()??l,m=c?.namedChild(0)?.text??u;i.push(pe(u,m,be(e,l,Ke),r))}return i}function Kk(e,t,n){let r=Se(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(Gn("*",be(e,c,Ke)));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 p=m.text,g=f?.text??p;if(p==="_")continue;i.push(pe(p,g,be(e,`${c}.${p}`,Ke),r))}else if(d.type==="identifier"){let m=d.text;i.push(pe(m,m,be(e,`${c}.${m}`,Ke),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;i.push(pe(l,l,be(e,u&&a.length>1?`${u}.${l}`:c,Ke),r))}return i}function Jk(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 Ue(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[ht(e,t,r,m,u,d)]})}return[ht(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Lp(e,t,n){return ot(e,t,r=>Yk(e,t,r),()=>it(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?Ue(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[ht(e,t,i,u,d,m,be(e,u.replace(/\\/g,"."),Hn))]}):[]}))}function Yk(e,t,n){let r=Se(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(pe(a,c,be(e,s.replace(/\\/g,"."),Hn),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}=Fp(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}=Fp(c,"");l&&o(d,l,u)}}return i}function Fp(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 Ap(e,t,n){return ot(e,t,r=>Xk(e,t,r),()=>Zk(n).flatMap(r=>tP(e,t,r,n)))}function Xk(e,t,n){let r=Se(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=Np(s);if(!a)continue;let c=Ir(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=Qk(s);if(a===null)continue;let c=Ir(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=Np(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function Np(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 Qk(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=Ye(e,"import_prefix")?.text??"",n=Ye(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function Zk(e){let t=e.split(`
|
|
111
|
+
`:" ",i+=1;continue}let o=e[i];if(o===";"){let s=Ko(e,i);r+=Ip(e.slice(i,s)),i=s;continue}if(o==='"'){let s=pi(e,i,0).index;r+=Ip(e.slice(i,s)),i=s;continue}r+=o,i+=1}return r}function gk(e){let t=0;for(;t<e.length&&(t=hl(e,t),!(t>=e.length));){let n=ps(e,t);if(!n){t+=1;continue}if(ok(n.form))return n.form;t=n.index}return null}function ps(e,t){let n=hl(e,t);if(e.startsWith("#?@",n)||e.startsWith("#?",n))return hk(e,n);if(e.startsWith("#_",n)){let i=ps(e,n+2);return i?{form:{type:"atom",text:"",start:n,end:i.index},index:i.index}:null}for(;Bc(e[n]);)n+=1;let r=e[n];return r?r==="("?ml(e,n,"list",")"):r==="["?ml(e,n,"vector","]"):r==="{"?ml(e,n,"map","}"):r==='"'?{form:{type:"atom",text:"",start:n,end:pi(e,n,0).index},index:pi(e,n,0).index}:bk(e,n):null}function hk(e,t){let n=e.startsWith("#?@",t)?3:2,r=ps(e,t+n);return r?{form:{type:"list",children:r.form.type==="list"||r.form.type==="vector"||r.form.type==="map"?yk(r.form.children):[],start:t,end:r.index},index:r.index}:null}function yk(e){let t=[];for(let n=0;n<e.length;n+=2){let r=lt(e[n]),i=e[n+1];r?.startsWith(":")&&i&&t.push(i)}return t}function ml(e,t,n,r){let i=[],o=t+1;for(;o<e.length;){if(o=hl(e,o),e[o]===r)return{form:{type:n,children:i,start:t,end:o+1},index:o+1};let s=ps(e,o);if(!s){o+=1;continue}s.form.type==="atom"&&s.form.text===""||i.push(s.form),o=s.index}return{form:{type:n,children:i,start:t,end:e.length},index:e.length}}function bk(e,t){let n=t;for(;n<e.length&&!$c(e[n]);)n+=1;return{form:{type:"atom",text:e.slice(t,n),start:t,end:n},index:n}}function hl(e,t){let n=t;for(;n<e.length;){let r=e[n];if(/\s|,/.test(r)){n+=1;continue}if(r===";"){n=Ko(e,n);continue}break}return n}function Ip(e){return e.replace(/[^\r\n]/g," ")}function Dp(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=Sn(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:os(e,t,o),kind:s?"namespace":"side-effect",used:s?He(c,s):!0,usedMembers:s?Dr(c,s):[]})}return r}function Ep(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:os(e,t,o)})}return r}function kp(e,t,n){return ms(e,t,{csharp:r=>Ck(e,t,r),vb:r=>Sk(e,t,r)},()=>{let r=tp(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return at(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[bt(e,t,o,u,d,m,be(e,u,yn))]})})}function Sk(e,t,n){let r=Se(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(pe(u,d,be(e,l,yn),r,c?"namespace":"named"))}return i}function Ck(e,t,n){let r=Se(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(pe(u,d,be(e,l,yn),r,a?"namespace":"named"))}return i}var xk=j("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function Pp(e,t){return xk.get(e,t,()=>{let n=new Set,r=P(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 yl(e,t,n){return ct(e,t,r=>vk(e,t,r),()=>Rk(e,t,n))}function Rk(e,t,n){return Nk(n).flatMap(r=>Ak(e,t,r.clause,r.specifier,r.start,r.end,n))}function vk(e,t,n){let r=Ik(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...wk(e,t,n,o,r));return i}function Ik(e,t,n){let r=Se(n,new Set(["import_statement"]));if(Ht(t))for(let i of Pp(e,t))r.add(i);return r}function wk(e,t,n,r,i){let o=Tk(r);if(!o)return[];let s=Je(e,t,o),a=Ye(r,"import_clause");return a?Dk(n,a,s,i,_k(r.text)):[Gn("*",s)]}function Dk(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(Ek(s.text,n,r,i));else if(s.type==="namespace_import"){let a=kk(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...Pk(s,n,r,i));return o}function Ek(e,t,n,r){return pe("default",e,t,n,"default",{isTypeOnly:r})}function kk(e,t,n,r,i){let s=Ye(t,"identifier")?.text??"";if(!s)return null;let a=Lk(e,s);return zn("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function Pk(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(pe(c,l,t,n,"named",{isTypeOnly:r||Fk(o.text)}))}return i}function Tk(e){let t=Ye(e,"string");if(!t)return null;let n=Ye(t,"string_fragment");return n?n.text:null}function _k(e){return/^\s*import\s+type\b/.test(e)}function Fk(e){return/^\s*type\b/.test(e.trim())}function Lk(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 Nk(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 Ak(e,t,n,r,i,o,s){let a=Je(e,t,r),c=Sn(s,i,o);return n?Mk(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=Dr(c,u.localName);return zn(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||He(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?Gn(u.importedName,u.sourcePath):qt(u.importedName,u.localName??"",u.sourcePath,u.localName?He(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[Gn("*",a)]}function Mk(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=Ok(r),s=[];return i&&s.push(...Tp(i,n)),o&&s.push(...Tp(o,n)),s}function Tp(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?Ue(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 Ok(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 bl(e,t,n){let r=q(e,t);return r?Wk(e,t,r):jk(e,t,n)}function jk(e,t,n){return[...Bk(e,t,n),...$k(e,t,n),...Hk(e,t,n)]}function Bk(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=Ue(s).map(d=>Uk(d.trim())).filter(d=>!!d),l=Er(n,o.index),u=Er(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 $k(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=Er(n,o.index),c=Er(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 Hk(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=Er(n,o.index),c=Er(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:Je(e,t,s),names:[],startLine:a,endLine:c})}return r}function Uk(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 Er(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Wk(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=Gk(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=zk(i,o,s,a);r.push(c)}return r}function Gk(e,t,n){let r=Ye(n,"string");if(!r)return;let i=Ye(r,"string_fragment");if(i)return Je(e,t,i.text)}function zk(e,t,n,r){let i=Ye(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 Ye(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function _p(e,t,n){return ms(e,t,{java:r=>Vk(e,t,r),kotlin:r=>qk(e,t,r),scala:r=>Kk(e,t,r)},()=>at(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?Jk(e,t,o,i):[]}))}function Vk(e,t,n){let r=Se(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(zn("*",be(e,l,Ke)));continue}let u=l.split(".").pop()??l;i.push(pe(u,u,be(e,l,Ke),r))}return i}function qk(e,t,n){let r=Se(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(zn("*",be(e,s.text,Ke)));continue}let l=s.text,u=l.split(".").pop()??l,m=c?.namedChild(0)?.text??u;i.push(pe(u,m,be(e,l,Ke),r))}return i}function Kk(e,t,n){let r=Se(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(zn("*",be(e,c,Ke)));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 p=m.text,g=f?.text??p;if(p==="_")continue;i.push(pe(p,g,be(e,`${c}.${p}`,Ke),r))}else if(d.type==="identifier"){let m=d.text;i.push(pe(m,m,be(e,`${c}.${m}`,Ke),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;i.push(pe(l,l,be(e,u&&a.length>1?`${u}.${l}`:c,Ke),r))}return i}function Jk(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 Ue(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[bt(e,t,r,m,u,d)]})}return[bt(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Lp(e,t,n){return ct(e,t,r=>Yk(e,t,r),()=>at(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?Ue(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[bt(e,t,i,u,d,m,be(e,u.replace(/\\/g,"."),Un))]}):[]}))}function Yk(e,t,n){let r=Se(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(pe(a,c,be(e,s.replace(/\\/g,"."),Un),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}=Fp(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}=Fp(c,"");l&&o(d,l,u)}}return i}function Fp(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 Ap(e,t,n){return ct(e,t,r=>Xk(e,t,r),()=>Zk(n).flatMap(r=>tP(e,t,r,n)))}function Xk(e,t,n){let r=Se(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=Np(s);if(!a)continue;let c=Ir(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=Qk(s);if(a===null)continue;let c=Ir(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=Np(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function Np(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 Qk(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=Ye(e,"import_prefix")?.text??"",n=Ye(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function Zk(e){let t=e.split(`
|
|
112
112
|
`),n=[],r=0;for(let i=0;i<t.length;i++){let o=t[i],s=o.trimStart(),a=r;if(r+=o.length+1,!s.startsWith("import ")&&!s.startsWith("from "))continue;let c=o,l=a+o.length,u=Ci(o);for(;i+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){i++;let m=t[i];c+=`
|
|
113
|
-
${m}`,l+=1+m.length,u+=Ci(m),r+=m.length+1}let d=eP(c);d&&n.push({...d,start:a,end:l})}return n}function eP(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 r=n[2].trim();return r.startsWith("(")&&r.endsWith(")")&&(r=r.slice(1,-1).trim()),{kind:"from",module:n[1],clause:r}}function tP(e,t,n,r){let i=
|
|
113
|
+
${m}`,l+=1+m.length,u+=Ci(m),r+=m.length+1}let d=eP(c);d&&n.push({...d,start:a,end:l})}return n}function eP(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 r=n[2].trim();return r.startsWith("(")&&r.endsWith(")")&&(r=r.slice(1,-1).trim()),{kind:"from",module:n[1],clause:r}}function tP(e,t,n,r){let i=Sn(r,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return Ue(o).flatMap(c=>{let l=c.trim().replace(/,$/,"");if(!l)return[];let[u,d]=l.split(/\s+as\s+/),m=u.trim(),f=(d??m.split(".")[0]??m).trim(),p=Ir(e,t,m),g=Dr(i,f);return[{importedName:m,localName:f,sourcePath:p,kind:"namespace",used:He(i,f)||g.length>0,usedMembers:g}]});let s=n.module?Ir(e,t,n.module):null,a=[];for(let c of Ue(o)){let l=c.trim().replace(/,$/,"");if(!l)continue;if(l==="*"){a.push({importedName:"*",localName:null,sourcePath:s,kind:"side-effect",used:!0,usedMembers:[]});continue}let[u,d]=l.split(/\s+as\s+/),m=(d??u).trim();a.push({importedName:u.trim(),localName:m,sourcePath:s,kind:"named",used:He(i,m),usedMembers:[]})}return a}import{basename as nP}from"path";function Mp(e,t,n){return ct(e,t,r=>iP(e,t,r),()=>rP(e,t,n))}function rP(e,t,n){return at(n,/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm,(r,i)=>{let o=r[1],s=r[2];if(!o||!s)return[];let a=o==="require_relative"?rs(e,t,s):null;if(a){let c=Op(s);return[qt(c,c,a,He(i,c))]}return[Gn(s,a)]})}function iP(e,t,n){let r=Se(n,new Set([])),i=[],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(f=>f.type==="argument_list")?.namedChild(0);if(!l||l.type!=="string")continue;let d=l.namedChildren.find(f=>f.type==="string_content")?.text;if(!d)continue;let m=a.text==="require_relative"?rs(e,t,d):null;if(m){let f=Op(d);i.push(pe(f,f,m,r))}else i.push(Gn(d,m))}return i}function Op(e){return Yo(nP(e).replace(/\.[^.]+$/,""),/_/)}function jp(e,t,n){return ct(e,t,r=>oP(e,t,r),()=>at(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?sP(e,t,o,i):[]}))}function oP(e,t,n){let r=Se(n,new Set(["use_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("use_declaration")){let s=o.namedChild(0);if(s)for(let a of xi(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=Gt(e,t,a.qualifiedName)??Gt(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push(pe(a.importedName,a.localName,c,r))}}return i}function xi(e,t){switch(e.type){case"identifier":case"super":case"crate":{let n=e.text;return[{qualifiedName:kr(t,n),importedName:n,localName:n}]}case"self":{let n=t.split("::").filter(Boolean).pop()??"self";return[{qualifiedName:t||"self",importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:kr(t,n),importedName:r,localName:r}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=kr(t,n.text),o=[];for(let s of r.namedChildren)o.push(...xi(s,i));return o}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...xi(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=xi(n,t),o=r.text;return i.map(s=>({...s,localName:o}))}case"use_wildcard":{let n=e.namedChild(0),r=n?n.text:"";return[{qualifiedName:kr(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function kr(e,t){return e?t?`${e}::${t}`:e:t}function sP(e,t,n,r){let i=n.trim();if(i.includes("{")&&i.includes("}")){let u=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),d=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return Ue(d).flatMap(m=>{let f=m.trim();if(!f)return[];if(f==="self"){let x=u.split("::").filter(Boolean).pop();return x?[bt(e,t,r,u,x,x)]:[]}let[p,g]=f.split(/\s+as\s+/),y=p?.trim();if(!y)return[];let h=(g??y.split("::").pop()??y).trim(),C=`${u}::${y}`.replace(/::::/g,"::");return[bt(e,t,r,C,y.split("::").pop()??y,h,Gt(e,t,u))]})}let[o,s]=i.split(/\s+as\s+/),a=o?.trim()??i,c=(s??a.split("::").pop()??a).trim(),l=Gt(e,t,a)??Gt(e,t,a.split("::").slice(0,-1).join("::"));return[bt(e,t,r,a,a.split("::").pop()??a,c,l)]}function Bp(e,t,n){let r=q(e,t);if(r)return aP(e,t,r);let i=[];for(let o of n.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)){let s=o[1]?.trim();s&&i.push(...lP(e,t,s))}return i}function aP(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!cP(i))continue;let o=i.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of xi(o,""))s.importedName&&r.push(Sl(e,t,s.qualifiedName))}return r}function cP(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function lP(e,t,n){let r=n.trim();if(r.includes("{")&&r.includes("}")){let i=r.slice(0,r.indexOf("{")).replace(/::$/,"").trim(),o=r.slice(r.indexOf("{")+1,r.lastIndexOf("}")).trim();return Ue(o).flatMap(s=>{let a=s.trim();if(!a||a==="self")return[];let[c]=a.split(/\s+as\s+/),l=`${i}::${c?.trim()??a}`.replace(/::::/g,"::");return[Sl(e,t,l)]})}return[Sl(e,t,r)]}function Sl(e,t,n){return{specifier:n,sourcePath:Gt(e,t,n)??Gt(e,t,n.split("::").slice(0,-1).join("::"))}}function Cn({language:e,extensions:t,imports:n,parseImports:r}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:r}}function $p(e,t){let n=t.toLowerCase();for(let r of e)for(let i of r.extensions)if(n.endsWith(i))return r;return null}var uP={language:"javascript",extensions:$n,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:yl,parseReExports:bl},dP=Cn({language:"python",extensions:Qo,imports:"ast-with-regex-fallback",parseImports:Ap}),mP=Cn({language:"jvm",extensions:Ke,imports:"ast-dispatch-with-regex-fallback",parseImports:_p}),fP={language:"rust",extensions:Zo,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:jp,parseExports:Bp},pP=Cn({language:"ruby",extensions:es,imports:"ast-with-regex-fallback",parseImports:Mp}),gP=Cn({language:"c/cpp",extensions:ts,imports:"ast-with-regex-fallback",parseImports:vp}),hP=Cn({language:"dotnet",extensions:yn,imports:"ast-dispatch-with-regex-fallback",parseImports:kp}),yP={language:"dart",extensions:ns,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:Dp,parseExports:Ep},bP=Cn({language:"php",extensions:Un,imports:"ast-with-regex-fallback",parseImports:Lp}),SP=Cn({language:"clojure",extensions:vr,imports:"regex-only",parseImports:wp}),Hp=[uP,dP,mP,fP,pP,gP,hP,yP,bP,SP];function gs(e){return $p(Hp,e)}function z4(e){return Hp.find(n=>n.language===e)?.capabilities??null}var Cl={clearGroups:["whole-project","source-file"]},CP=j("source-imports",Cl),xP=j("source-exports",Cl),RP=j("source-reexports",Cl),Up=oe({kind:"source-imports",invalidation:K("source-imports"),serialize:vP,deserialize:IP}),Wp=oe({kind:"source-reexports",invalidation:K("source-reexports"),serialize:wP,deserialize:DP});function Kt(e,t){let n=te(t);return RP.get(e,n,()=>{let r=gs(n);if(!r?.parseReExports)return[];let i=P(e,n);if(!i)return[];let o=ce(e,n,i),s=sl(e),a=Wp.read(e,n,o);if(a?.resolutionFingerprint===s)return a.reExports;let c=r.parseReExports(e,n,i);return Wp.write(e,n,o,{resolutionFingerprint:s,reExports:c}),c})}function re(e,t){let n=te(t);return CP.get(e,n,()=>{let r=gs(n);if(!r)return[];let i=P(e,n);if(!i)return[];let o=ce(e,n,i),s=sl(e),a=Up.read(e,n,o);if(a?.resolutionFingerprint===s)return a.imports;let c=r.parseImports(e,n,i);return Up.write(e,n,o,{resolutionFingerprint:s,imports:c}),c})}function hs(e,t){let n=te(t);return xP.get(e,n,()=>{let r=gs(n);if(!r?.parseExports)return[];let i=P(e,n);return i?r.parseExports(e,n,i):[]})}function vP(e){return JSON.stringify(e)}function IP(e){try{let t=JSON.parse(e);return!wt(t)||typeof t.resolutionFingerprint!="string"||!Array.isArray(t.imports)?null:{resolutionFingerprint:t.resolutionFingerprint,imports:t.imports}}catch{return null}}function wP(e){return JSON.stringify(e)}function DP(e){try{let t=JSON.parse(e);return!wt(t)||typeof t.resolutionFingerprint!="string"||!Array.isArray(t.reExports)?null:{resolutionFingerprint:t.resolutionFingerprint,reExports:t.reExports}}catch{return null}}function ut(e){return{forFile(t,n){return Gp(e,t,n)},forFiles(t,n){let r=new Map;for(let i of t)r.set(i,Gp(e,i,n));return r}}}function Gp(e,t,n){let r={file:t},i=n.facts||n.identifiers;if(n.text&&(r.text=P(e,t)),n.lines&&(r.lines=Ce(e,t)),n.ast&&(r.ast=q(e,t)),n.imports&&(r.imports=re(e,t)),n.reexports&&(r.reexports=Kt(e,t)),i){let o=Uc(e,t),s=o.facts;n.facts&&(r.facts=s),o.unavailable&&(r.sourceFactsUnavailable=o.unavailable),n.identifiers&&s&&(r.identifiers=s.fileIdentifiers,r.identifierLineMap=s.identifierLineMap)}return r}function Vn(e,t){return e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.start_char, der.end_line, der.end_char, d.relative_path, gs.display_name, gs.documentation
|
|
114
114
|
FROM global_symbols gs
|
|
115
115
|
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
116
116
|
JOIN documents d ON der.document_id = d.id
|
|
@@ -137,7 +137,7 @@ ${m}`,l+=1+m.length,u+=Ci(m),r+=m.length+1}let d=eP(c);d&&n.push({...d,start:a,e
|
|
|
137
137
|
${e.pathExclusionsFor("d")}
|
|
138
138
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
|
|
139
139
|
${Vp(t.orderBy)}
|
|
140
|
-
${qp(t.limit)}`,...t.params??[])}function Vp(e){return e?`ORDER BY ${e}`:""}function qp(e){return typeof e=="number"?`LIMIT ${e}`:""}function
|
|
140
|
+
${qp(t.limit)}`,...t.params??[])}function Vp(e){return e?`ORDER BY ${e}`:""}function qp(e){return typeof e=="number"?`LIMIT ${e}`:""}function Jt(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 Yt(e){if(!e)return null;let t=zp(e);if(t)return t.replace(/\n/g," ");let n=e.indexOf("|");if(n===-1)return e.replace(/\n/g," ");let r=e.slice(n+1);return(zp(r)??r).replace(/\n/g," ")}function zp(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function EP(e,t={}){if(It(e.symbol)!==null)return t.includeClassMemberFallbacks===!0;let i=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function xn(e,t,n={}){let r=new Map;for(let o of t)e.length>0&&!EP(o,{includeClassMemberFallbacks:n.includeClassMemberFallbacks})||r.set(o.id,o);for(let o of e)r.set(o.id,o);let i=[...r.values()];return n.sort?i.sort((o,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):i}var kP=j("file-definitions",{clearGroups:["definition-catalog"]}),PP=j("file-function-like-definitions",{clearGroups:["definition-catalog"]}),Kp=new WeakMap;function Q(e,t,n={}){return n.includeClassMemberFallbacks?xl(e,t,void 0,{includeClassMemberFallbacks:!0}):kP.get(e,t,()=>{let r=Qp(e,t);if(r)return r;let i=xl(e,t),o=Te(e),s=ut(e).forFile(t,{text:!0}).text;return o&&s&&Xp.write(e,t,ce(e,t,s),{projectFingerprint:o,definitions:i.map(a=>({...a}))}),i})}function TP(e,t){return PP.get(e,t,()=>{let n=Qp(e,t);return n?n.filter(r=>r.isFunctionLike):xl(e,t,r=>r.isFunctionLike)})}var Xp=oe({kind:"file-definitions",invalidation:K("file-definitions"),serialize:_P,deserialize:FP});function Qp(e,t){let n=Te(e);if(!n)return null;let r=ut(e).forFile(t,{text:!0}).text;if(!r)return null;let i=Xp.read(e,t,ce(e,t,r));return i?LP(i,n,t):null}function _P(e){return JSON.stringify(e)}function FP(e){try{let t=JSON.parse(e);return!wt(t)||typeof t.projectFingerprint!="string"||!Array.isArray(t.definitions)?null:{projectFingerprint:t.projectFingerprint,definitions:t.definitions}}catch{return null}}function LP(e,t,n){if(e.projectFingerprint!==t)return null;let r=[];for(let i of e.definitions){let o=NP(i,n);if(!o)return null;r.push(o)}return r}function NP(e,t){return!wt(e)||typeof e.symbolId!="number"||typeof e.symbol!="string"||typeof e.documentId!="number"||typeof e.startLine!="number"||typeof e.startChar!="number"&&e.startChar!==void 0||typeof e.endLine!="number"||typeof e.endChar!="number"&&e.endChar!==void 0||e.relativePath!==t||typeof e.leaf!="string"||typeof e.parentTypeName!="string"&&e.parentTypeName!==null||typeof e.isFunctionLike!="boolean"||typeof e.isTypeLike!="boolean"||typeof e.kind!="number"&&e.kind!==null||typeof e.documentation!="string"&&e.documentation!==null||typeof e.enclosingSymbol!="string"&&e.enclosingSymbol!==null?null:{symbolId:e.symbolId,symbol:e.symbol,documentId:e.documentId,startLine:e.startLine,startChar:e.startChar,endLine:e.endLine,endChar:e.endChar,relativePath:e.relativePath,leaf:e.leaf,parentTypeName:e.parentTypeName,isFunctionLike:e.isFunctionLike,isTypeLike:e.isTypeLike,kind:e.kind,documentation:e.documentation,enclosingSymbol:e.enclosingSymbol}}function xl(e,t,n,r={}){let i=xn(AP(e,t),MP(e,t),{sort:!0,includeClassMemberFallbacks:r.includeClassMemberFallbacks}).map(Zp);return n&&(i=i.filter(n)),ng(e,t,i)}function AP(e,t){return e.all(`SELECT
|
|
141
141
|
gs.id,
|
|
142
142
|
gs.symbol,
|
|
143
143
|
der.document_id,
|
|
@@ -176,7 +176,7 @@ ${m}`,l+=1+m.length,u+=Ci(m),r+=m.length+1}let d=eP(c);d&&n.push({...d,start:a,e
|
|
|
176
176
|
AND m.role = 1
|
|
177
177
|
${e.symbolNoiseFor("gs")}
|
|
178
178
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
179
|
-
ORDER BY start_line, end_line`,t)}function Zp(e){return{symbolId:e.id,symbol:e.symbol,documentId:e.document_id,startLine:e.start_line,startChar:e.start_char??0,endLine:e.end_line,endChar:e.end_char??0,relativePath:e.relative_path,leaf:T(e.symbol),parentTypeName:
|
|
179
|
+
ORDER BY start_line, end_line`,t)}function Zp(e){return{symbolId:e.id,symbol:e.symbol,documentId:e.document_id,startLine:e.start_line,startChar:e.start_char??0,endLine:e.end_line,endChar:e.end_char??0,relativePath:e.relative_path,leaf:T(e.symbol),parentTypeName:It(e.symbol),isFunctionLike:ee(e.symbol),isTypeLike:ue(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function xe(e,t={}){return Rl(e,t.scope)}function Rl(e,t){return N(e,{scope:t,includeIgnored:!1}).flatMap(n=>Q(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function eg(e,t){return N(e,{scope:t,includeIgnored:!1}).flatMap(n=>TP(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function Ri(e,t){let n=Jp(OP(e,t.scope,t.sqlPrefilter)),r=Jp(jP(e,t.scope,t.sqlPrefilter)),i=new Set([...n.keys(),...r.keys()]),o=[];for(let s of[...i].sort()){if(e.isIgnored(s))continue;let a=xn(n.get(s)??[],r.get(s)??[],{sort:!0}).filter(c=>t.symbolMatches(c.symbol));a.length!==0&&o.push(...ng(e,s,a.map(Zp)))}return o}function OP(e,t,n){let r=t?"AND d.relative_path LIKE ?":"",i=n?`AND ${tg("gs",n)}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
|
|
180
180
|
gs.id,
|
|
181
181
|
gs.symbol,
|
|
182
182
|
der.document_id,
|
|
@@ -220,8 +220,8 @@ ${m}`,l+=1+m.length,u+=Ci(m),r+=m.length+1}let d=eP(c);d&&n.push({...d,start:a,e
|
|
|
220
220
|
${i}
|
|
221
221
|
${e.symbolNoiseFor("gs")}
|
|
222
222
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
223
|
-
ORDER BY d.relative_path, start_line, end_line`,...o)}function BP(e){return`(${e}.symbol LIKE '%().' OR ${e}.symbol LIKE '%()')`}function tg(e,t){return t==="callable"?BP(e):$P(e)}function $P(e){return`(${e}.symbol LIKE '%.' OR ${e}.symbol LIKE '%()')`}function Jp(e){let t=new Map;for(let n of e){let r=t.get(n.relative_path);r?r.push(n):t.set(n.relative_path,[n])}return t}function ys(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>Q(e,i)).filter(i=>!e.isIgnored(i.relativePath));return n.onlyDocumented&&(r=r.filter(i=>i.documentation!==null&&i.documentation!=="")),n.sort&&(r=r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath)||i.startLine-o.startLine||i.endLine-o.endLine)),r.map(i=>({startLine:i.startLine,endLine:i.endLine,symbol:i.symbol,shortName:I(i.symbol),signature:
|
|
224
|
-
AND `),o=
|
|
223
|
+
ORDER BY d.relative_path, start_line, end_line`,...o)}function BP(e){return`(${e}.symbol LIKE '%().' OR ${e}.symbol LIKE '%()')`}function tg(e,t){return t==="callable"?BP(e):$P(e)}function $P(e){return`(${e}.symbol LIKE '%.' OR ${e}.symbol LIKE '%()')`}function Jp(e){let t=new Map;for(let n of e){let r=t.get(n.relative_path);r?r.push(n):t.set(n.relative_path,[n])}return t}function ys(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>Q(e,i)).filter(i=>!e.isIgnored(i.relativePath));return n.onlyDocumented&&(r=r.filter(i=>i.documentation!==null&&i.documentation!=="")),n.sort&&(r=r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath)||i.startLine-o.startLine||i.endLine-o.endLine)),r.map(i=>({startLine:i.startLine,endLine:i.endLine,symbol:i.symbol,shortName:I(i.symbol),signature:Jt(Yt(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function vl(e){let t=new Map,n=e.map((r,i)=>({definition:r,index:i,span:r.endLine-r.startLine})).sort((r,i)=>r.span-i.span||r.index-i.index);for(let{definition:r}of n)for(let i=r.startLine;i<=r.endLine;i+=1)t.has(i)||t.set(i,r);return t}function Dt(e,t){let n=Kp.get(e);return n||(n=vl(e),Kp.set(e,n)),n.get(t)??null}function bs(e,t){let n=Q(e,t.relative_path).find(r=>r.symbolId===t.id);return n?{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,startChar:n.startChar,endLine:n.endLine,endChar:n.endChar,relativePath:n.relativePath}:{symbolId:t.id,symbol:t.symbol,documentId:t.document_id,startLine:t.start_line,startChar:t.start_char??0,endLine:t.end_line,endChar:t.end_char??0,relativePath:t.relative_path}}function ng(e,t,n){let r=ut(e).forFile(t,{text:!0}).text,i=Gc(e,t);return i?VP(n,i,r):r?HP(n,r):n}function HP(e,t){let n=t.split(/\r?\n/),r=UP(e,n),i=WP(e,r),o=GP(i,n);return zP(e,o)}function UP(e,t){let n=e.some(i=>Ss(i.symbol))?ZP(t):null,r=new Map;for(let i of e)r.set(i.symbolId,QP(t,n,i));return r}function WP(e,t){return e.filter(n=>Ss(n.symbol)).map(n=>({definition:n,startLine:t.get(n.symbolId)??n.startLine})).sort((n,r)=>n.startLine-r.startLine||n.definition.startLine-r.definition.startLine||n.definition.symbol.localeCompare(r.definition.symbol))}function GP(e,t){let n=new Map;for(let r=0;r<e.length;r+=1){let i=e[r],o=e[r+1],s=o?Math.max(i.startLine,o.startLine-1):t.length-1;n.set(i.definition.symbolId,{startLine:i.startLine,endLine:eT(t,i.definition,i.startLine,s)})}return n}function zP(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function VP(e,t,n=null){let r=new Map;for(let i of t){let o=r.get(i.name);o?o.push(i):r.set(i.name,[i])}return e.map(i=>{if(!XP(i)||!i.leaf)return Yp(i,n);let o=r.get(i.leaf);if(!o||o.length===0)return Yp(i,n);let s=n?qP(i,o,n):null;if(s)return{...i,startLine:s.startLine,endLine:s.endLine};let a=o[0],c=Math.abs(a.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let u=o[l],d=Math.abs(u.startLine-i.startLine);d<c&&(a=u,c=d)}return{...i,startLine:a.startLine,endLine:a.endLine}})}function qP(e,t,n){let r=KP(e.symbol);if(!r)return null;let i=n.split(/\r?\n/),o=new RegExp(`\\b${$(r)}\\b`);for(let s of t){let a=JP(i,s.startLine);if(a&&o.test(a))return s}return null}function KP(e){return e.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function JP(e,t){for(let n=t;n>=0;n-=1){let r=e[n]?.trim()??"";if(r){if(/^impl\b/.test(r))return YP(e,n,t);if(/^(?:struct|enum|trait|mod)\b/.test(r))return null}}return null}function YP(e,t,n){let r=[];for(let i=t;i<=n;i+=1){let o=e[i]??"";if(r.push(o),o.includes("{"))break}return r.join(" ")}function XP(e){return Ss(e.symbol)?!0:ue(e.symbol)==="term"&&It(e.symbol)===null}function Yp(e,t){if(!t||!e.leaf||ue(e.symbol)!=="term"||It(e.symbol)!==null)return e;let n=$(e.leaf),r=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`),o=t.split(/\r?\n/).findIndex(s=>r.test(s));return o>=0?{...e,startLine:o,endLine:o}:e}function QP(e,t,n){if(!Ss(n.symbol))return n.startLine;let r=Math.max(0,Math.min(n.startLine,e.length-1));if(!t)return r;let i=t.get(n.leaf);if(!i||i.length===0)return r;let o=null;for(let s of i){let a=Math.abs(s-n.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??r}function ZP(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,r=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,i=/\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(r);l?.[1]&&s(l[1],a);for(let u of c.matchAll(i))u[1]&&s(u[1],a)}return o}function eT(e,t,n,r){let i=Math.max(n,Math.min(e.length-1,r)),o=Math.max(n,Math.min(i,t.endLine)),s=0,a=0,c=!1;for(let l=n;l<=i;l+=1){let u=tT(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 tT(e){let t="",n=null,r=!1;for(let i=0;i<e.length;i+=1){let o=e[i],s=e[i+1];if(!n&&o==="/"&&s==="/"){t+=" ".repeat(e.length-i);break}if(n){if(r){r=!1,t+=" ";continue}if(o==="\\"){r=!0,t+=" ";continue}o===n&&(n=null),t+=" ";continue}if(o==='"'||o==="'"||o==="`"){n=o,t+=" ";continue}t+=o}return t}function Ss(e){return e.includes("().")}function Cs(e){let t=ye(e);if("kind"in t)return[];let n=[];for(let r=t.descriptors.length-2;r>=0;r-=1){let i=t.descriptors[r];i?.suffix==="type"&&i.name&&n.push(i.name)}return n}var nT=j("symbol-resolution",{clearGroups:[]});function B(e,t){return Ii(e,t).match}function Ii(e,t){return nT.get(e,t,()=>{let n=ig(e,t.trim()).filter(o=>!e.isIgnored(o.relative_path));if(n.length>0)return vi(e,n);let r=lT(e,t);if(r&&!e.isIgnored(r.relative_path))return vi(e,[r]);let i=rT(e,t);return i.length>0?vi(e,i):aT(e,t)})}function rT(e,t){let n=Rs(t),r=Il(n);if(!r)return[];let i=`%${r.path}%`,o=r.leaf;return iT(e,i,o,n)}function iT(e,t,n,r){let i=xn([],[...oT(e,t,n),...sT(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>Tr(o,r)>1);return i.sort((o,s)=>Tr(s,r)-Tr(o,r)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.start_line-s.start_line||o.symbol.localeCompare(s.symbol)),i}function oT(e,t,n){return Vn(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function sT(e,t,n){return Pr(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function aT(e,t){let n=Rs(t),r=gT(t),i=fT(e,r),o=hT(i,t,n).filter(a=>!e.isIgnored(a.relative_path));if(o.length>0)return vi(e,o);let s=[];for(let a of i){if(e.isIgnored(a.relative_path))continue;let c=pT(a,t,n,r);c<=0||s.push({row:a,score:c})}return s.sort((a,c)=>c.score-a.score||a.row.end_line-a.row.start_line-(c.row.end_line-c.row.start_line)||a.row.relative_path.localeCompare(c.row.relative_path)||a.row.symbol.localeCompare(c.row.symbol)),vi(e,s.map(a=>a.row))}function vi(e,t){let n=t.map(i=>bs(e,i)),r=n[0]??null;return{match:r,candidates:r?cT(n,r):[],total:n.length}}function cT(e,t){let n=new Set([`${t.symbolId}:${t.relativePath}:${t.startLine}`]),r=[];for(let i of e){let o=`${i.symbolId}:${i.relativePath}:${i.startLine}`;if(!n.has(o)&&(n.add(o),r.push({symbol:i.symbol,shortName:I(i.symbol),relativePath:i.relativePath,startLine:i.startLine}),r.length>=5))break}return r}function lT(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return;let[,r,i,o]=n,s=Math.max(0,parseInt(i,10)-1),a=Math.max(s,parseInt(o,10)-1);return uT(e,r,s,a)??dT(e,r,s,a)}function uT(e,t,n,r){return Vn(e,{where:"d.relative_path LIKE ? AND der.start_line <= ? AND der.end_line >= ?",params:[`%${t}%`,n,r],orderBy:"(der.end_line - der.start_line) ASC",limit:1})[0]}function dT(e,t,n,r){return Pr(e,{where:"d.relative_path LIKE ? AND c.start_line <= ? AND c.end_line >= ?",params:[`%${t}%`,n,r],orderBy:"(MAX(c.end_line) - MIN(c.start_line)) ASC",limit:1})[0]}function wi(e,t){let n=ig(e,t).find(r=>!e.isIgnored(r.relative_path));return n?bs(e,n):null}function ig(e,t){let n=Vn(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line"}),r=n.length>0?[]:Pr(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line"});return xn(n,r)}function xs(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=mT(e,t.symbolId)[0];return n?bs(e,n):null}function mT(e,t){let n=Vn(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),r=Pr(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return xn(n,r)}function fT(e,t){let n=t.map(()=>"(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)"),r=t.flatMap(a=>{let c=`%${a}%`;return[c,c,c]}),i=n.join(`
|
|
224
|
+
AND `),o=Vn(e,{where:i,params:r,limit:200}),s=Pr(e,{where:i,params:r,limit:200});return xn(o,s)}function pT(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=I(e.symbol),m=T(e.symbol),f=e.display_name??"",p=e.symbol.toLowerCase(),g=d.toLowerCase(),y=m.toLowerCase(),h=f.toLowerCase(),C=e.relative_path.toLowerCase(),x=/[/:.]/.test(n),S=Il(n),b=S?.leaf.toLowerCase(),v=0;return(u===i||u===o)&&(v+=1150),(d===i||d===o)&&(v+=1100),f===s&&(v+=1180),m===s&&(v+=1160),(`${m}()`===i||`${m}()`===o)&&(v+=955),(p===a||p===c)&&(v+=1e3),(g===a||g===c)&&(v+=950),(C===a||C===c)&&(v+=925),(C.endsWith(`/${c}`)||C.endsWith(`/${a}`))&&(v+=875),h===l&&(v+=850),y===l&&(v+=825),(`${y}()`===a||`${y}()`===c)&&(v+=820),(g.endsWith(`:${c}`)||g.endsWith(`:${l}`)||g.endsWith(`:${l}()`))&&(v+=800),p.includes(c)&&(v+=120),g.includes(c)&&(v+=140),C.includes(c)&&(v+=140),h.includes(c)&&(v+=110),r.every(R=>{let E=R.toLowerCase();return p.includes(E)||g.includes(E)||C.includes(E)||h.includes(E)})&&(v+=100+r.length*15),S&&C.includes(S.path.toLowerCase())&&(v+=360,b&&(y===b||`${y}()`===b||`${y}()`==`${b}()`)&&(v+=700),le(e.symbol)&&(v+=180)),ee(e.symbol)&&y===l&&(v+=60),!x&&pn(e.symbol)&&(v-=160),v-=Math.min(50,Math.max(0,e.end_line-e.start_line)),v}function Il(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 Rs(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function gT(e){let t=Rs(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 hT(e,t,n){let r=t.trim(),i=e.filter(o=>{let s=I(o.symbol),a=(o.display_name??"").trim();return o.symbol===r||s===r||s===n||a===r||a===n||`${a}()`===r||Tr(o,n)>1||o.relative_path===r});return i.length===0?[]:(i.sort((o,s)=>Tr(s,n)-Tr(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)}function Tr(e,t){let n=Il(t);if(!n)return 0;let r=e.relative_path.toLowerCase(),i=T(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return r.includes(o)?i!==s?1:le(e.symbol)?It(e.symbol)===null?5:4:It(e.symbol)===null?3:2:0}function E8(e,t,n=5){let r=rg(t);if(!r)return[];let i=Vn(e,{where:"1 = 1",orderBy:"d.relative_path, der.start_line",limit:5e3}),o=new Map;for(let s of i){if(e.isIgnored(s.relative_path))continue;let a=I(s.symbol),c=T(s.symbol),l=s.display_name??c,u=[a,c,l].filter(f=>f.trim().length>0),d=Math.min(...u.map(f=>yT(rg(f),r))),m=o.get(a);(!m||d<m.distance)&&o.set(a,{shortName:a,distance:d})}return[...o.values()].sort((s,a)=>s.distance-a.distance||s.shortName.localeCompare(a.shortName)).slice(0,n).map(s=>s.shortName)}function rg(e){return Rs(e).toLowerCase().replace(/[^a-z0-9_]+/g,"")}function yT(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=Array.from({length:t.length+1},(r,i)=>i);for(let r=0;r<e.length;r++){let i=[r+1];for(let o=0;o<t.length;o++){let s=e[r]===t[o]?0:1;i[o+1]=Math.min(i[o]+1,n[o+1]+1,n[o]+s)}n=i}return n[t.length]}function vs(e,t,n,r={}){if(!n)return[];let i=P(e,t);return i?i.indexOf(n)===-1?[]:(Xt(e,t).get(n)??[]).filter(s=>!bT(s,r)):[]}function bT(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var ST=j("file-identifiers",{clearGroups:["whole-project","source-file"]});function og(e,t){let n=G(e,t);return n?n.fileIdentifiers:ST.get(e,t,()=>new Set(Xt(e,t).keys()))}var CT=j("file-ident-lines",{clearGroups:["whole-project","source-file"]});function Xt(e,t){let n=G(e,t);return n?n.identifierLineMap:CT.get(e,t,()=>RT(e,t))}var xT=j("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function sg(e,t){let n=G(e,t);return n?n.identifiersByLine:xT.get(e,t,()=>{let r=Xt(e,t),i=0;for(let s of r.values()){let a=s[s.length-1];a!==void 0&&a>i&&(i=a)}let o=new Array(i+1);for(let s=0;s<=i;s+=1)o[s]=new Set;for(let[s,a]of r)for(let c of a)o[c].add(s);return o})}function RT(e,t){let n=new Map,r=(a,c)=>{let l=n.get(a);if(!l){n.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)},i=P(e,t);if(!i)return n;let o=st(i).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]&&r(l[1],a)}return n}function ag(e,t){return Is(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
|
|
225
225
|
m.symbol_id,
|
|
226
226
|
d.relative_path,
|
|
227
227
|
COUNT(*) AS ref_count
|
|
@@ -248,7 +248,7 @@ ${m}`,l+=1+m.length,u+=Ci(m),r+=m.length+1}let d=eP(c);d&&n.push({...d,start:a,e
|
|
|
248
248
|
WHERE m.role != 1
|
|
249
249
|
${r}
|
|
250
250
|
${e.pathExclusionsFor("d")}
|
|
251
|
-
ORDER BY d.relative_path, c.start_line`,...n??[])})}function Is(e,t,n){if(!t)return n();if(t.length===0)return[];let r=[];for(let i=0;i<t.length;i+=750)r.push(...n(t.slice(i,i+750)));return r}function ws(e,t){let n=ug(e);return n?t.filter(r=>ug(r.file)===n):t}function Ds(e,t,n,r){let i=n.find(o=>o.file===t);if(i)return i;if(r){let o=new Set(re(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(Ve(a,s.file))return s;return null}return n.length===1?n[0]:null}function ug(e){let t=M(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var vT=J("global-leaf-index",{clearGroups:["whole-project"]});function
|
|
251
|
+
ORDER BY d.relative_path, c.start_line`,...n??[])})}function Is(e,t,n){if(!t)return n();if(t.length===0)return[];let r=[];for(let i=0;i<t.length;i+=750)r.push(...n(t.slice(i,i+750)));return r}function ws(e,t){let n=ug(e);return n?t.filter(r=>ug(r.file)===n):t}function Ds(e,t,n,r){let i=n.find(o=>o.file===t);if(i)return i;if(r){let o=new Set(re(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(Ve(a,s.file))return s;return null}return n.length===1?n[0]:null}function ug(e){let t=M(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var vT=J("global-leaf-index",{clearGroups:["whole-project"]});function Qt(e){return vT.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
|
|
252
252
|
COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
|
|
253
253
|
FROM global_symbols gs
|
|
254
254
|
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
@@ -262,7 +262,7 @@ ${m}`,l+=1+m.length,u+=Ci(m),r+=m.length+1}let d=eP(c);d&&n.push({...d,start:a,e
|
|
|
262
262
|
GROUP BY m.symbol_id
|
|
263
263
|
) mention_doc ON mention_doc.symbol_id = gs.id
|
|
264
264
|
WHERE 1 = 1
|
|
265
|
-
${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=T(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.some(s=>s.symbolId===r.id)||o.push({symbol:r.symbol,symbolId:r.id,file:r.relative_path})}return n})}var dg=/[A-Za-z_$][A-Za-z0-9_$]*/g,mg=/^[A-Za-z_$][A-Za-z0-9_$]*$/,IT=512;function Di(e){let t=[],n=!1;for(let r of e)r&&(n=!0,mg.test(r)||t.push(r));return{candidateNames:e,hasUsableCandidate:n,nonIdentifierNames:t}}function Es(e,t){let n=wT(t)?t:Di(t);if(n.candidateNames.size===0||!n.hasUsableCandidate)return!0;if(n.candidateNames.size<=IT){for(let i of n.candidateNames)if(i){if(mg.test(i)){if(DT(i).test(e))return!0;continue}if(e.includes(i))return!0}return!1}dg.lastIndex=0;let r;for(;(r=dg.exec(e))!==null;)if(n.candidateNames.has(r[0]))return!0;for(let i of n.nonIdentifierNames)if(e.includes(i))return!0;return!1}function wT(e){return"candidateNames"in e}function DT(e){return new RegExp(`(?<![A-Za-z_$0-9])${$(e)}(?![A-Za-z_$0-9])`)}var ET=j("source-import-paths-by-local-name",{clearGroups:["whole-project","source-file"]});function ks(e,t){let n=
|
|
265
|
+
${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=T(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.some(s=>s.symbolId===r.id)||o.push({symbol:r.symbol,symbolId:r.id,file:r.relative_path})}return n})}var dg=/[A-Za-z_$][A-Za-z0-9_$]*/g,mg=/^[A-Za-z_$][A-Za-z0-9_$]*$/,IT=512;function Di(e){let t=[],n=!1;for(let r of e)r&&(n=!0,mg.test(r)||t.push(r));return{candidateNames:e,hasUsableCandidate:n,nonIdentifierNames:t}}function Es(e,t){let n=wT(t)?t:Di(t);if(n.candidateNames.size===0||!n.hasUsableCandidate)return!0;if(n.candidateNames.size<=IT){for(let i of n.candidateNames)if(i){if(mg.test(i)){if(DT(i).test(e))return!0;continue}if(e.includes(i))return!0}return!1}dg.lastIndex=0;let r;for(;(r=dg.exec(e))!==null;)if(n.candidateNames.has(r[0]))return!0;for(let i of n.nonIdentifierNames)if(e.includes(i))return!0;return!1}function wT(e){return"candidateNames"in e}function DT(e){return new RegExp(`(?<![A-Za-z_$0-9])${$(e)}(?![A-Za-z_$0-9])`)}var ET=j("source-import-paths-by-local-name",{clearGroups:["whole-project","source-file"]});function ks(e,t){let n=hn(t);return ET.get(e,n,()=>kT(e,n))}function kT(e,t){let n=new Map;for(let r of re(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i&&fg(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)fg(n,o,r.sourcePath)}return n}function fg(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Fr(e,t,n){let r=Qt(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[Ei(r[0])];let i=r.filter(c=>c.file===t);if(i.length>0)return i.map(Ei);let o=ks(e,t),s=o.get(n);if(s)for(let c of s){let l=r.filter(u=>Ve(c,u.file));if(l.length>0)return l.map(Ei)}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=>Ve(c,u.file));if(l.length>0&&l.length===r.length)return l.map(Ei)}return[]}function pg(e,t,n){let r=Fr(e,t,n);if(r.length>0)return r;let i=Qt(e).get(n);return!i||i.length===0?[]:i.map(Ei)}function gg(e,t,n={}){let r=xs(e,t);if(!r)return[];let i=T(r.symbol);if(!i)return[];if(n.semantic!==!1&&n.semanticEvidence){let s=n.semanticEvidence.references(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 Ps(e,a)}}let o=new Map;for(let s of $e(e)){let a=P(e,s);if(!a||a.indexOf(i)===-1||s!==r.relativePath&&!Fr(e,s,i).some(u=>u.symbolId===r.symbolId))continue;let c=vs(e,s,i,s===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});c.length>0&&o.set(s,c)}return Ps(e,o)}function hg(e,t,n={}){let r=new Map;for(let c of t){if(!c.leaf)continue;let l=r.get(c.leaf)??[];l.push(c),r.set(c.leaf,l)}if(r.size===0)return new Map;let i=new Set(t.map(c=>c.symbolId)),o=new Set(r.keys()),s=Di(o),a=new Map;for(let c of $e(e)){if(n.skipPath?.(c)||!Es(P(e,c),s))continue;let l=og(e,c);if(l.size!==0){for(let u of l)if(r.has(u))for(let d of Fr(e,c,u)){if(!i.has(d.symbolId)||c===d.relativePath)continue;let m=a.get(d.symbolId);m||(m=new Set,a.set(d.symbolId,m)),m.add(c)}}}return a}function Ei(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function Ps(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=Q(e,i);for(let a of o){let c=Dt(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 ki(e,t){let n=NT(e,t);return n?Ps(e,TT(e,n.match,n.identifier)):[]}function Et(e,t,n={}){return PT(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function PT(e,t,n={}){let r=gg(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence}),i=r.length>0?yg(r,"source-attribution"):yg(ki(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function yg(e,t){return e.map(n=>({...n,provenance:t}))}function TT(e,t,n){let r=new Map;for(let[i,o]of _T(e,t.symbolId))r.set(i,FT(e,i,o,t,n));return r}function _T(e,t){let n=new Map;for(let r of _r(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 FT(e,t,n,r,i){let o=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},s=i?vs(e,t,i,o):[];return n.flatMap(a=>LT(s,a))}function LT(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function NT(e,t){let n=xs(e,t);return n?{match:n,identifier:T(n.symbol)||null}:null}var bg=jn({kind:"file-dependency-graph",invalidation:K("file-dependency-graph"),serialize:e=>JSON.stringify(e),deserialize:HT}),AT=j("file-dep-graph",{clearGroups:["whole-project"]});function ie(e,t,n={}){let r=n.scipEdges??"all-references",i=n.sourceEdges??"imports-only",o=jT(t,r,i);return AT.get(e,o,()=>{let s=new Set(N(e,{includeIgnored:!1})),a=Te(e),c=0,l=0,u=null,d=!1,m=0,f=0;return w("file-dep-graph.product",()=>{if(a){let h=bg.read(e,o,a);if(h){d=!0;let C=$T(h);return c=h.sourceFileCount,l=h.sourceEdgeCount,m=h.scipEdgeCount,f=C.size,u=h.sourceDependencyFingerprint,C}}let p=w("file-dep-graph.source-imports",()=>{let h=MT(e,s,t,i);return c=h.files.length,l=h.edges.length,u=h.fingerprint,h},()=>({scope:t??null,sourceEdges:i,files:c,edges:l})),g=new Map,y=(h,C)=>zT(e,g,s,h,C);w("file-dep-graph.scip-edges",()=>{for(let h of GT(e,t,r))m+=1,y(h.from_file,h.to_file)},()=>({scope:t??null,edges:m}));for(let h of p.edges)y(h.fromFile,h.toFile);return f=g.size,a&&bg.write(e,o,a,{sourceDependencyFingerprint:p.fingerprint,sourceFileCount:p.files.length,sourceEdgeCount:p.edges.length,scipEdgeCount:m,graph:BT(g)}),g},()=>({scope:t??null,available:a!==null,hit:d,files:c,sourceEdges:l,sourceEdgeMode:i,scipEdges:m,graphFiles:f,sourceDependencyFingerprint:u}))})}function MT(e,t,n,r){let i=[],o=[];for(let s of t)if(!(n&&!s.includes(n))){i.push(s);for(let a of re(e,s))a.sourcePath&&o.push({fromFile:s,toFile:a.sourcePath});if(r==="imports-and-reexports")for(let a of Kt(e,s))a.sourcePath&&o.push({fromFile:s,toFile:a.sourcePath})}return{files:i,edges:o,fingerprint:OT(i,o)}}function OT(e,t){let n=t.map(r=>`${r.fromFile}\0${r.toFile}`).sort();return he(JSON.stringify({files:e,edges:n}))}function jT(e,t,n){return`edge-mode-v3:${t}:${n}:${e??"<all>"}`}function BT(e){return[...e].map(([t,n])=>[t,[...n]])}function $T(e){return new Map(e.graph.map(([t,n])=>[t,new Set(n)]))}function HT(e){let t=JSON.parse(e);return UT(t)?t:null}function UT(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.sourceDependencyFingerprint=="string"&&typeof t.sourceFileCount=="number"&&typeof t.sourceEdgeCount=="number"&&typeof t.scipEdgeCount=="number"&&Array.isArray(t.graph)&&t.graph.every(WT)}function WT(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&Array.isArray(e[1])&&e[1].every(t=>typeof t=="string")}function GT(e,t,n){let r=t?"AND d1.relative_path LIKE ?":"",i=t?[`%${t}%`]:[],o=n==="imports-only"?"AND m.role = 2":"AND m.role != 1";return e.all(`SELECT DISTINCT
|
|
266
266
|
d1.relative_path AS from_file,
|
|
267
267
|
d2.relative_path AS to_file
|
|
268
268
|
FROM mentions m
|
|
@@ -280,15 +280,15 @@ ${m}`,l+=1+m.length,u+=Ci(m),r+=m.length+1}let d=eP(c);d&&n.push({...d,start:a,e
|
|
|
280
280
|
WHERE d1.id != d2.id
|
|
281
281
|
${o}
|
|
282
282
|
${e.pathExclusionsFor("d1","d2")}
|
|
283
|
-
${r}`,...i)}function zT(e,t,n,r,i){if(r===i||e.isIgnored(r)||e.isIgnored(i)||!n.has(i))return;let o=t.get(r);o||(o=new Set,t.set(r,o)),o.add(i)}function Ts(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function Sg(e){let t=new Map,n=qT(e),r=new Map;return i=>{let o=VT(i),s=r.get(o);if(s!==void 0)return s;if(!n.has(i.file))return r.set(o,i.symbol),i.symbol;let a=t.get(i.file);a||(a=KT(Q(e,i.file)),t.set(i.file,a));let c=JT(a,i);return r.set(o,c),c}}function VT(e){return`${e.file}\0${e.symbol}\0${e.line}`}function qT(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function KT(e){let t=new Map,n=new Map;for(let r of e){let i=t.get(r.leaf);i?i.push(r):t.set(r.leaf,[r]);let o=n.get(r.startLine);o?o.push(r):n.set(r.startLine,[r])}return{definitions:e,byLeaf:t,byStartLine:n}}function JT(e,t){if(e.definitions.length===0)return t.symbol;let n=QT(t.symbol),r=YT(e.byLeaf,n),i=XT(r,t.line);if(i)return i.symbol;let o=e.byStartLine.get(t.line)??[];return o.length===1?o[0].symbol:t.symbol}function YT(e,t){let n=[],r=new Set;for(let i of t)for(let o of e.get(i)??[])r.has(o.symbolId)||(r.add(o.symbolId),n.push(o));return n}function XT(e,t){let n=null;for(let r of e)if(!(r.startLine>t||r.endLine<t)){if(r.startLine===t)return r;(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r)}return n}function QT(e){let t=new Set([e]),r=e.split(/::|\.|#/).filter(Boolean).at(-1);return r&&t.add(r),t}function Cg(e,t){let r=re(e,t).map(i=>e_(t,i));return{usage:r,positions:t_(e,t,r)}}function xg(e,t){return{importUsage(n){let r=e.importUsageFacts(n);if(!t||r.positions.length===0)return r.usage;let i=t.importDefinitionsForFile(n,r.positions);return i.available?ZT(r.usage,i.sourcePaths):r.usage}}}function ZT(e,t){return e.map((n,r)=>{let i=t.get(String(r));return i?{...n,sourcePath:i}:n})}function e_(e,t){let n=t.isTypeOnly===!0,r=t.kind==="side-effect"||n||t.used;return{importer:e,sourcePath:t.sourcePath,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:n,isUsed:r,isTypeUsed:n,isValueUsed:t.kind==="side-effect"||!n&&t.used,references:[]}}function t_(e,t,n){let r=q(e,t);if(!r)return[];let i=n_(r.rootNode),o=new Map;for(let a of i){let c=o.get(Dl(a.importedName,a.localName));c?c.push(a.position):o.set(Dl(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let l=o.get(Dl(a.importedName,a.localName??a.importedName))?.shift();l&&s.push({...l,id:String(c),file:t})}),s}function n_(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let r=n.namedChildren.find(i=>i.type!=="visibility_modifier");r&&t.push(..._s(r,""))}return t.filter(n=>n.importedName!=="*")}function _s(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:wl(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:wl(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=kr(t,n.text);return r.namedChildren.flatMap(o=>_s(o,i))}case"use_list":return e.namedChildren.flatMap(n=>_s(n,t));case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);return!n||!r?[]:_s(n,t).map(i=>({...i,localName:r.text}))}case"use_wildcard":{let n=e.namedChild(0),r="*";return[{importedName:r,localName:r,position:wl(n??e,r)}]}default:return[]}}function wl(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+r_(t)}}function r_(e){return Math.max(0,Math.min(e.length-1,1))}function Dl(e,t){return`${e}\0${t}`}import{spawnSync as Gl}from"child_process";import{existsSync as zl}from"fs";import{fileURLToPath as DF}from"url";function
|
|
284
|
-
`:i),S_(r,e)}import{execFileSync as T_}from"child_process";import{existsSync as R_,readFileSync as v_}from"fs";import{deserializeSCIP as I_,SymbolRole as w_}from"@c4312/scip";import{existsSync as
|
|
285
|
-
`).filter(Boolean)}catch{return null}}function q_(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?Kg(e,r):e,o;try{o=O_(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){Jg(a)||n.push(a);continue}t.push(a)}}return t}function Jg(e){let t=e.split("/");return e==="meta.json"||t.some(n=>K_.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var K_=new Set([".git","node_modules",".scipquery-cache",".scipquery-generations",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]);var Y_=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function Yg(e){let t=Al(e,{includePath:X_});return J_("sha256").update(JSON.stringify(t)).digest("hex")}function X_(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||Y_.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}var rh=2,rF=5e3,iF=5e3,ih=10,oF=3e4;function Qg(e,t,n,r=ch){let i=r.engineIdentity(e),o={protocolVersion:rh,projectRoot:r.canonicalProjectRoot(e),projectFingerprint:r.projectFingerprint(e),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(t),environment:oh(r.environment())};return{key:Os(Ms(o)),...o}}function Ti(e,t,n){return e.protocolVersion===rh&&(t-e.heartbeatAtMs<=rF||e.busyUntilMs!==void 0&&t<=e.busyUntilMs)&&n(e.pid)}function Ol(e,t,n){let r;try{r=Os(js(t))}catch{r="missing"}let i=Os(Ms({projectRoot:Et(e),serverPath:Et(t),serverFingerprint:r})).slice(0,20);return Et(n,`scip-query-rust-session-${i}`)}function Zg(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function oh(e){return Object.fromEntries(Object.entries(e).filter(([t])=>ah(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function sh(e,t){let n=t.runtime??uF,r=t.identityRuntime??ch,i=Ol(e,t.serverPath,t.tempRoot??nF()),o=!1,s=(a,c)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return aF(i,t.serverPath,t.semanticWorkerPath,a,c,n)};return{requestSemantic(a,c){let l=Qg(e,t.semanticWorkerPath,a,r),u=n.now()+Math.max(1,c-1e3);return s({kind:"semantic",identityKey:l.key,workerEnvironment:th(),request:{...a,readinessDeadlineMs:u,referenceRetryTimeoutMs:sF(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:Zg(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let l=Qg(e,t.semanticWorkerPath,a,r),u=n.now()+Math.max(1,c-1e3);return s({kind:"import-definitions",identityKey:l.key,workerEnvironment:th(),request:{...a,readinessDeadlineMs:u,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:Zg(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){o=!0}}}function sF(e,t){return t!==void 0?t:e===void 0?oF:void 0}function aF(e,t,n,r,i,o){let s=o.randomId(),a=o.now(),c=Et(e,"requests"),l=Et(e,"responses"),u=Et(c,`${s}.json`),d=Et(l,`${s}.json`);Xg(c,{recursive:!0}),Xg(l,{recursive:!0}),_e(u,{id:s,request:r});let m=o.now()+i;try{for(eh(e,t,n,m,o);o.now()<=m;){if(nh(d)){let p=cF(js(d,"utf8"));if(!p.ok)throw new Error(p.error);return U()&&mn({type:"span",name:"rust.semantic.durable-session.request",durationMs:o.now()-a,ok:!0,session:p.session,kind:r.kind}),p.response}let f=_i(e);(!f||!Ti(f,o.now(),o.isProcessAlive))&&eh(e,t,n,m,o),o.sleep(ih)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}finally{Ml(u,{force:!0}),Ml(d,{force:!0})}}function eh(e,t,n,r,i){let o=_i(e);if(o&&Ti(o,i.now(),i.isProcessAlive))return;Ml(Et(e,"server.json"),{force:!0}),i.spawnServer(t,e,n);let s=Math.min(r,i.now()+iF);for(;i.now()<=s;){let a=_i(e);if(a&&Ti(a,i.now(),i.isProcessAlive))return;i.sleep(ih)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function _i(e){try{let t=JSON.parse(js(Et(e,"server.json"),"utf8"));return typeof t.protocolVersion!="number"||typeof t.pid!="number"||typeof t.heartbeatAtMs!="number"||t.busyUntilMs!==void 0&&typeof t.busyUntilMs!="number"?null:{protocolVersion:t.protocolVersion,pid:t.pid,heartbeatAtMs:t.heartbeatAtMs,...t.busyUntilMs===void 0?{}:{busyUntilMs:t.busyUntilMs}}}catch{return null}}function cF(e){try{let t=JSON.parse(e);return t.ok===!0&&(t.session==="created"||t.session==="reused"||t.session==="invalidated")&&t.response&&typeof t.response=="object"?{ok:!0,session:t.session,response:t.response}:{ok:!1,error:typeof t.error=="string"?t.error:"helper wrote an invalid response"}}catch(t){return{ok:!1,error:`helper wrote malformed JSON: ${t instanceof Error?t.message:String(t)}`}}}function th(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>lF(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function ah(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function lF(e){return ah(e)||e.startsWith("SCIP_RUST_")||e==="SCIP_QUERY_PROFILE"||e==="SCIP_QUERY_PROFILE_CACHE_STATE"||e==="SCIP_QUERY_PROFILE_COMMAND"||e==="SCIP_QUERY_PROFILE_OUT"||e==="SCIP_QUERY_PROFILE_RUN_ID"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND"||e==="SCIP_QUERY_PROFILE_MIN_MS"}var ch={canonicalProjectRoot(e){try{return tF(e)}catch{return Et(e)}},projectFingerprint(e){return Yg(e)},engineIdentity:Ll,fileFingerprint(e){return Os(js(e))},environment(){return oh(process.env)}},uF={now:Date.now,randomId:eF,isProcessAlive:ct,spawnServer(e,t,n){if(!nh(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);Q_(process.execPath,[e,t,n],{detached:!0,stdio:"ignore"}).unref()},sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)}};function Ms(e){return Array.isArray(e)?`[${e.map(Ms).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Ms(n)}`).join(",")}}`:JSON.stringify(e)}function Os(e){return Z_("sha256").update(e).digest("hex")}var dh=15e3,mh=8,ph=5e3,gF=64,hF=96,Ul=class{constructor(t,n,r={}){this.projectRoot=t;this.status=n;this.opts=r;this.requester=r.requester??SF(t,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION)}projectRoot;status;opts;requester;referencesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:n.reason,references:Fi(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,references:Rn(t,new Map(r.references),new Set(r.incompleteReferenceSymbolIds??[]))}}catch(r){return this.opts.fallbackReferenceResolver?.referencesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),references:Fi(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:n.reason,callees:Li(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,callees:$l(t,new Map(r.callees??[]))}}catch(r){return this.opts.fallbackCalleeResolver?.calleesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),callees:Li(t)}}}referencesAndCalleesForDefinitions(t,n){let r=this.status(this.projectRoot);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,references:Fi(t),callees:Li(n)};let i=[...t,...n];try{let o=this.requestSession(r.resolvedBinary,i,{includeReferences:t.length>0,includeCallees:n.length>0,referenceDefinitions:t,calleeDefinitions:n});return{available:o.available,resolvedBinary:r.resolvedBinary,reason:o.reason,references:Rn(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:$l(n,new Map(o.callees??[]))}}catch(o){return this.fallbackReferencesAndCallees(r,t,n,o)}}signaturesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:n.reason,signatures:fh(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,signatures:IF(t,new Map(r.signatures??[]))}}catch(r){return this.opts.fallbackSignatureResolver?.signaturesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),signatures:fh(t)}}}importDefinitionsForFile(t,n){let r=this.status(this.projectRoot);if(n.length===0)return{available:r.available,resolvedBinary:r.resolvedBinary,reason:r.reason,sourcePaths:new Map};if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,sourcePaths:new Map(n.map(i=>[i.id,null]))};try{let i=this.requestImportDefinitions(r.resolvedBinary,t,n);return{available:i.available,resolvedBinary:r.resolvedBinary,reason:i.reason,sourcePaths:new Map(i.sourcePaths)}}catch(i){return{available:!1,resolvedBinary:r.resolvedBinary,reason:i instanceof Error?i.message:String(i),sourcePaths:new Map(n.map(o=>[o.id,null]))}}}dispose(){this.requester.shutdown()}requestSession(t,n,r){let i=Bs(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,dh),o=$s(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=Bs(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,mh),a=$s(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),c=r.referenceDefinitions?[...r.referenceDefinitions]:void 0,l=r.calleeDefinitions?[...r.calleeDefinitions]:void 0,u=r.signatureDefinitions?[...r.signatureDefinitions]:void 0,d=Ai(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,...r}),m={projectRoot:this.projectRoot,rustAnalyzerBinary:t,definitions:[...n],...c?{referenceDefinitions:c}:{},...l?{calleeDefinitions:l}:{},...u?{signatureDefinitions:u}:{},requestTimeoutMs:i,...r.includeReferences!==!1&&o>0?{referenceRetryTimeoutMs:o}:{},diagnosticsTimeoutMs:a,settleDelayMs:d,concurrency:s,includeReferences:r.includeReferences,includeCallees:r.includeCallees,includeSignatures:r.includeSignatures},f=wF(m);return w("rust.semantic.session.request",()=>this.requester.requestSemantic(m,Vn(f,Wl(i,m.referenceRetryTimeoutMs),s)),()=>({definitions:n.length,operationDefinitions:f,referenceDefinitions:m.referenceDefinitions?.length,calleeDefinitions:m.calleeDefinitions?.length,signatureDefinitions:m.signatureDefinitions?.length,references:m.includeReferences!==!1,callees:m.includeCallees===!0,signatures:m.includeSignatures===!0,referenceRetryTimeoutMs:m.referenceRetryTimeoutMs}))}fallbackReferencesAndCallees(t,n,r,i){let o=n.length===0?{available:!0,references:Fi(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=r.length===0?{available:!0,callees:Li(r)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(r);return o&&s?{available:o.available&&s.available,resolvedBinary:o.resolvedBinary??s.resolvedBinary??t.resolvedBinary,reason:o.reason??s.reason,references:Rn(n,o.references),callees:$l(r,s.callees)}:{available:!1,resolvedBinary:t.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:Fi(n),callees:Li(r)}}requestImportDefinitions(t,n,r){let i=Bs(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,dh),o=Bs(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,mh),s=$s(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=$s(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,ph),c={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...r],requestTimeoutMs:i,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return w("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(c,Vn(r.length,i,o)),()=>({file:n,positions:r.length}))}};function gh(e,t,n={}){return new Ul(e,t,n)}function Ai(e,t){let n=Sh(e);if(n!==null)return n;let r=t.includeReferences!==!1;return r&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=gF||r&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=hF?0:ph}function hh(e){let t=e?.trim().toLowerCase(),n=t==="0"||t==="false"||t==="off"||t==="worker",r=t==="1"||t==="true"||t==="on"||t==="durable",i=t===void 0||t==="";return{transport:n||!i&&!r?"worker":"durable",source:i?"default":"environment",fallback:"worker",valid:i||n||r,optOut:"SCIP_RUST_SEMANTIC_DURABLE_SESSION=0"}}function yF(e){return hh(e).transport}function z3(e,t){let n=hh(t);if(n.transport==="worker")return{...n,state:"per-command"};let r=Ni(bh()),i=Ol(e,r,Hl()),o=_i(i);return o?{...n,state:Ti(o,Date.now(),ct)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function bF(e,t){let n=null,r=!1,i=!1,o=!1,s=()=>n??=t(),a=()=>{i||(e.shutdown(),i=!0)},c=(u,d,m)=>{let f=vF(u);r=!0;try{a()}catch{}U()&&mn({type:"span",name:"rust.semantic.durable-session.request",durationMs:m,ok:!1,kind:d,session:"worker-fallback",reason:f})},l=(u,d,m)=>{if(o)throw new Error("Rust semantic failover session was already disposed.");if(r)return m(s());let f=Date.now();try{return d(e)}catch(p){c(p,u,Date.now()-f)}return m(s())};return{requestSemantic(u,d){return l("semantic",m=>m.requestSemantic(u,d),m=>m.requestSemantic(u,d))},requestImportDefinitions(u,d){return l("import-definitions",m=>m.requestImportDefinitions(u,d),m=>m.requestImportDefinitions(u,d))},shutdown(){if(o)return;o=!0;let u=[];try{a()}catch(d){u.push(d)}try{n?.shutdown()}catch(d){u.push(d)}if(u.length>0)throw u[0]}}}function SF(e,t,n={worker:()=>CF(),durable:()=>sh(e,{serverPath:Ni(bh()),semanticWorkerPath:Ni(yh())})}){return yF(t)==="durable"?bF(n.durable(),n.worker):n.worker()}function CF(e={}){let t=null,n=null,r=1,i=!1,o=()=>{n&&(jl(n,{recursive:!0,force:!0}),n=null)},s=()=>{let l=t;t=null,l&&l.terminate(),o()},a=()=>{if(t)return t;let l=e.semanticWorkerPath?mF(e.semanticWorkerPath):yh();if(!dF(Ni(l)))throw new Error(`Rust semantic session worker was not found at ${Ni(l)}. Run npm run build before using built semantic Rust queries.`);return n=lh(Bl(Hl(),"scip-query-rust-session-")),t=new pF(l,e.shareEnvironment?{env:fF}:void 0),t.unref(),t},c=()=>{let l=n??lh(Bl(Hl(),"scip-query-rust-session-"));return n=l,Bl(l,`${r++}.json`)};return{requestSemantic(l,u){if(i)throw new Error("Rust semantic session was already disposed.");let d=a(),m=c(),f=new SharedArrayBuffer(4),p=new Int32Array(f);if(d.postMessage({kind:"semantic",request:l,responsePath:m,sharedBuffer:f}),Atomics.wait(p,0,0,u)==="timed-out")throw s(),new Error(`Rust semantic session worker timed out after ${(u/1e3).toFixed(0)}s`);try{let y=xF(uh(m,"utf8"));if(!y.ok)throw new Error(y.error);return y.response}finally{jl(m,{force:!0})}},requestImportDefinitions(l,u){if(i)throw new Error("Rust semantic session was already disposed.");let d=a(),m=c(),f=new SharedArrayBuffer(4),p=new Int32Array(f);if(d.postMessage({kind:"import-definitions",request:l,responsePath:m,sharedBuffer:f}),Atomics.wait(p,0,0,u)==="timed-out")throw s(),new Error(`Rust semantic import-definition session worker timed out after ${(u/1e3).toFixed(0)}s`);try{let y=RF(uh(m,"utf8"));if(!y.ok)throw new Error(y.error);return y.response}finally{jl(m,{force:!0})}},shutdown(){if(i)return;if(i=!0,!t){o();return}let l=c(),u=new SharedArrayBuffer(4),d=new Int32Array(u);t.postMessage({kind:"shutdown",responsePath:l,sharedBuffer:u}),Atomics.wait(d,0,0,5e3),s()}}}function xF(e){let t=JSON.parse(e);if(!t||typeof t!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=t;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof t.error=="string"?t.error:"Rust semantic session worker failed."}}function RF(e){let t=JSON.parse(e);if(!t||typeof t!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=t;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof t.error=="string"?t.error:"Rust semantic session worker failed."}}function vF(e){let t=e instanceof Error?`${e.name} ${e.message}`.toLowerCase():String(e).toLowerCase();return t.includes("readiness")?"readiness":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("helper")?"helper":"request"}function Fi(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Li(e){return new Map(e.map(t=>[t.symbolId,[]]))}function fh(e){return new Map(e.map(t=>[t.symbolId,null]))}function $l(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function IF(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function wF(e){let t=0;return e.includeReferences!==!1&&(t+=(e.referenceDefinitions??e.definitions).length),e.includeCallees===!0&&(t+=(e.calleeDefinitions??e.definitions).length),e.includeSignatures===!0&&(t+=(e.signatureDefinitions??e.definitions).length),Math.max(1,t)}function Wl(e,t){return t&&t>0?Math.max(e,t):e}function yh(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function bh(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function Bs(e,t){return xn(e)??t}function $s(e,t){return Sh(e)??t}function Sh(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var Vl=15e3,ql=8;function vh(e,t={}){let n=t.status??Ls,r=PF(e,n),i=TF(e,n),o=_F(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!EF(t)?null:gh(e,n,{fallbackReferenceResolver:r,fallbackCalleeResolver:i,fallbackSignatureResolver:o}),a=t.referenceResolver??s??r,c=t.calleeResolver??s??i,l=t.signatureResolver??s??o,u=t.importUsageResolver??xg(t.sourceImportUsageResolver??kF(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,m=t.sourceZeroCalleeOracle,f=t.scipOccurrenceCalleeOracle,p=new Map,g=new Map,y=null,h=null,C=()=>(y??=n(e),y),x=()=>{let E=C();return E.dependencyAvailable?h??E:E},S=E=>{if(E.length===0)return new Map;let D=Mi(E);try{let k=a.referencesForDefinitions(D),L=C();return h={...L,available:k.available,resolvedBinary:k.resolvedBinary??L.resolvedBinary,reason:k.reason??L.reason},k.available?new Map(k.references):Rn(D,k.references)}catch(k){return h={...C(),available:!1,reason:k instanceof Error?k.message:String(k)},Kn(D)}},b=E=>{if(E.length===0)return new Map;let D=Mi(E),k=D.filter(Ch);if(k.length===0)return Jn(D);let L=new Map,ne=Rh(k,f),X=[];for(let F of k)g.has(F.symbolId)?L.set(F.symbolId,g.get(F.symbolId)??[]):ne.has(F.symbolId)?L.set(F.symbolId,ne.get(F.symbolId)??[]):xh(F,m)?L.set(F.symbolId,[]):X.push(F);if(X.length===0)return Lr(D,L,void 0);try{let F=c.calleesForDefinitions(X),ae=C();h={...ae,available:F.available,resolvedBinary:F.resolvedBinary??ae.resolvedBinary,reason:F.reason??ae.reason};let Z=Lr(X,F.callees,d);for(let[ln,bc]of Z)L.set(ln,bc);return Lr(D,L,void 0)}catch(F){return h={...C(),available:!1,reason:F instanceof Error?F.message:String(F)},Jn(D)}},v=(E,D)=>{let k=Mi(E),L=Mi(D),ne=L.filter(Ch),X=new Map,F=Rh(ne,f),ae=[];for(let Z of ne)F.has(Z.symbolId)?X.set(Z.symbolId,F.get(Z.symbolId)??[]):xh(Z,m)?X.set(Z.symbolId,[]):ae.push(Z);if(k.length===0&&ae.length===0)return{references:Kn(k),callees:Lr(L,X,void 0)};try{let Z=s?s.referencesAndCalleesForDefinitions(k,ae):AF(a,c,{referenceDefinitions:k,calleeDefinitions:ae}),ln=C();h={...ln,available:Z.available,resolvedBinary:Z.resolvedBinary??ln.resolvedBinary,reason:Z.reason??ln.reason};let bc=Z.available?new Map(Z.references):Rn(k,Z.references);for(let[Sc,Cc]of Z.callees)X.set(Sc,Cc);let Wm=Lr(L,X,d);for(let[Sc,Cc]of Wm)g.set(Sc,Cc);return{references:bc,callees:Wm}}catch(Z){return h={...C(),available:!1,reason:Z instanceof Error?Z.message:String(Z)},{references:Kn(k),callees:Jn(L)}}},R=E=>{if(E.length===0)return new Map;let D=Mi(E);try{let k=l.signaturesForDefinitions(D),L=C();return h={...L,available:k.available,resolvedBinary:k.resolvedBinary??L.resolvedBinary,reason:k.reason??L.reason},Ih(D,k.signatures)}catch(k){return h={...C(),available:!1,reason:k instanceof Error?k.message:String(k)},Hs(D)}};return{language:"rust",availability:x,dispose:()=>{s?.dispose()},importUsage:E=>{let D=p.get(E);if(D)return D;try{let k=u.importUsage(E);return p.set(E,k),k}catch(k){return h={...C(),available:!1,reason:k instanceof Error?k.message:String(k)},[]}},referencesFor:E=>S([E]).get(E.symbolId)??[],referencesForDefinitions:S,referencesAndCalleesForDefinitions:v,calleesFor:E=>b([E]).get(E.symbolId)??[],calleesForDefinitions:b,signatureFor:E=>R([E]).get(E.symbolId)??null}}function EF(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function kF(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function Mi(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:T(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:ee(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function Ch(e){return e.isFunctionLike}function xh(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function Rh(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function PF(e,t){return{referencesForDefinitions:n=>FF(e,t,n)}}function TF(e,t){return{calleesForDefinitions:n=>LF(e,t,n)}}function _F(e,t){return{signaturesForDefinitions:n=>NF(e,t,n)}}function FF(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,references:Kn(n)};let i=Kl();if(!zl(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,references:Kn(n)};let o=Nr(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Vl),s=Us(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=Nr(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ql),c=Us(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=Ai(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!0}),u={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,...s>0?{referenceRetryTimeoutMs:s}:{},diagnosticsTimeoutMs:c,settleDelayMs:l,concurrency:a},d=Gl(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Vn(n.length,Wl(o,u.referenceRetryTimeoutMs),a)}),m=Jl(d.stdout);if(m)return{available:m.available,resolvedBinary:r.resolvedBinary,reason:m.reason,references:Rn(n,new Map(m.references),new Set(m.incompleteReferenceSymbolIds??[]))};let f=d.error instanceof Error?d.error.message:d.stderr.trim()||`Rust semantic worker exited with status ${d.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:f,references:Kn(n)}}function LF(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,callees:Jn(n)};let i=Kl();if(!zl(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,callees:Jn(n)};let o=Nr(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Vl),s=Nr(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ql),a=Us(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=Ai(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!0},u=Gl(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Vn(n.length,o,s)}),d=Jl(u.stdout);if(d)return{available:d.available,resolvedBinary:r.resolvedBinary,reason:d.reason,callees:Lr(n,new Map(d.callees??[]),void 0)};let m=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,callees:Jn(n)}}function NF(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,signatures:Hs(n)};let i=Kl();if(!zl(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,signatures:Hs(n)};let o=Nr(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Vl),s=Nr(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ql),a=Us(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=Ai(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!1,includeSignatures:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!1,includeSignatures:!0},u=Gl(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Vn(n.length,o,s)}),d=Jl(u.stdout);if(d)return{available:d.available,resolvedBinary:r.resolvedBinary,reason:d.reason,signatures:Ih(n,new Map(d.signatures??[]))};let m=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,signatures:Hs(n)}}function AF(e,t,n){let r=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:Kn(n.referenceDefinitions)},i=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:Jn(n.calleeDefinitions)};return{available:r.available&&i.available,resolvedBinary:r.resolvedBinary??i.resolvedBinary,reason:r.reason??i.reason,references:r.references,callees:i.callees}}function Kn(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Jn(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Hs(e){return new Map(e.map(t=>[t.symbolId,null]))}function Lr(e,t,n){let r=0,i=0;return w("rust.semantic.callees.complete-map",()=>{let o=new Map;for(let s of e){let a=t.get(s.symbolId)??[];a.length>0&&(r+=1),i+=a.length,o.set(s.symbolId,a.map(c=>({...c,symbol:n?n(c):c.symbol})))}return o},()=>({definitions:e.length,rows:r,callees:i,resolveSymbols:!!n}))}function Ih(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function Kl(){return DF(new URL("./rust-semantic-worker.js",import.meta.url))}function Jl(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return typeof n.available!="boolean"||!Array.isArray(n.references)?null:{available:n.available,reason:typeof n.reason=="string"?n.reason:void 0,references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(r=>typeof r=="number"):void 0,callees:Array.isArray(n.callees)?n.callees:void 0,signatures:Array.isArray(n.signatures)?n.signatures:void 0}}catch{return null}}function Nr(e,t){return xn(e)??t}function Us(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as MF,readFileSync as OF}from"fs";import{deserializeSCIP as jF,SymbolRole as BF}from"@c4312/scip";var Yl=new WeakMap;function Dh(e,t){let n=t.filter($F);if(n.length===0)return new Map;let r=!1,i=0,o=0;return w("rust.scip-occurrence.callees",()=>{let s=WF(e);if(r=!!s,!s)return new Map;let a=new Map;for(let c of n){let l=HF(e,s,c);l!==null&&(a.set(c.symbolId,l),i+=1,o+=l.length)}return a},()=>({definitions:t.length,candidates:n.length,indexAvailable:r,resolvedDefinitions:i,resolvedCallees:o}))}function $F(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||Ie(e.symbol))}function HF(e,t,n){let r=G(e,n.relativePath);if(!r||r.language!=="rust")return null;let i=r.callables.find(l=>l.startLine!==n.startLine||l.endLine!==n.endLine?!1:l.name===n.leaf||n.leaf.endsWith(l.name)||l.name.endsWith(n.leaf));if(!i)return null;let o=r.callSites.filter(l=>l.line>=i.startLine&&l.line<=i.endLine);if(o.length===0)return null;let s=(t.occurrencesByFile.get(n.relativePath)??[]).filter(l=>l.line>=i.startLine&&l.line<=i.endLine&&l.callee.symbol!==n.symbol);if(s.some(l=>l.traitImplMember)||!UF(o,s))return null;let a=[],c=new Set;for(let l of s){let u=`${l.callee.symbol}\0${l.callee.file}\0${l.callee.line}`;c.has(u)||(c.add(u),a.push(l.callee))}return a}function UF(e,t){let n=wh(e),r=wh(t);if(n.size!==r.size)return!1;for(let[i,o]of n)if(r.get(i)!==o)return!1;return!0}function wh(e){let t=new Map;for(let n of e){let r=n.calleeLeaf??n.leaf;if(!r)continue;let i=`${n.line}\0${r}`;t.set(i,(t.get(i)??0)+1)}return t}function WF(e){if(Yl.has(e))return Yl.get(e)??null;let t=GF(e);return Yl.set(e,t),t}function GF(e){if(!MF(e.config.indexPath))return null;try{let t=xe(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),r=jF(OF(e.config.indexPath)),i=new Map;for(let o of r.documents??[]){let s=o.relativePath;if(!s||!s.endsWith(".rs")||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&BF.Definition)!==0)continue;let l=n.get(c.symbol);if(!l)continue;let u=c.range?.[0];Number.isInteger(u)&&a.push({line:u,leaf:l.leaf,traitImplMember:Ie(l.symbol),callee:{symbol:l.symbol,file:l.relativePath,line:l.startLine}})}i.set(s,a)}return{occurrencesByFile:i}}catch{return null}}var Ws=class{sessions=new WeakMap;getOrCreate(t,n,r){let i=zF(t,n),o=this.sessions.get(t);o||(o=new Map,this.sessions.set(t,o));let s=o.get(i);if(s)return s.hits+=1,s.lastUsedAtMs=Date.now(),s.provider;let a=Date.now(),c=r();return o.set(i,{key:i,language:n,projectRoot:t.config.projectRoot,provider:c,createdAtMs:a,lastUsedAtMs:a,hits:1}),c}sessionsFor(t){return[...this.sessions.get(t)?.values()??[]]}clear(t){let n=this.sessions.get(t);if(n)for(let r of n.values())r.provider.dispose?.();this.sessions.delete(t)}};function zF(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as _L}from"crypto";import{existsSync as FL,mkdirSync as ey,readFileSync as LL,rmSync as ty}from"fs";import{dirname as NL,resolve as ny}from"path";import{readFileSync as VF}from"fs";import{join as Xl}from"path";var p6=4,Eh=5e3,qF="watch.lock",KF="watch-state.json",JF="watch-activity.json";function kh(e){return{lockPath:Xl(e,qF),statePath:Xl(e,KF),activityPath:Xl(e,JF)}}function Ql(e){try{return YF(JSON.parse(VF(e,"utf8")))}catch{return null}}function YF(e){if(!e||typeof e!="object")return null;let t=e;return t.version!==1||typeof t.protocolVersion!="number"||typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0||typeof t.projectRoot!="string"||t.worktreeId!==void 0&&(typeof t.worktreeId!="string"||t.worktreeId.length===0)||typeof t.cliVersion!="string"||!yt(t.startedAt)||!yt(t.heartbeatAt)||!yt(t.lastActivityAt)||!XF(t.watcher)||t.idleDeadlineAt!==void 0&&!yt(t.idleDeadlineAt)||t.indexGeneration!==void 0&&!/^[a-f0-9]{64}$/.test(t.indexGeneration)||t.lastError!==void 0&&!QF(t.lastError)||t.lastRefresh!==void 0&&!ZF(t.lastRefresh)||t.typescriptSemantic!==void 0&&!eL(t.typescriptSemantic)||t.typescriptIndex!==void 0&&!tL(t.typescriptIndex)?null:t}function yt(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function XF(e){if(!e||typeof e!="object"||!("state"in e))return!1;let t=e;switch(t.state){case"idle":return!0;case"waiting":return lt(t.changedFiles)&<(t.reindexAt);case"indexing":return lt(t.startedAt);case"cooldown":return lt(t.until)&&typeof t.dirty=="boolean";default:return!1}}function QF(e){if(!e||typeof e!="object")return!1;let t=e;return yt(t.at)&&typeof t.message=="string"}function ZF(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.trigger?.kind=="string"&&typeof t.result=="string"&&yt(t.startedAt)&&yt(t.completedAt)&<(t.durationMs)}function eL(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.protocolVersion=="number"&&(t.state==="idle"||t.state==="ready"||t.state==="unavailable"||t.state==="error")&<(t.requests)&<(t.sessionsCreated)&<(t.sessionsReused)&<(t.sessionsRefreshed)&<(t.sessionsReplaced)&<(t.projectsCreated)&&(t.lastRequestAt===void 0||yt(t.lastRequestAt))&&(t.lastError===void 0||typeof t.lastError=="string")&&(t.busyUntil===void 0||yt(t.busyUntil))}function tL(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.protocolVersion=="number"&&(t.state==="idle"||t.state==="ready"||t.state==="unavailable"||t.state==="error")&&Yn(t.requests)&&Yn(t.sessionsCreated)&&Yn(t.sessionsReplaced)&&Yn(t.initializations)&&Yn(t.programUpdates)&&Yn(t.documentsEmitted)&&Yn(t.documentsRemoved)&&(t.lastRequestAt===void 0||yt(t.lastRequestAt))&&(t.lastDurationMs===void 0||lt(t.lastDurationMs)&&t.lastDurationMs>=0)&&(t.lastError===void 0||typeof t.lastError=="string")&&(t.busyUntil===void 0||yt(t.busyUntil))}function lt(e){return typeof e=="number"&&Number.isFinite(e)}function Yn(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}import{performance as W}from"perf_hooks";function ut(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import Ph from"path";function nL(e,t){return e.getReferences().map(n=>{let r=n.getNode();return Gs(r,t)})}function rL(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function Th(e,t,n,r){let i=[];for(let o of rL(e))for(let s of nL(o,r))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||i.push(s);for(let o of n)i.push(o);return Ar(i)}function _h(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();Mr(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:Gs(a,r),node:a}))}return i}function Gs(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:Mr(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function Fh(e,t,n){let r=e.getSourceFile(),i=eu(r,e),o=e.getText(),s=new RegExp(`\\b${$(o)}\\b`,"g"),a=r.getFullText().split(`
|
|
286
|
-
`),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 Ar(c.filter(l=>Mr(n,Ph.join(n,l.file))===t))}function Zl(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 eu(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Ar(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 Mr(e,t){let n=Ph.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function Lh(e,t,n,r){let i=iL(t,r);return i.size===0?new Map:oL(e,n,i)}function iL(e,t){let n=new Map;for(let r of Q(e,t)){let i=T(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function oL(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of sL(e,o)){let a=n.get(s);if(!a)continue;let c=eu(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 sL(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 aL=j("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function Nh(e,t,n,r){let i=ru(e,t),o=tu(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||T(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return tu(s,n)}function nu(e,t,n,r){return tu(ru(e,t).get(r)??[],n)}function Ah(e,t){let n=new Map;for(let[r,i]of ru(e,t)){let o=i[0];o&&n.set(r,o)}return n}function ru(e,t){return aL.get(e,t,()=>{let n=new Map;for(let r of Q(e,t)){let i=r.leaf||T(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 tu(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 iu from"path";var Oi=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function kt(e){let t=e.toLowerCase();return Oi.some(n=>t.endsWith(n))}function Mh(e,t){let n=new Map,r=null,i=null,o=()=>(i??=N(e,{extensions:Oi}),i),s=()=>(r??=w("typescript.source-file-index",()=>cL(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),r),a=c=>kt(c)?ut(n,c,()=>{let l=ji(iu.resolve(e.config.projectRoot,c));for(let{project:u,sourceFiles:d}of s()){let m=d.get(l)??null;if(m||(m=u.addSourceFileAtPathIfExists(l)??null,m&&d.set(ji(m.getFilePath()),m)),m)return{project:u,sourceFile:m}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function cL(e,t,n){let r=t.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[ji(o.getFilePath()),o]))}));for(let i of n){let o=ji(iu.resolve(e,i));for(let s of r){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){s.sourceFiles.set(ji(a.getFilePath()),a);break}}}return r}function ji(e){return iu.resolve(e)}function ou(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Oh(e){let t=`${e.relativeDir}/src`;return[`${t}/index.ts`,`${t}/index.tsx`,`${t}/index.mts`,`${t}/index.cts`]}import{existsSync as Bi,readFileSync as lL}from"fs";import Fe from"path";var su=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function au(e,t){let r=t?Fe.dirname(Fe.join(e,t)):e,i=Fe.resolve(e);for(;r.startsWith(i);){for(let s of su){let a=Fe.join(r,s);if(Bi(a))return a}let o=Fe.dirname(r);if(o===r)break;r=o}for(let o of su){let s=Fe.join(e,o);if(Bi(s))return s}return null}function jh(e){let t=e.config.projectRoot,n=new Set(uL(t,e.config.semantic?.typescript?.tsconfigs)),r=N(e,{includeIgnored:!1,extensions:Oi});for(let i of r){let o=au(t,i);o&&n.add(Fe.resolve(o))}if(n.size===0){let i=au(t);i&&n.add(Fe.resolve(i))}return[...n].filter(i=>!Bh(t,i)).sort((i,o)=>i.localeCompare(o))}function uL(e,t=[]){let n=new Set;for(let r of t){let i=Fe.isAbsolute(r)?r:Fe.join(e,r);Bi(i)&&n.add(Fe.resolve(i))}for(let r of dL(e))for(let i of su){let o=Fe.join(r,i);Bi(o)&&n.add(Fe.resolve(o))}if(n.size===0){let r=au(e);r&&n.add(Fe.resolve(r))}return[...n].filter(r=>!Bh(e,r)).sort((r,i)=>r.localeCompare(i))}function dL(e){let t=Fe.join(e,"package.json");if(!Bi(t))return[];let n;try{n=JSON.parse(lL(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>Xc(e,i))}function Bh(e,t){let n=Fe.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 mL}from"module";var $h=mL(import.meta.url),$i,zs;function cu(){if($i!==void 0)return $i;try{$i=$h("ts-morph")}catch{$i=null}return $i}function Vs(){if(zs)return zs;let e=cu();if(!e)return"ts-morph:unavailable";let t="unknown";try{t=$h("ts-morph/package.json").version??"unknown"}catch{}return zs=`ts-morph:${t}:typescript:${e.ts.version}`,zs}function Hh(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!0})}))}function qs(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function Ks(e,t){let n=new Map(e.map(i=>[i.symbol,i])),r=new Map(e.map(i=>[i.symbolId,[]]));for(let i of t.values())for(let o of i){let s=n.get(o.targetSymbol);s&&r.get(s.symbolId).push(o.location)}for(let[i,o]of r)r.set(i,fL(o));return r}function Gh(e,t,n){let r=Wh(e,t),i=Wh(e,n),o=[...r].filter(d=>!i.has(d)).sort(),s=[...i].filter(d=>!r.has(d)).sort(),a=Uh(e,t),c=Uh(e,n),l=[...a].filter(d=>!c.has(d)).sort(),u=[...c].filter(d=>!a.has(d)).sort();return{passed:o.length===0&&s.length===0,expectedCount:r.size,actualCount:i.size,missing:o,extra:s,callerFiles:{passed:l.length===0&&u.length===0,expectedCount:a.size,actualCount:c.size,missing:l,extra:u}}}function Uh(e,t){let n=new Set;for(let r of e)for(let i of t.get(r.symbolId)??[])i.file!==r.relativePath&&n.add(`${r.symbol}\0${i.file}`);return n}function zh(e,t,n){let r=new Set(n),i=new Map(n.map(o=>[o,[]]));for(let o of e)for(let s of t.get(o.symbolId)??[])r.has(s.file)&&i.get(s.file).push({targetSymbol:o.symbol,location:s});for(let[o,s]of i)i.set(o,pL(s));return i}function Wh(e,t){let n=new Set;for(let r of e)for(let i of t.get(r.symbolId)??[])n.add(`${r.symbol}\0${i.file}\0${i.line}\0${i.column}`);return n}function fL(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}\0${n.column}`,n);return[...t.values()].sort(Vh)}function pL(e){let t=new Map;for(let n of e){let{location:r}=n;t.set(`${n.targetSymbol}\0${r.file}\0${r.line}\0${r.column}`,n)}return[...t.values()].sort((n,r)=>n.targetSymbol.localeCompare(r.targetSymbol)||Vh(n.location,r.location))}function Vh(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.column-t.column}var gL=32;function Qh(e,t){let n=w("typescript.provider.load",()=>cu());if(!n)return qs("ts-morph is not installed");let r=w("typescript.provider.tsconfig-discovery",()=>jh(e));if(r.length===0)return qs("no tsconfig found");try{let i=w("typescript.provider.project-bundles",()=>Hh(n,r),()=>({tsconfigs:r.length}));return hL(e,n,i)}catch(i){return qs(i instanceof Error?i.message:String(i),r[0],r)}}function hL(e,t,n,r={}){return w("typescript.provider.construct",()=>new uu(e,t,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var uu=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Rr(t.config.projectRoot),this.sourceFiles=Mh(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;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return ut(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=bL();return w("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,r),()=>({file:t,...r}))})}referencesFor(t){return ut(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){let r=new Map,i=U(),o=[];for(let u of t){let d=this.referencesCache.get(u.symbolId);d?r.set(u.symbolId,d):o.push(u)}if(o.length===0)return r;let s=o,a=n.exact?[]:o.filter(u=>!Kh(u));if(a.length>=gL){let u=this.referencesForDefinitionsBySymbolScan(a);for(let d of a){let m=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}if(s=o.filter(d=>Kh(d)),s.length===0)return r}let c=new Map;for(let u of s){let d=c.get(u.relativePath);d?d.push(u):c.set(u.relativePath,[u])}let l=[];for(let[u,d]of c){let m=Jh();w("typescript.references-map.file",()=>{let f=this.definitionNodesForFile(u);for(let p of d){i&&(m.cacheMisses+=1);let g=f.get(p.symbolId)??null;i&&(g?m.nodeHits+=1:m.nodeMisses+=1);try{let y=this.referencesForDefinitionNode(p,g,i?m:void 0);this.referencesCache.set(p.symbolId,y),r.set(p.symbolId,y)}catch{m.preciseSearchFailures+=1,l.push(p)}}},()=>({relativePath:u,definitions:d.length,...Yh(m)}))}if(l.length>0){let u=this.referencesForDefinitionsBySymbolScan(l);for(let d of l){let m=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}}return r}referenceFragmentsForFiles(t){let n=xe(this.db).filter(o=>kt(o.relativePath)),r=t.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(n,r);return zh(n,i,r)}referencesForDefinitionsBySymbolScan(t,n){let r=U(),i=Jh(),o=new Map,s=new Set(t.map(c=>c.symbolId)),a=new Map(t.map(c=>[c.symbolId,c]));for(let c of t)o.set(c.symbolId,[]);return w("typescript.references-map.inverted-scan",()=>{let c=r?W.now():0,l=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let y of t){let h=l.get(y.symbolId)??[];if(h.length>0){let C=o.get(y.symbolId)??[];C.push(...h),o.set(y.symbolId,C)}r&&(i.packageReferenceCount+=h.length)}r&&(i.packageRefsMs+=W.now()-c);let u=new Map,d=new Map,m=this.hierarchyTargetsForDefinitions(t),f=new Set(t.map(y=>y.leaf).filter(Boolean)),p=r?W.now():0;for(let y of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(y))continue;let h=this.sourceFiles.sourceFile(y);h&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(h,y,s,a,m,f,u,d,o,r?i:void 0))}r&&(i.scanMs+=W.now()-p);let g=r?W.now():0;this.addHierarchyMemberReferences(t,o,r?i:void 0),r&&(i.hierarchyMs+=W.now()-g);for(let[y,h]of o){let C=Ar(h);o.set(y,C),r&&(i.referenceCount+=C.length)}},()=>({definitions:t.length,...Yh(i)})),o}addReferencesFromSourceFileScan(t,n,r,i,o,s,a,c,l,u){let d=this.compilerCheckerForSourceFile(t),m=t.compilerNode,f=xL(t),p=g=>{if(this.tsMorph.ts.isIdentifier(g)){if(u&&(u.identifiers+=1),!s.has(g.text)&&!f.has(g.text)){this.tsMorph.ts.forEachChild(g,p);return}let y=this.compilerReferenceSymbol(d,g,u);if(y){let h;a.has(y)?h=a.get(y)??null:(h=this.referenceDefinitionFromCompilerSymbol(y),a.set(y,h)),u&&(h?u.targetHits+=1:u.targetMisses+=1);let C=ut(c,y,()=>this.compilerSymbolKeys(y)),x=null,S=null,b=h&&r.has(h.symbolId)?i.get(h.symbolId):void 0;if(b&&(x=lu(m,g),!qh(b,n,x))){let v=m.getLineAndCharacterOfPosition(g.getStart(m));S={file:n,line:v.line,column:v.character};let R=l.get(b.symbolId)??[];R.push(S),l.set(b.symbolId,R),u&&(u.requestedHits+=1)}for(let v of C)for(let R of o.get(v)?.values()??[]){if(x??=lu(m,g),qh(R,n,x))continue;if(!S){let D=m.getLineAndCharacterOfPosition(g.getStart(m));S={file:n,line:D.line,column:D.character}}let E=l.get(R.symbolId)??[];E.push(S),l.set(R.symbolId,E),u&&(u.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(g,p)};p(m)}hierarchyTargetsForDefinitions(t){let n=new Map;for(let r of t){let i=this.nodeForDefinition(r),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(a,s,c))for(let u of this.compilerSymbolKeys(l)){let d=n.get(u)??new Map;d.set(r.symbolId,r),n.set(u,d)}}return n}hierarchyMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(!o.has(a)){o.add(a),i.add(c);for(let u of l){let d=u.getProperty(r.name);d&&s(u,d,this.hierarchyAncestorTypesForType(t,u))}}};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}addHierarchyMemberReferences(t,n,r){let i=new Map;for(let o of t){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(s.getSourceFile()),u=l.getSymbolAtLocation(a.name);if(!u)continue;let d=a.getSourceFile(),m=d.getLineAndCharacterOfPosition(a.name.getStart(d)),f={definition:o,location:{file:o.relativePath,line:m.line,column:m.character}},p=n.get(o.symbolId)??[];for(let y of this.hierarchyMemberSymbols(l,c,u))if(y!==u)for(let h of this.compilerSymbolLocations(y))p.push(h),r&&(r.hierarchyReferences+=1);n.set(o.symbolId,p);let g=this.hierarchyRootMemberSymbols(l,c,u);for(let y of g){let h=i.get(y)??new Map;h.set(o.symbolId,f),i.set(y,h)}r&&(r.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){r&&(r.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=n.get(s.symbolId)??[];for(let c of o.values())c.definition.symbolId!==s.symbolId&&(a.push(c.location),r&&(r.hierarchyReferences+=1));n.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(o.has(a))return;o.add(a);let u=!1;for(let d of l){let m=d.getProperty(r.name);m&&(u=!0,s(d,m,this.hierarchyAncestorTypesForType(t,d)))}if(!u)for(let d of this.compilerSymbolKeys(c))i.add(d)};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}compilerSymbolKeys(t){return(t.declarations??[]).map(n=>{let r=n.getSourceFile();return`${r.fileName}\0${n.getStart(r)}\0${t.name}`})}compilerSymbolLocations(t){let n=[];for(let r of t.declarations??[]){let i=r.getSourceFile(),o=Mr(this.db.config.projectRoot,i.fileName);if(!o)continue;let s=r.name,a=i.getLineAndCharacterOfPosition((s??r).getStart(i));n.push({file:o,line:a.line,column:a.character})}return n}baseTypes(t,n){try{return t.getBaseTypes(n)??[]}catch{return[]}}hierarchyAncestorTypes(t,n){let r=new Set(this.hierarchyAncestorTypesForType(t,t.getTypeAtLocation(n)));for(let i of n.heritageClauses??[])for(let o of i.types)r.add(t.getTypeAtLocation(o));return[...r]}hierarchyAncestorTypesForType(t,n){let r=new Set(this.baseTypes(t,n));for(let i of n.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let s of o.types)r.add(t.getTypeAtLocation(s));return[...r]}isHierarchyMethod(t){return this.tsMorph.ts.isMethodDeclaration(t)||this.tsMorph.ts.isMethodSignature(t)}isHierarchyContainer(t){return this.tsMorph.ts.isClassDeclaration(t)||this.tsMorph.ts.isClassExpression(t)||this.tsMorph.ts.isInterfaceDeclaration(t)}compilerReferenceSymbol(t,n,r){r&&(r.symbolLookups+=1);let i=t.getSymbolAtLocation(n);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return r&&(r.aliasResolutions+=1),t.getAliasedSymbol(i)}catch{return i}}}calleesFor(t){return ut(this.calleesCache,t.symbolId,()=>ut(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}calleesForDefinitions(t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i])}for(let[i,o]of r){let s=this.fileCalleesCache.get(i),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(i,a);for(let l of o){let u=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,u),n.set(l.symbolId,u)}}return n}referencesForDefinitionNode(t,n,r){let i=r?W.now():0,o=this.packageImportReferencesForDefinition(t);if(r&&(r.packageRefsMs+=W.now()-i,r.packageReferenceCount+=o.length),!n)return o;let s=r?W.now():0,a=Th(n,t,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=W.now()-s,r.referenceCount+=a.length),a}signatureFor(t){return ut(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let 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 Xh(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${Xh(o)}`})}importUsageForSourceFile(t,n,r){let i=[],o=new Map;for(let s of n.getImportDeclarations()){r.declarations+=1;let a=Je(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of du(s)){r.entries+=1;let u=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(u?r.bindingSymbols+=1:r.missingBindingSymbols+=1);let d={sourcePath:a,entry:l,typeOnlyDeclaration:c,bindingSymbol:u,references:[]};if(i.push(d),c||!l.localName||!u)continue;let m=o.get(l.localName);m?m.push(d):o.set(l.localName,[d])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||SL(s))return;r.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(r.symbolLookups+=1,!!c){for(let l of a)if(l.bindingSymbol===c){l.references.push({location:Gs(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?yL(t,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(r.fallbackEntries+=1,this.valueImportUsageForEntry(t,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(t,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let s of i)for(let a of _h(s,t,r.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(t,n,r,o)}valueImportUsageFromLocations(t,n,r,i){let o=i.some(c=>!Zl(c.node)),s=i.some(c=>Zl(c.node)),a=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:a,isUsed:a||i.length>0,isTypeUsed:a||s,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferencesForFiles(t){let n=new Map,r=new Set;for(let o of t){let s=this.sourceFiles.sourceFile(o);if(s)for(let a of s.getImportDeclarations()){let c=ou(this.workspacePackages,a.getModuleSpecifierValue());c&&r.add(c)}}if(r.size===0)return n;let i=this.packageExportsForNames(r);for(let o of t)this.addPackageImportReferencesForDocument(n,i,o);for(let[o,s]of n)n.set(o,Ar(s));return n}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,Ar(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=ou(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=Fh(a.identifier,r,this.db.config.projectRoot);l.length>0&&wL(t,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(t=>t.name))),this.packageExportIndex)}packageExportsForNames(t){let n=new Map;for(let r of this.workspacePackages){if(!t.has(r.name))continue;let i=new Map;for(let o of Oh(r))this.collectPackageExports(r,o,i,new Set);i.size>0&&n.set(r.name,i)}return n}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.relativeDir}/src/`))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 p=r.get(m);p||(p=new Set,r.set(m,p)),p.add(f.symbolId)}}}indexedDefinitionByLeaf(t,n){return ut(this.indexedDefinitionLeafCache,t,()=>Ah(this.db,t)).get(n)??null}nodeForDefinition(t){return ut(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return ut(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?Lh(this.tsMorph,this.db,n,t):new Map})}referenceDefinitionFromCompilerSymbol(t){return this.definitionFromCompilerSymbol(t,void 0,!0)}definitionFromCompilerSymbol(t,n,r=!1){let i=t.name,o=n?W.now():0,s=t.declarations??[];n&&(n.declarationsMs+=W.now()-o,n.declarationChecks+=s.length);for(let a of s){let c=n?W.now():0,l=a.getSourceFile(),u=Mr(this.db.config.projectRoot,l.fileName),d=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(n&&(n.declarationLocationMs+=W.now()-c),!u||this.db.isIgnored(u))continue;let m=n?W.now():0,f=this.compilerDeclarationName(a),p=r?nu(this.db,u,d,i)??(f&&f!==i?nu(this.db,u,d,f):null):Nh(this.db,u,d,i);if(n&&(n.indexedLookupMs+=W.now()-m),p)return{symbolId:p.symbolId,symbol:p.symbol,file:p.relativePath,line:p.startLine}}return null}compilerDeclarationName(t){let n=t.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(t,n){let r=U(),i=0,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=r?vL():void 0;return w("typescript.callee-map.file",()=>{let f=r?W.now():0,p=this.sourceFiles.sourceFile(t);if(r&&(c=Math.round(W.now()-f)),!p)return new Map;let g=r?W.now():0,y=Q(this.db,t).sort((E,D)=>E.startLine-D.startLine||D.endLine-E.endLine);if(r&&(l=Math.round(W.now()-g)),i=y.length,y.length===0)return new Map;let h=new Map,C=r?W.now():0,x=this.compilerCheckerForSourceFile(p),S=p.compilerNode;r&&(u=Math.round(W.now()-C));let b=new Map,v=E=>{if(this.tsMorph.ts.isCallExpression(E)||this.tsMorph.ts.isNewExpression(E)){r&&(o+=1);let D=this.semanticCalleeForCallNode(x,S,y,E,b,n,m);D&&(r&&(s+=1),CL(h,D.callerId,D.target))}this.tsMorph.ts.forEachChild(E,v)},R=r?W.now():0;v(S),r&&(d=Math.round(W.now()-R));for(let[E,D]of h)h.set(E,DL(D));return a=h.size,h},()=>({relativePath:t,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:u,traversalMs:d,...m?IL(m):{}}))}semanticCalleeForCallNode(t,n,r,i,o,s,a){let c=a?W.now():0,l=RL(r,lu(n,i));if(a&&(a.callerLookupMs+=W.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let u=i.expression,d=this.compilerSymbolForExpression(t,u,a),m=null;if(d)if(a&&(a.targetSymbolHits+=1),o.has(d))a&&(a.compilerSymbolCacheHits+=1),m=o.get(d)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let f=a?W.now():0;m=this.definitionFromCompilerSymbol(d,a),a&&(a.targetLookupMs+=W.now()-f),o.set(d,m)}else a&&(a.targetMisses+=1);return m?{callerId:l.symbolId,target:{symbol:m.symbol,file:m.file,line:m.line}}:null}compilerSymbolForExpression(t,n,r){let i=r?W.now():0,o=t.getSymbolAtLocation(n);if(r&&(r.expressionSymbolMs+=W.now()-i),o)return o;r&&(r.typeFallbacks+=1);let s=r?W.now():0,a=t.getTypeAtLocation(n).getSymbol();return r&&(r.typeSymbolMs+=W.now()-s),a}compilerCheckerForSourceFile(t){let n=t.getProject(),r=this.compilerCheckerCache.get(n);return r||(r=n.getTypeChecker().compilerObject,this.compilerCheckerCache.set(n,r)),r}};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 yL(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 bL(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function SL(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function CL(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function xL(e){let t=new Set;for(let n of e.getImportDeclarations())for(let r of du(n))r.localName&&t.add(r.localName);return t}function RL(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 lu(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function qh(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function Kh(e){return e.symbol.includes("#")?ue(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function vL(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function IL(e){return{...e,callerLookupMs:Math.round(e.callerLookupMs),expressionSymbolMs:Math.round(e.expressionSymbolMs),typeSymbolMs:Math.round(e.typeSymbolMs),targetLookupMs:Math.round(e.targetLookupMs),declarationsMs:Math.round(e.declarationsMs),declarationLocationMs:Math.round(e.declarationLocationMs),indexedLookupMs:Math.round(e.indexedLookupMs)}}function Jh(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function Yh(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function wL(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function DL(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 Xh(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}import{createHash as EL}from"crypto";import{readFileSync as kL}from"fs";import{dirname as PL,join as Js}from"path";var Ys=2,TL="typescript-semantic";function Zh(e){let t=Js(e,TL);return{rootDir:t,requestDir:Js(t,"requests"),responseDir:Js(t,"responses")}}function Xs(e){try{let t=JSON.parse(kL(Js(PL(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||typeof t.status!="string"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:EL("sha256").update(JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages})).digest("hex")}catch{return null}}var AL=12e4,ML=5;function oy(e,t,n={}){let r=new mu(e,n),i=null,o=null,s=process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1",a=()=>(i??=Qh(e,t),i),c=(d,m,f)=>{if(s)return f();try{return m(r.request(d))}catch{return s=!0,f()}},l=(d,m)=>c({kind:"references",definitions:[...d],...m?.exact?{exact:!0}:{}},f=>iy(f),()=>a().referencesForDefinitions?.(d,m)??new Map(d.map(f=>[f.symbolId,a().referencesFor(f)]))),u=d=>c({kind:"callees",definitions:[...d]},m=>iy(m),()=>a().calleesForDefinitions?.(d)??new Map(d.map(m=>[m.symbolId,a().calleesFor(m)])));return{language:"typescript",availability:()=>(o??=c({kind:"availability"},BL,()=>a().availability()),o),importUsage:d=>c({kind:"import-usage",file:d},m=>m,()=>a().importUsage(d)),referencesFor:d=>l([d]).get(d.symbolId)??[],referencesForDefinitions:l,referenceFragmentsForFiles:d=>c({kind:"reference-fragments",files:[...d]},m=>jL(m),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>u([d]).get(d.symbolId)??[],calleesForDefinitions:u,signatureFor:d=>c({kind:"signature",definition:d},$L,()=>a().signatureFor(d)),dispose:()=>i?.dispose?.()}}var mu=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??UL,this.timeoutMs=n.timeoutMs??HL(),this.cacheDir=NL(t.config.dbPath),this.projectRoot=Rt(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;request(t){let n=kh(this.cacheDir),r=Zh(this.cacheDir),i=Ql(n.statePath);if(!ry(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript semantic service is not running.");let o=Xs(this.db.config.dbPath);if(!o)throw new Error("Published TypeScript generation identity is unavailable.");let s=this.runtime.randomId(),a=ny(r.requestDir,`${s}.json`),c=ny(r.responseDir,`${s}.json`),l=this.runtime.now()+this.timeoutMs;ey(r.requestDir,{recursive:!0}),ey(r.responseDir,{recursive:!0}),_e(a,{protocolVersion:Ys,id:s,generation:o,deadlineAtMs:l,profileEnvironment:hf(),request:t});try{for(;this.runtime.now()<=l;){if(FL(c))return OL(LL(c,"utf8"),s,o);let u=Ql(n.statePath);if(!ry(u,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(ML)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}finally{ty(a,{force:!0}),ty(c,{force:!0})}}};function ry(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Eh,i=e?.typescriptSemantic?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptSemantic.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===Ys&&n.isProcessAlive(e.pid)&&(r||i)}function OL(e,t,n){let r=JSON.parse(e);if(r.protocolVersion!==Ys||r.id!==t||r.ok===!0&&r.generation!==n)throw new Error("TypeScript semantic service wrote an incompatible response.");if(r.ok===!0)return r.response;throw new Error(typeof r.error=="string"?r.error:"TypeScript semantic service request failed.")}function iy(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function jL(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function BL(e){if(!e||typeof e!="object"||typeof e.available!="boolean")throw new Error("TypeScript semantic service wrote invalid availability.");return e}function $L(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function HL(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:AL}var UL={now:Date.now,randomId:_L,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ct};var sy=new Ws;un({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>sy.clear(e)});function Or(e,t){let n=De(t)??"typescript";return sy.getOrCreate(e,n,()=>n==="rust"?vh(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>Cg(e,r)},calleeSymbolResolver:Sg(e),sourceZeroCalleeOracle:r=>WL(e,r),scipOccurrenceCalleeOracle:r=>Dh(e,r)}):oy(e,t))}function De(e){return e?M(e)==="rust"?"rust":kt(e)?"typescript":null:"typescript"}function WL(e,t){let n=G(e,t.relativePath);if(!n||n.language!=="rust")return!1;let r=n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine&&i.name===t.leaf)??n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return r?!n.callSites.some(i=>i.line>=r.startLine&&i.line<=r.endLine):!1}import{existsSync as GL,readFileSync as zL}from"fs";import{resolve as VL}from"path";var qL=/^[A-Za-z_][A-Za-z0-9_]*$/,ay=/\bDefault::default\b/g,KL=/^\.\.\s*Default::default\b/;function cy(e,t){let n=new Map,r=new Map;for(let i of t){let o=fu(e,i,r);o!==null&&n.set(i.symbolId,o)}return n}function fu(e,t,n=new Map){let r=YL(t.symbol);if(!r)return null;let i=_r(e,[t.symbolId]);if(i.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${$(r)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${$(r)}\\s*$`),a=JL(e,t.symbolId),c=[];for(let l of i){let u=XL(e,l.relative_path,n);if(u===null)return null;let d=u.split(/\r?\n/),m=0,f=[],p=0;for(let g=l.chunk_start;g<=l.chunk_end&&g<d.length;g+=1){let h=d[g]??"",C=new Set;o.lastIndex=0;let x;for(;x=o.exec(h);)c.push({file:l.relative_path,line:g,column:x.index+x[1].length+r.length+2}),p+=1;for(let S=0;S<h.length;S+=1){let b=KL.exec(h.slice(S));if(b){if(a&&f.includes(m)){let R=S+b[0].lastIndexOf("default");c.push({file:l.relative_path,line:g,column:R}),C.add(R),p+=1}S+=b[0].length-1;continue}let v=h[S];if(v==="{"){let R=s.test(h.slice(0,S));m+=1,R&&f.push(m);continue}if(v==="}")for(m=Math.max(0,m-1);f.length>0&&f[f.length-1]>m;)f.pop()}for(ay.lastIndex=0;x=ay.exec(h);){let S=x.index+9;if(!C.has(S))return null}}if(p===0)return null}return Ns(c)}function JL(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function YL(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!qL.test(t)?null:t}function XL(e,t,n){if(n.has(t))return n.get(t)??null;let r=e.get("SELECT text FROM documents WHERE relative_path = ?",t),i=typeof r?.text=="string"?r.text:QL(e,t);return n.set(t,i),i}function QL(e,t){let n=VL(e.config.projectRoot,t);if(!GL(n))return null;try{return zL(n,"utf8")}catch{return null}}import{readFileSync as nN}from"fs";import{dirname as rN,join as iN}from"path";function Zs(e){let t=Qs(e.projectFiles),n=new Set(t),r=new Map(e.snapshot.files.map(d=>[d.path,d])),i=e.snapshot.files.filter(d=>{let m=Nl(d.path,["typescript"]);return m==="config"||m==="ambient"}).map(d=>d.path),o=Qs([...t,...i]),s=o.find(d=>!r.has(d)),a=new Set(e.snapshot.files.map(d=>d.path)).size!==e.snapshot.files.length,c=!s&&o.some(d=>ly(r.get(d))),l=he(JSON.stringify({pnpmWorkspaces:e.snapshot.pnpmWorkspaces,typescriptProjectMode:e.snapshot.typescriptProjectMode,typescriptProjects:Qs(e.snapshot.typescriptProjects),membership:t})),u=new Map;return{identityFor(d,m){if(!n.has(d))return jr("target-outside-project");if(a)return jr("duplicate-input-path");if(s)return jr("missing-input-fingerprint");if(c)return jr("unreadable-input");let f=[],p,g;if(e.graph===null)f.push("dependency-graph-unavailable"),g="whole-project",p=o;else{let C=eN(d,e.graph,u);if(C.find(S=>!r.has(S)))return jr("missing-input-fingerprint");if(p=Qs([...C,...i]),p.some(S=>ly(r.get(S))))return jr("unreadable-input");g="dependency-closure"}let y=p.map(C=>tN(r.get(C)));return{version:1,key:he(JSON.stringify({version:1,engineIdentity:e.engineIdentity,schemaVersion:m,projectIdentity:l,inputs:y})),mode:g,inputFiles:p,reasons:f}}}}function ZL(e,t){let n=new Set,r=[e];for(let i=0;i<r.length;i+=1){let o=r[i];if(!(o===void 0||n.has(o))){n.add(o);for(let s of[...t.get(o)??[]].sort())n.has(s)||r.push(s)}}return[...n].sort()}function eN(e,t,n){let r=n.get(e);if(r)return r;let i=ZL(e,t);return n.set(e,i),i}function tN(e){return{path:e.path,size:e.size,hash:e.hash}}function ly(e){return e.size<0||e.hash==="unreadable"}function jr(e){return{version:1,key:null,mode:"unkeyed",inputFiles:[],reasons:[e]}}function Qs(e){return[...new Set(e)].sort()}var oN=J("typescript-semantic-identity-context",{clearGroups:["whole-project"]});function vn(e,t,n){let r=oN.get(e,()=>sN(e));if(!r)return null;let i=`${n}\0${t}`,o=r.identities.get(i);if(o)return o;let s=r.builder.identityFor(t,n);return r.identities.set(i,s),s}function Hi(e){return N(e,{includeIgnored:!1}).filter(kt).sort()}function sN(e){try{let t=JSON.parse(nN(iN(rN(e.config.dbPath),"meta.json"),"utf8")),n=Wg(t.fingerprint);return n?{builder:Zs({projectFiles:Hi(e),snapshot:n,graph:ie(e),engineIdentity:Vs()}),identities:new Map}:null}catch{return null}}var pu="typescript-reference-fragment-v2",ta=oe({kind:"typescript-reference-fragments",invalidation:K("typescript-reference-fragments"),serialize:e=>JSON.stringify(e),deserialize:cN});function c7(e,t,n,r=e){let i=Hi(e),o=Zs({projectFiles:i,snapshot:t,graph:ie(e),engineIdentity:Vs()}),s=[...n].map(([a,c])=>({relativePath:a,contentHash:o.identityFor(a,pu).key,value:[...c]}));if(s.some(a=>a.contentHash===null))throw new Error("TypeScript reference fragment identity is unavailable for an affected document.");return ta.writeBatch(r,s.map(a=>({...a,contentHash:a.contentHash}))),s.length}function gu(e,t,n){let r=t.filter(o=>kt(o.relativePath));if(r.length===0)return ea("no TypeScript definitions");let i=ea("shadow did not run");return w("typescript.reference-fragments.shadow",()=>{try{let o=Or(e,r[0].relativePath);if(!o.availability().available||!o.referenceFragmentsForFiles)return i=ea("TypeScript reference fragment provider is unavailable"),i;let s=Hi(e),a=new Set(s),c=o.referenceFragmentsForFiles(s),l=Ks(r,c),u=Gh(r,aN(n,a),l);if(!u.passed)return i={state:"failing",files:s.length,keyedFiles:0,writtenFiles:0,...u},i;let d=[];for(let m of s){let f=vn(e,m,pu);f?.key&&d.push({relativePath:m,contentHash:f.key,value:c.get(m)??[]})}return ta.writeBatch(e,d),i={state:"passing",files:s.length,keyedFiles:d.length,writtenFiles:d.length,...u},i}catch(o){return i=ea(o instanceof Error?o.message:String(o)),i}},()=>({...i}))}function aN(e,t){return new Map([...e].map(([n,r])=>[n,r.filter(i=>t.has(i.file))]))}function hu(e,t){if(t.length===0)return{references:new Map,files:0,cacheHits:0,cacheMisses:0,computedFiles:0};let n="fallback",r=0,i=0,o=0,s=0;return w("typescript.reference-fragments.materialize",()=>{try{let a=Hi(e);r=a.length;let c=new Map,l=new Map,u=[];for(let f of a){let p=vn(e,f,pu);if(!p?.key)return null;c.set(f,p.key);let g=ta.read(e,f,p.key);g===null?(o+=1,u.push(f)):(i+=1,l.set(f,g))}if(o===0)return n="hit",{references:Ks(t,l),files:r,cacheHits:i,cacheMisses:o,computedFiles:s};let d=Or(e,t[0].relativePath);if(!d.availability().available||!d.referenceFragmentsForFiles)return null;let m=d.referenceFragmentsForFiles(u);if(u.some(f=>!m.has(f)))return null;s=m.size,ta.writeBatch(e,u.map(f=>({relativePath:f,contentHash:c.get(f),value:m.get(f)??[]})));for(let[f,p]of m)l.set(f,p);return n="computed",{references:Ks(t,l),files:r,cacheHits:i,cacheMisses:o,computedFiles:s}}catch{return null}},()=>({state:n,files:r,cacheHits:i,cacheMisses:o,computedFiles:s}))}function ea(e){return{state:"unavailable",files:0,keyedFiles:0,writtenFiles:0,expectedCount:0,actualCount:0,missing:[],extra:[],reason:e}}function cN(e){try{let t=JSON.parse(e);return!Array.isArray(t)||!t.every(lN)?null:t}catch{return null}}function lN(e){if(!e||typeof e!="object")return!1;let t=e,n=t.location;return typeof t.targetSymbol=="string"&&!!n&&typeof n.file=="string"&&typeof n.line=="number"&&typeof n.column=="number"}var uN="typescript-import-usage-v1",dN="typescript-signatures-v1",yu=J("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),uy=On({kind:"semantic-import-usage",invalidation:K("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:xy}),dy=On({kind:"semantic-signatures",invalidation:K("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:CN}),my=oe({kind:"typescript-import-usage",invalidation:K("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:xy}),fy=oe({kind:"typescript-signatures",invalidation:K("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:xN});function We(e){let t=new Map,n=new Set;return{capability:(r,i)=>Ry(e,r,i),importUsage:r=>fN(e,r),references:r=>hy(e,r),materializeReferences:(r,i)=>by(e,r,t,n,i),callerMap:r=>pN(e,r,t,n),calleeMap:r=>yN(e,r),signature:r=>bN(e,r)}}function mN(e,t){if(t.size===0)return;let n=yu.get(e,()=>new Map);for(let[r,i]of t)n.set(r,[...i])}function gy(e,t){if(!yu.has(e))return{hits:[],misses:[...t]};let n=yu.get(e,()=>new Map),r=[],i=[];for(let o of t)n.has(o.symbolId)?r.push({definition:o,callees:n.get(o.symbolId)??[]}):i.push(o);return{hits:r,misses:i}}function Wi(e,t){return We(e).importUsage(t)}function fN(e,t){if(De(t)==="typescript"){let o="fallback",s=0,a=0,c=0,l=0;return w("typescript.import-usage.materialize",()=>{let u=vn(e,t,uN);if(u?.key){s=1;let m=my.read(e,t,u.key);if(m)return o="hit",a=1,m;c=1;let f=Pt(e,t);if(!f)return o="unavailable",[];let p=f.importUsage(t);return my.write(e,t,u.key,p),o="computed",p}l=1;let d=Pt(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:l}))}let n=Cy(e,"semantic-import-usage",t);if(n){let o=uy.read(e,t,n);if(o)return o}let r=Pt(e,t);if(!r)return[];let i=r.importUsage(t);return n&&uy.write(e,t,n,i),i}function na(e,t){return We(e).references(t)}function hy(e,t){let n=fu(e,t);if(n)return n;let r=Ng(e,t);if(r)return r;let i=Pt(e,t.relativePath);return i?i.referencesFor(t):[]}function In(e,t){return We(e).callerMap(t)}function yy(e,t){let n=new Map,r=new Map;for(let i of t){if(De(i.relativePath)==="typescript"){let o=Pt(e,i.relativePath);if(!o)continue;let s=r.get(o)??[];s.push(i),r.set(o,s);continue}bu(e,n,i,hy(e,i))}for(let[i,o]of r){let s=hu(e,o),a=s?.references??(i.referencesForDefinitions?i.referencesForDefinitions(o,{exact:!0}):new Map(o.map(c=>[c.symbolId,i.referencesFor(c)])));!s&&U()&&gu(e,o,a);for(let c of o)bu(e,n,c,a.get(c.symbolId)??[])}return n}function pN(e,t,n=new Map,r=new Set){let i=new Map,o=by(e,t,n,r),s=0;return w("semantic.callers.from-references",()=>{for(let a of t)s+=bu(e,i,a,n.get(a.symbolId)??[])},()=>({definitions:t.length,materialized:o.definitions,inMemoryHits:o.inMemoryHits,incompleteInMemoryHits:o.incompleteInMemoryHits,resultRows:i.size,callerFiles:s})),i}function by(e,t,n,r,i={}){let o=Te(e),s=[],a=[],c=[],l=0,u=0,d=0,m=0,f=0,p=0,g=0,y=0,h=0,C=0,x=0,S=0,b=[],v=new Map,R=t.filter(D=>De(D.relativePath)==="typescript"&&!n.has(D.symbolId)&&!r.has(D.symbolId)),E=hu(e,R);if(E){h=R.length,C=E.cacheHits,x=E.cacheMisses,S=E.computedFiles;for(let D of R)n.set(D.symbolId,E.references.get(D.symbolId)??[])}if(w("semantic.references.cache-scan",()=>{for(let[D,k]of Ts(t)){let L=[];for(let F of k)n.has(F.symbolId)?u+=1:r.has(F.symbolId)?y+=1:L.push(F);if(L.length===0){g+=1;continue}let ne=gN(e,o,D);if(!ne){for(let F of L)De(F.relativePath)||(l+=1),c.push(F);continue}p+=1;let X=Zm(e,D,ne);for(let F of L){let ae=X.get(F.symbol)??null;if(ae!==null){let Z=hN(ae);if(Z){d+=1,n.set(F.symbolId,Z);continue}m+=1}a.push({definition:F,cacheFingerprint:ne})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:l,cacheHits:d,parseFailures:m,misses:a.length,unkeyed:c.length,inMemoryHits:u,incompleteInMemoryHits:y,fullyInMemoryFiles:g,cacheReadFiles:p})),a.length>0||c.length>0){b=[...c,...a.map(D=>D.definition)],v=w("semantic.references.compute-misses",()=>{let D=Su(e,b,i);return f=D.size,D},()=>({definitions:b.length,misses:a.length,unkeyed:c.length,rows:f}));for(let D of b)v.has(D.symbolId)?(n.set(D.symbolId,v.get(D.symbolId)??[]),r.delete(D.symbolId)):r.add(D.symbolId);for(let{definition:D,cacheFingerprint:k}of a)v.has(D.symbolId)&&Ry(e,"semantic-references",D.relativePath).available&&s.push({relativePath:D.relativePath,symbol:D.symbol,projectFingerprint:k,payload:JSON.stringify(v.get(D.symbolId)??[])})}return s.length>0&&w("semantic.references.cache-write",()=>tf(e,s),()=>({entries:s.length})),v.size>0&&gu(e,b,v),{definitions:t.length,inMemoryHits:u,incompleteInMemoryHits:y,cacheHits:d,misses:a.length,unkeyed:c.length,skippedUnsupportedLanguage:l,parseFailures:m,computed:f,incomplete:r.size,cacheWrites:s.length,fragmentDefinitions:h,fragmentCacheHits:C,fragmentCacheMisses:x,fragmentComputedFiles:S}}function gN(e,t,n){if(!t)return null;let r=De(n);return r==="typescript"?t:r==="rust"?he(JSON.stringify({kind:"semantic-references",language:r,engine:qn(e.config.projectRoot),projectFingerprint:t})):null}function Su(e,t,n={}){let r=U(),i=new Map,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=0,f=0;return w("semantic.references.provider-loop",()=>{let p=cy(e,t),g=Lg(e,t),y=new Map,h=n.prefetchCallees?new Map:null,C=[];for(let S of t){let b,v=()=>(b??=Pt(e,S.relativePath),b);if(h){let k=v();if(k?.referencesAndCalleesForDefinitions){let L=h.get(k);L?L.push(S):h.set(k,[S]),f+=1}}let R=p.get(S.symbolId);if(R){a+=1,c+=R.length,Ui(i,S.symbolId,R,r,k=>{d+=1,m+=k});continue}let E=g.get(S.symbolId);if(E){l+=1,u+=E.length,Ui(i,S.symbolId,E,r,k=>{d+=1,m+=k});continue}let D=v();if(!D){r&&(s+=1);continue}if(r&&(o+=1),D.referencesForDefinitions){let k=y.get(D);k?k.push(S):y.set(D,[S])}else C.push({provider:D,definition:S})}let x=new Set;if(h)for(let[S,b]of h){if(!S.referencesAndCalleesForDefinitions)continue;let v=y.get(S)??[],R=S.referencesAndCalleesForDefinitions(v,b);x.add(S),mN(e,R.callees);for(let E of v){if(!R.references.has(E.symbolId))continue;let D=R.references.get(E.symbolId)??[];Ui(i,E.symbolId,D,r,k=>{d+=1,m+=k})}}for(let[S,b]of y){if(x.has(S))continue;let v=S.referencesForDefinitions(b);for(let R of b){if(!v.has(R.symbolId))continue;let E=v.get(R.symbolId)??[];Ui(i,R.symbolId,E,r,D=>{d+=1,m+=D})}}for(let{provider:S,definition:b}of C){let v=S.referencesFor(b);Ui(i,b.symbolId,v,r,R=>{d+=1,m+=R})}return i},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:c,rustScipOccurrenceFastPathRows:l,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:f,definitionsWithReferences:d,referenceCount:m,rows:i.size}))}function Ui(e,t,n,r,i){e.set(t,n),r&&n.length>0&&i(n.length)}function bu(e,t,n,r){let i=0;for(let o of r){if(o.file===n.relativePath||e.isIgnored(o.file))continue;let s=t.get(n.symbolId);s||(s=new Set,t.set(n.symbolId,s));let a=s.size;s.add(o.file),s.size!==a&&(i+=1)}return i}function hN(e){try{return JSON.parse(e)}catch{return null}}function ra(e,t){return We(e).calleeMap(t)}function yN(e,t){let n=U(),r=new Map,i=0,o=0,s=0,a=0;return w("semantic.callees.provider-loop",()=>{let c=new Map,l=[];for(let u of t){let d=Pt(e,u.relativePath);if(!d){n&&(o+=1);continue}n&&(i+=1);let m=u;if(d.calleesForDefinitions){let f=c.get(d);f?f.push(m):c.set(d,[m])}else l.push({provider:d,definition:m})}for(let[u,d]of c){let m=u.calleesForDefinitions(d);for(let f of d){let p=m.get(f.symbolId)??[];py(r,f.symbolId,p,n,g=>{s+=1,a+=g})}}for(let{provider:u,definition:d}of l){let m=u.calleesFor(d);py(r,d.symbolId,m,n,f=>{s+=1,a+=f})}return r},()=>({definitions:t.length,providerHits:i,providerMisses:o,definitionsWithCallees:s,calleeCount:a,rows:r.size}))}function py(e,t,n,r,i){n.length>0&&(e.set(t,n),r&&i(n.length))}function Sy(e,t){return We(e).signature(t)}function bN(e,t){if(De(t.relativePath)==="typescript"){let s="fallback",a=0,c=0,l=0,u=0;return w("typescript.signature.materialize",()=>{let d=vn(e,t.relativePath,dN);if(d?.key){a=1;let f=fy.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(f,t.symbol))return s="hit",c=1,f[t.symbol]??null;l=1;let p=Pt(e,t.relativePath);if(!p)return s="unavailable",null;let g=p.signatureFor(t);return fy.write(e,t.relativePath,d.key,{...f,[t.symbol]:g}),s="computed",g}u=1;let m=Pt(e,t.relativePath);return m?(s="direct-fallback",m.signatureFor(t)):(s="unavailable",null)},()=>({state:s,eligible:a,cacheHits:c,cacheMisses:l,fallbacks:u}))}let n=Cy(e,"semantic-signatures",t.relativePath),r=SN(t);if(n){let s=dy.read(e,r,n);if(s)return s.signature}let i=Pt(e,t.relativePath);if(!i)return null;let o=i.signatureFor(t);return n&&dy.write(e,r,n,{signature:o}),o}function Cy(e,t,n){let r=Te(e);if(!r)return null;let i=De(n);return i!=="rust"?null:he(JSON.stringify({kind:t,language:i,engine:qn(e.config.projectRoot),projectFingerprint:r}))}function SN(e){return`${e.relativePath}\0${e.symbol}`}function xy(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function CN(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t.signature;return n!==null&&typeof n!="string"?null:{signature:n}}catch{return null}}function xN(e){try{let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return null;for(let n of Object.values(t))if(n!==null&&typeof n!="string")return null;return t}catch{return null}}function Ry(e,t,n){let r=De(n);if(!r)return{slot:t,language:"typescript",available:!1,reason:"semantic evidence is only available for TypeScript or Rust files"};try{return{slot:t,language:r,...Or(e,n).availability()}}catch(i){return{slot:t,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function Pt(e,t){if(!De(t))return null;let n=Or(e,t);return n.availability().available?n:null}var H={references:na,referenceMap:Su,callerMap:(e,t)=>We(e).callerMap(t),calleeMap:Cu};function Cu(e,t){let n=U(),r=new Map,i=gy(e,t),o=[],s=[],a=0,c=0,l=0,u=0,d=0,m=0,f=0;for(let{definition:x,callees:S}of i.hits)d+=1,S.length>0&&(m+=1,f+=S.length,r.set(x.symbolId,S));let p=RN(e,i.hits);if(p.entries.length>0&&w("semantic.callees.prefetch-cache-write",()=>Dc(e,p.entries),()=>({entries:p.entries.length,sourceMissing:p.sourceMissing,skippedUnsupportedLanguage:p.skippedUnsupportedLanguage})),w("semantic.callees.cache-scan",()=>{for(let[x,S]of Ts(i.misses)){if(!De(x)){n&&(a+=S.length);continue}let b=P(e,x);if(!b){n&&(c+=S.length),s.push(...S);continue}let v=ce(e,x,b),R=vy(e,x);if(!R){s.push(...S);continue}let E=Qm(e,x,v,R);for(let D of S){let k=E.get(D.symbol)??null;if(k!==null){let L=IN(k);if(L){n&&(l+=1),L.length>0&&r.set(D.symbolId,L);continue}n&&(u+=1)}o.push({def:D,contentHash:v,depsDigest:R})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:a,sourceMissing:c,cacheHits:l,parseFailures:u,misses:o.length,unkeyed:s.length,inMemoryHits:d,inMemoryRows:m,inMemoryCalleeCount:f,resultRows:r.size})),o.length===0&&s.length===0)return r;let g=[...s,...o.map(x=>x.def)],y=0,h=w("semantic.callees.compute-misses",()=>{let x=ra(e,g);return y=x.size,x},()=>({definitions:g.length,misses:o.length,unkeyed:s.length,rows:y}));for(let[x,S]of h)r.set(x,S);let C=o.filter(x=>We(e).capability("semantic-callees",x.def.relativePath).available).map(x=>({relativePath:x.def.relativePath,symbol:x.def.symbol,contentHash:x.contentHash,depsDigest:x.depsDigest,payload:JSON.stringify(h.get(x.def.symbolId)??[])}));return C.length>0?w("semantic.callees.cache-write",()=>Dc(e,C),()=>({entries:C.length})):w("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:o.length})),r}function RN(e,t){let n=[],r=new Map,i=0,o=0;for(let{definition:s,callees:a}of t){if(!De(s.relativePath)){o+=1;continue}if(!r.has(s.relativePath)){let l=P(e,s.relativePath),u=l?vy(e,s.relativePath):null;r.set(s.relativePath,l&&u?{contentHash:ce(e,s.relativePath,l),depsDigest:u}:null)}let c=r.get(s.relativePath);if(!c){i+=1;continue}n.push({relativePath:s.relativePath,symbol:s.symbol,contentHash:c.contentHash,depsDigest:c.depsDigest,payload:JSON.stringify(a)})}return{entries:n,sourceMissing:i,skippedUnsupportedLanguage:o}}var vN="typescript-callees-v1";function vy(e,t){let n=De(t);if(n==="typescript")return vn(e,t,vN)?.key??null;let r=DN(e,t);return n==="rust"?he(JSON.stringify({kind:"semantic-callees",language:n,engine:qn(e.config.projectRoot),positionMapping:"nearby-leaf-v1",depsDigest:r})):r}function IN(e){try{return JSON.parse(e)}catch{return null}}var wN=j("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function DN(e,t){return wN.get(e,t,()=>{let r=[...ie(e).get(t)??[]].sort().map(i=>`${i}:${ce(e,i,P(e,i))}`);return he(r.join("|"))})}function B7(e,t,n={}){let r=B(e,t);if(!r)return[];let o=!ee(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=Dt(e,r,{semantic:n.semantic,semanticEvidence:H}).map(u=>({relativePath:u.file,line:u.line})),a=EN(e,r),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 EN(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=kN(t.symbol);if(n.length===0)return[];let r=[];for(let i of N(e,{extensions:[".rb"],includeIgnored:!1})){let o=P(e,i);if(!o)continue;let s=o.split(`
|
|
287
|
-
`);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&r.push({relativePath:i,line:a})}}return r}function
|
|
283
|
+
${r}`,...i)}function zT(e,t,n,r,i){if(r===i||e.isIgnored(r)||e.isIgnored(i)||!n.has(i))return;let o=t.get(r);o||(o=new Set,t.set(r,o)),o.add(i)}function Ts(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function Sg(e){let t=new Map,n=qT(e),r=new Map;return i=>{let o=VT(i),s=r.get(o);if(s!==void 0)return s;if(!n.has(i.file))return r.set(o,i.symbol),i.symbol;let a=t.get(i.file);a||(a=KT(Q(e,i.file)),t.set(i.file,a));let c=JT(a,i);return r.set(o,c),c}}function VT(e){return`${e.file}\0${e.symbol}\0${e.line}`}function qT(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function KT(e){let t=new Map,n=new Map;for(let r of e){let i=t.get(r.leaf);i?i.push(r):t.set(r.leaf,[r]);let o=n.get(r.startLine);o?o.push(r):n.set(r.startLine,[r])}return{definitions:e,byLeaf:t,byStartLine:n}}function JT(e,t){if(e.definitions.length===0)return t.symbol;let n=QT(t.symbol),r=YT(e.byLeaf,n),i=XT(r,t.line);if(i)return i.symbol;let o=e.byStartLine.get(t.line)??[];return o.length===1?o[0].symbol:t.symbol}function YT(e,t){let n=[],r=new Set;for(let i of t)for(let o of e.get(i)??[])r.has(o.symbolId)||(r.add(o.symbolId),n.push(o));return n}function XT(e,t){let n=null;for(let r of e)if(!(r.startLine>t||r.endLine<t)){if(r.startLine===t)return r;(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r)}return n}function QT(e){let t=new Set([e]),r=e.split(/::|\.|#/).filter(Boolean).at(-1);return r&&t.add(r),t}function Cg(e,t){let r=re(e,t).map(i=>e_(t,i));return{usage:r,positions:t_(e,t,r)}}function xg(e,t){return{importUsage(n){let r=e.importUsageFacts(n);if(!t||r.positions.length===0)return r.usage;let i=t.importDefinitionsForFile(n,r.positions);return i.available?ZT(r.usage,i.sourcePaths):r.usage}}}function ZT(e,t){return e.map((n,r)=>{let i=t.get(String(r));return i?{...n,sourcePath:i}:n})}function e_(e,t){let n=t.isTypeOnly===!0,r=t.kind==="side-effect"||n||t.used;return{importer:e,sourcePath:t.sourcePath,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:n,isUsed:r,isTypeUsed:n,isValueUsed:t.kind==="side-effect"||!n&&t.used,references:[]}}function t_(e,t,n){let r=q(e,t);if(!r)return[];let i=n_(r.rootNode),o=new Map;for(let a of i){let c=o.get(Dl(a.importedName,a.localName));c?c.push(a.position):o.set(Dl(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let l=o.get(Dl(a.importedName,a.localName??a.importedName))?.shift();l&&s.push({...l,id:String(c),file:t})}),s}function n_(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let r=n.namedChildren.find(i=>i.type!=="visibility_modifier");r&&t.push(..._s(r,""))}return t.filter(n=>n.importedName!=="*")}function _s(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:wl(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:wl(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=kr(t,n.text);return r.namedChildren.flatMap(o=>_s(o,i))}case"use_list":return e.namedChildren.flatMap(n=>_s(n,t));case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);return!n||!r?[]:_s(n,t).map(i=>({...i,localName:r.text}))}case"use_wildcard":{let n=e.namedChild(0),r="*";return[{importedName:r,localName:r,position:wl(n??e,r)}]}default:return[]}}function wl(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+r_(t)}}function r_(e){return Math.max(0,Math.min(e.length-1,1))}function Dl(e,t){return`${e}\0${t}`}import{spawnSync as Gl}from"child_process";import{existsSync as zl}from"fs";import{fileURLToPath as DF}from"url";function Rn(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}import{execFileSync as Dg}from"child_process";import{existsSync as kl,readFileSync as l_}from"fs";import{createRequire as u_}from"module";import{platform as Eg}from"os";import{dirname as wg,join as Fs}from"path";import{execFileSync as Rg,spawnSync as i_}from"child_process";import{platform as o_}from"os";var vg=o_()==="win32";function kZ(e,t=i_){try{return t(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}function El(e){let t=vg?"where":"which";try{return Rg(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var s_=/\.(?:c|m)?js$/i,a_=/\.(?:exe|com)$/i;function PZ(e,t){return s_.test(e)?{binary:process.execPath,args:[e,...t]}:{binary:e,args:[...t]}}function c_(e,t){return Rg(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8"})}function Ig(e,t={}){let n=t.isWindows??vg,r=t.lookup??c_,i;try{i=r(n?"where":"which",[e])}catch{return null}let o=i.split(/\r?\n/).map(s=>s.trim()).filter(Boolean);return n?o.find(s=>a_.test(s))??null:o[0]??null}var d_=u_(import.meta.url),kg={language:"rust",indexerBinary:"rust-analyzer",installUrl:"https://github.com/rust-lang/rust-analyzer"};function Pl(e){return[e.indexerBinary,...e.binaryAliases??[]]}function m_(e){let t=Pl(e);return t.length===1?t[0]:t.join(" or ")}function Tl(e){for(let t of Pl(e))if(Eg()==="win32"){let n=Ig(t);if(n)return n}else if(El(t))return t;return p_(e)}function OZ(e){return Tl(e)!==null||f_(e)}function f_(e){return Pg(e)!==null}function p_(e){let t=Pg(e);if(!t)return null;let r=JSON.parse(l_(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return Fs(wg(t),r);for(let i of Pl(e)){let o=r[i];if(o)return Fs(wg(t),o)}return null}function Pg(e){if(!e.bundledNpmPackage)return null;try{return d_.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function g_(e,t){for(let n of e.projectLocalBinaries??[]){let r=Fs(t,n);if(kl(r))return r}return null}function h_(e,t){return g_(e,t)??Tl(e)}function jZ(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||_l(n,t))return t;let r=_g(n,t);return r?{...t,DOTNET_ROOT:r}:t}function Tg(e,t){let n=m_(e),r=t?h_(e,t):Tl(e);if(!r)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:r};let i=y_(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function y_(e){if(_l(e,process.env))return{runnable:!0};let t=_g(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=Fg(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 _g(e,t){for(let n of Fg(t))if(_l(e,{...t,DOTNET_ROOT:n}))return n;return null}function Fg(e){let t=[],n=e.DOTNET_ROOT;if(n&&kl(n)&&t.push(n),Eg()==="darwin"&&El("brew"))try{let r=Dg("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=Fs(r,"libexec");kl(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function _l(e,t){try{return Dg(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}function Ls(e){let t=Tg(kg,e),n=t.runnable;return{available:n,dependencyAvailable:n,resolvedBinary:t.resolvedBinary??void 0,reason:n?"rust-analyzer semantic reference queries are enabled.":"rust-analyzer is not runnable; Rust semantic checks will use SCIP/source evidence only."}}import{existsSync as dF,mkdtempSync as lh,readFileSync as uh,rmSync as jl}from"fs";import{tmpdir as Hl}from"os";import{join as Bl}from"path";import{fileURLToPath as Ni,pathToFileURL as mF}from"url";import{SHARE_ENV as fF,Worker as pF}from"worker_threads";function dt(e){try{return process.kill(e,0),!0}catch(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="EPERM"}}function vn(e,t,n=new Set){let r=new Map;for(let i of e)n.has(i.symbolId)||r.set(i.symbolId,t.get(i.symbolId)??[]);return r}function qn(e,t,n){let r=Rn(process.env.SCIP_RUST_SEMANTIC_BATCH_TIMEOUT_MS)??0;if(r>0)return r;let i=Math.max(1,Math.ceil(e/Math.max(1,n)));return Math.max(12e4,3e4+i*t)}import{spawn as Q_}from"child_process";import{createHash as Z_,randomUUID as eF}from"crypto";import{existsSync as nh,mkdirSync as Xg,readFileSync as js,realpathSync as tF,rmSync as Ml}from"fs";import{tmpdir as nF}from"os";import{resolve as kt}from"path";import{mkdirSync as b_,renameSync as S_,writeFileSync as C_}from"fs";import{dirname as x_}from"path";function _e(e,t,n={}){b_(x_(e),{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`,i=JSON.stringify(t,null,n.spacing);C_(r,n.trailingNewline?`${i}
|
|
284
|
+
`:i),S_(r,e)}import{execFileSync as T_}from"child_process";import{existsSync as R_,readFileSync as v_}from"fs";import{deserializeSCIP as I_,SymbolRole as w_}from"@c4312/scip";import{existsSync as JZ,readFileSync as YZ}from"fs";import{relative as QZ,resolve as ZZ,sep as e3}from"path";import{fileURLToPath as n3,pathToFileURL as r3}from"url";function Ns(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}\0${n.column}`,n);return[...t.values()].sort((n,r)=>{let i=n.file.localeCompare(r.file);return i!==0?i:n.line!==r.line?n.line-r.line:n.column-r.column})}var Fl=new WeakMap,D_="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function Lg(e,t){let n=new Map,r=As(),i=t.filter(s=>Mg(s,r));if(i.length===0)return n;let o=Og(e);if(!o)return n;for(let s of i){let a=Ag(o,s);a!==null&&n.set(s.symbolId,a)}return n}function Ng(e,t){if(!Mg(t,As()))return null;let n=Og(e);return n?Ag(n,t):null}function Ag(e,t){return e.referencesBySymbol.get(t.symbol)??[]}function Mg(e,t="safe"){if(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||Ie(e.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(e.symbol))return!1;if(t==="all")return!0;let n=ue(e.symbol);if(n==="method")return!0;if(n!=="term")return!1;let r=ye(e.symbol);return"kind"in r?!1:!E_(r)}function E_(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function Og(e){if(Fl.has(e))return Fl.get(e)??null;let t=k_(e);return Fl.set(e,t),t}function k_(e){if(!R_(e.config.indexPath))return null;try{let t=I_(v_(e.config.indexPath)),n=new Map;for(let r of t.documents??[]){let i=r.relativePath;if(!(!i||e.isIgnored(i)))for(let o of r.occurrences??[]){if(!o.symbol||(o.symbolRoles&w_.Definition)!==0)continue;let s=P_(i,o.range);if(!s)continue;let a=n.get(o.symbol)??[];a.push(s),n.set(o.symbol,a)}}for(let[r,i]of n)n.set(r,Ns(i));return{referencesBySymbol:n}}catch{return null}}function P_(e,t){if(t.length<3)return null;let n=t[0],r=t[1];return!Number.isInteger(n)||!Number.isInteger(r)?null:{file:e,line:n,column:r}}function As(){return process.env[D_]==="all"?"all":"safe"}var jg=new Map;function Ll(e){let n=Ls(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?__(e,n):"unavailable"}}function Kn(e){return{...Ll(e),scipOccurrenceReferenceMode:As()}}function __(e,t){let n=`${e}\0${t}`,r=jg.get(n);if(r)return r;let i;try{i=T_(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()}catch{i="unknown"}return jg.set(n,i),i}import{createHash as J_}from"crypto";import{execFileSync as A_}from"child_process";import{createHash as Vg}from"crypto";import{lstatSync as M_,readdirSync as O_,readFileSync as j_,readlinkSync as B_,realpathSync as qg}from"fs";import{isAbsolute as $_,join as Kg,relative as H_,sep as U_}from"path";function Nl(e,t){let n=e.split("/").at(-1)??e;if(Gg.has(n)||n===".scipquery.json"||/^tsconfig(?:\..+)?\.json$/.test(n))return"config";if(/\.d\.(?:ts|mts|cts)$/.test(e.toLowerCase()))return"ambient";let r=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return t.some(i=>(zg[i]??[]).includes(r))?"source":"other"}function Ug(e,t,n){let r=e.split("/").at(-1)??e;if(n?.includes(e)||n?.includes(r)||Gg.has(r))return!0;let i=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return(zg[t]??[]).includes(i)}function Wg(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.version!="number"||!Bg(t.languages)||typeof t.pnpmWorkspaces!="boolean"||typeof t.typescriptProjectMode!="string"||!Bg(t.typescriptProjects)||t.clojureConfigPath!==void 0&&typeof t.clojureConfigPath!="string"||!Array.isArray(t.files)||!t.files.every(F_)?null:t}function p3(e,t){let n=new Map((e?.files??[]).map(a=>[a.path,a])),r=new Map(t.files.map(a=>[a.path,a])),i=new Set([...n.keys(),...r.keys()]),o=[];for(let a of[...i].sort()){let c=n.get(a),l=r.get(a),u=Nl(a,t.languages);!c&&l?o.push({kind:"added",path:a,inputKind:u,after:l}):c&&!l?o.push({kind:"deleted",path:a,inputKind:u,before:c}):c&&l&&(c.hash!==l.hash||c.size!==l.size)&&o.push({kind:"modified",path:a,inputKind:u,before:c,after:l})}let s=new Set;return e||s.add("prior-snapshot-unavailable"),e&&e.version!==t.version&&s.add("snapshot-version-changed"),($g(e?.files??[])||$g(t.files))&&s.add("duplicate-input-path"),[...e?.files??[],...t.files].some(L_)&&s.add("unreadable-input"),{version:1,changes:o,projectIdentityChanged:e?!N_(e,t):!0,uncertainty:[...s].sort()}}function Bg(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function $g(e){return new Set(e.map(t=>t.path)).size!==e.length}function F_(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.path=="string"&&typeof t.size=="number"&&typeof t.hash=="string"}function L_(e){return e.hash==="unreadable"||e.size<0}function N_(e,t){return Hg(e.languages,t.languages)&&e.pnpmWorkspaces===t.pnpmWorkspaces&&e.typescriptProjectMode===t.typescriptProjectMode&&Hg(e.typescriptProjects,t.typescriptProjects)&&e.clojureConfigPath===t.clojureConfigPath}function Hg(e,t){if(e.length!==t.length)return!1;let n=[...e].sort(),r=[...t].sort();return n.every((i,o)=>i===r[o])}var Gg=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","deps.edn","project.clj","bb.edn","shadow-cljs.edn"]),zg={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"],clojure:[".clj",".cljs",".cljc"]};function W_(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function G_(e){return(V_(e)??q_(e)).filter(t=>t&&!Jg(t)).sort()}function Al(e,t={}){let n=G_(e).filter(i=>!t.language||Ug(i,t.language,t.markerFiles)).filter(i=>!t.includePath||t.includePath(i)),r=qg(e);return n.map(i=>{let o=Kg(e,i);try{if(M_(o).isSymbolicLink()){let a=qg(o),c=H_(r,a);if(c===".."||c.startsWith(`..${U_}`)||$_(c))throw new Error("external symlink");let l=B_(o);return{path:i,size:Buffer.byteLength(l),hash:Vg("sha256").update("symlink\0").update(l).digest("hex")}}let s=j_(o);return{path:i,size:s.byteLength,hash:Vg("sha256").update(s).digest("hex")}}catch{return{path:i,size:-1,hash:"unreadable"}}})}function Pi(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:n.typescriptProjectMode!=="workspace"&&n.pnpmWorkspaces===!0,typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:W_(n.typescriptProjects),clojureConfigPath:z_(n.clojureConfigPath),files:Al(e)}}function z_(e){return e?.trim()||void 0}function V_(e){try{return A_("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
|
|
285
|
+
`).filter(Boolean)}catch{return null}}function q_(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?Kg(e,r):e,o;try{o=O_(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){Jg(a)||n.push(a);continue}t.push(a)}}return t}function Jg(e){let t=e.split("/");return e==="meta.json"||t.some(n=>K_.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var K_=new Set([".git","node_modules",".scipquery-cache",".scipquery-generations",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]);var Y_=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function Yg(e){let t=Al(e,{includePath:X_});return J_("sha256").update(JSON.stringify(t)).digest("hex")}function X_(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||Y_.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}var rh=2,rF=5e3,iF=5e3,ih=10,oF=3e4;function Qg(e,t,n,r=ch){let i=r.engineIdentity(e),o={protocolVersion:rh,projectRoot:r.canonicalProjectRoot(e),projectFingerprint:r.projectFingerprint(e),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(t),environment:oh(r.environment())};return{key:Os(Ms(o)),...o}}function Ti(e,t,n){return e.protocolVersion===rh&&(t-e.heartbeatAtMs<=rF||e.busyUntilMs!==void 0&&t<=e.busyUntilMs)&&n(e.pid)}function Ol(e,t,n){let r;try{r=Os(js(t))}catch{r="missing"}let i=Os(Ms({projectRoot:kt(e),serverPath:kt(t),serverFingerprint:r})).slice(0,20);return kt(n,`scip-query-rust-session-${i}`)}function Zg(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function oh(e){return Object.fromEntries(Object.entries(e).filter(([t])=>ah(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function sh(e,t){let n=t.runtime??uF,r=t.identityRuntime??ch,i=Ol(e,t.serverPath,t.tempRoot??nF()),o=!1,s=(a,c)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return aF(i,t.serverPath,t.semanticWorkerPath,a,c,n)};return{requestSemantic(a,c){let l=Qg(e,t.semanticWorkerPath,a,r),u=n.now()+Math.max(1,c-1e3);return s({kind:"semantic",identityKey:l.key,workerEnvironment:th(),request:{...a,readinessDeadlineMs:u,referenceRetryTimeoutMs:sF(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:Zg(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let l=Qg(e,t.semanticWorkerPath,a,r),u=n.now()+Math.max(1,c-1e3);return s({kind:"import-definitions",identityKey:l.key,workerEnvironment:th(),request:{...a,readinessDeadlineMs:u,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:Zg(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){o=!0}}}function sF(e,t){return t!==void 0?t:e===void 0?oF:void 0}function aF(e,t,n,r,i,o){let s=o.randomId(),a=o.now(),c=kt(e,"requests"),l=kt(e,"responses"),u=kt(c,`${s}.json`),d=kt(l,`${s}.json`);Xg(c,{recursive:!0}),Xg(l,{recursive:!0}),_e(u,{id:s,request:r});let m=o.now()+i;try{for(eh(e,t,n,m,o);o.now()<=m;){if(nh(d)){let p=cF(js(d,"utf8"));if(!p.ok)throw new Error(p.error);return U()&&fn({type:"span",name:"rust.semantic.durable-session.request",durationMs:o.now()-a,ok:!0,session:p.session,kind:r.kind}),p.response}let f=_i(e);(!f||!Ti(f,o.now(),o.isProcessAlive))&&eh(e,t,n,m,o),o.sleep(ih)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}finally{Ml(u,{force:!0}),Ml(d,{force:!0})}}function eh(e,t,n,r,i){let o=_i(e);if(o&&Ti(o,i.now(),i.isProcessAlive))return;Ml(kt(e,"server.json"),{force:!0}),i.spawnServer(t,e,n);let s=Math.min(r,i.now()+iF);for(;i.now()<=s;){let a=_i(e);if(a&&Ti(a,i.now(),i.isProcessAlive))return;i.sleep(ih)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function _i(e){try{let t=JSON.parse(js(kt(e,"server.json"),"utf8"));return typeof t.protocolVersion!="number"||typeof t.pid!="number"||typeof t.heartbeatAtMs!="number"||t.busyUntilMs!==void 0&&typeof t.busyUntilMs!="number"?null:{protocolVersion:t.protocolVersion,pid:t.pid,heartbeatAtMs:t.heartbeatAtMs,...t.busyUntilMs===void 0?{}:{busyUntilMs:t.busyUntilMs}}}catch{return null}}function cF(e){try{let t=JSON.parse(e);return t.ok===!0&&(t.session==="created"||t.session==="reused"||t.session==="invalidated")&&t.response&&typeof t.response=="object"?{ok:!0,session:t.session,response:t.response}:{ok:!1,error:typeof t.error=="string"?t.error:"helper wrote an invalid response"}}catch(t){return{ok:!1,error:`helper wrote malformed JSON: ${t instanceof Error?t.message:String(t)}`}}}function th(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>lF(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function ah(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function lF(e){return ah(e)||e.startsWith("SCIP_RUST_")||e==="SCIP_QUERY_PROFILE"||e==="SCIP_QUERY_PROFILE_CACHE_STATE"||e==="SCIP_QUERY_PROFILE_COMMAND"||e==="SCIP_QUERY_PROFILE_OUT"||e==="SCIP_QUERY_PROFILE_RUN_ID"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND"||e==="SCIP_QUERY_PROFILE_MIN_MS"}var ch={canonicalProjectRoot(e){try{return tF(e)}catch{return kt(e)}},projectFingerprint(e){return Yg(e)},engineIdentity:Ll,fileFingerprint(e){return Os(js(e))},environment(){return oh(process.env)}},uF={now:Date.now,randomId:eF,isProcessAlive:dt,spawnServer(e,t,n){if(!nh(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);Q_(process.execPath,[e,t,n],{detached:!0,stdio:"ignore"}).unref()},sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)}};function Ms(e){return Array.isArray(e)?`[${e.map(Ms).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Ms(n)}`).join(",")}}`:JSON.stringify(e)}function Os(e){return Z_("sha256").update(e).digest("hex")}var dh=15e3,mh=8,ph=5e3,gF=64,hF=96,Ul=class{constructor(t,n,r={}){this.projectRoot=t;this.status=n;this.opts=r;this.requester=r.requester??SF(t,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION)}projectRoot;status;opts;requester;referencesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:n.reason,references:Fi(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,references:vn(t,new Map(r.references),new Set(r.incompleteReferenceSymbolIds??[]))}}catch(r){return this.opts.fallbackReferenceResolver?.referencesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),references:Fi(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:n.reason,callees:Li(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,callees:$l(t,new Map(r.callees??[]))}}catch(r){return this.opts.fallbackCalleeResolver?.calleesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),callees:Li(t)}}}referencesAndCalleesForDefinitions(t,n){let r=this.status(this.projectRoot);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,references:Fi(t),callees:Li(n)};let i=[...t,...n];try{let o=this.requestSession(r.resolvedBinary,i,{includeReferences:t.length>0,includeCallees:n.length>0,referenceDefinitions:t,calleeDefinitions:n});return{available:o.available,resolvedBinary:r.resolvedBinary,reason:o.reason,references:vn(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:$l(n,new Map(o.callees??[]))}}catch(o){return this.fallbackReferencesAndCallees(r,t,n,o)}}signaturesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:n.reason,signatures:fh(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,signatures:IF(t,new Map(r.signatures??[]))}}catch(r){return this.opts.fallbackSignatureResolver?.signaturesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),signatures:fh(t)}}}importDefinitionsForFile(t,n){let r=this.status(this.projectRoot);if(n.length===0)return{available:r.available,resolvedBinary:r.resolvedBinary,reason:r.reason,sourcePaths:new Map};if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,sourcePaths:new Map(n.map(i=>[i.id,null]))};try{let i=this.requestImportDefinitions(r.resolvedBinary,t,n);return{available:i.available,resolvedBinary:r.resolvedBinary,reason:i.reason,sourcePaths:new Map(i.sourcePaths)}}catch(i){return{available:!1,resolvedBinary:r.resolvedBinary,reason:i instanceof Error?i.message:String(i),sourcePaths:new Map(n.map(o=>[o.id,null]))}}}dispose(){this.requester.shutdown()}requestSession(t,n,r){let i=Bs(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,dh),o=$s(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=Bs(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,mh),a=$s(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),c=r.referenceDefinitions?[...r.referenceDefinitions]:void 0,l=r.calleeDefinitions?[...r.calleeDefinitions]:void 0,u=r.signatureDefinitions?[...r.signatureDefinitions]:void 0,d=Ai(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,...r}),m={projectRoot:this.projectRoot,rustAnalyzerBinary:t,definitions:[...n],...c?{referenceDefinitions:c}:{},...l?{calleeDefinitions:l}:{},...u?{signatureDefinitions:u}:{},requestTimeoutMs:i,...r.includeReferences!==!1&&o>0?{referenceRetryTimeoutMs:o}:{},diagnosticsTimeoutMs:a,settleDelayMs:d,concurrency:s,includeReferences:r.includeReferences,includeCallees:r.includeCallees,includeSignatures:r.includeSignatures},f=wF(m);return w("rust.semantic.session.request",()=>this.requester.requestSemantic(m,qn(f,Wl(i,m.referenceRetryTimeoutMs),s)),()=>({definitions:n.length,operationDefinitions:f,referenceDefinitions:m.referenceDefinitions?.length,calleeDefinitions:m.calleeDefinitions?.length,signatureDefinitions:m.signatureDefinitions?.length,references:m.includeReferences!==!1,callees:m.includeCallees===!0,signatures:m.includeSignatures===!0,referenceRetryTimeoutMs:m.referenceRetryTimeoutMs}))}fallbackReferencesAndCallees(t,n,r,i){let o=n.length===0?{available:!0,references:Fi(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=r.length===0?{available:!0,callees:Li(r)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(r);return o&&s?{available:o.available&&s.available,resolvedBinary:o.resolvedBinary??s.resolvedBinary??t.resolvedBinary,reason:o.reason??s.reason,references:vn(n,o.references),callees:$l(r,s.callees)}:{available:!1,resolvedBinary:t.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:Fi(n),callees:Li(r)}}requestImportDefinitions(t,n,r){let i=Bs(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,dh),o=Bs(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,mh),s=$s(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=$s(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,ph),c={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...r],requestTimeoutMs:i,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return w("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(c,qn(r.length,i,o)),()=>({file:n,positions:r.length}))}};function gh(e,t,n={}){return new Ul(e,t,n)}function Ai(e,t){let n=Sh(e);if(n!==null)return n;let r=t.includeReferences!==!1;return r&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=gF||r&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=hF?0:ph}function hh(e){let t=e?.trim().toLowerCase(),n=t==="0"||t==="false"||t==="off"||t==="worker",r=t==="1"||t==="true"||t==="on"||t==="durable",i=t===void 0||t==="";return{transport:n||!i&&!r?"worker":"durable",source:i?"default":"environment",fallback:"worker",valid:i||n||r,optOut:"SCIP_RUST_SEMANTIC_DURABLE_SESSION=0"}}function yF(e){return hh(e).transport}function V3(e,t){let n=hh(t);if(n.transport==="worker")return{...n,state:"per-command"};let r=Ni(bh()),i=Ol(e,r,Hl()),o=_i(i);return o?{...n,state:Ti(o,Date.now(),dt)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function bF(e,t){let n=null,r=!1,i=!1,o=!1,s=()=>n??=t(),a=()=>{i||(e.shutdown(),i=!0)},c=(u,d,m)=>{let f=vF(u);r=!0;try{a()}catch{}U()&&fn({type:"span",name:"rust.semantic.durable-session.request",durationMs:m,ok:!1,kind:d,session:"worker-fallback",reason:f})},l=(u,d,m)=>{if(o)throw new Error("Rust semantic failover session was already disposed.");if(r)return m(s());let f=Date.now();try{return d(e)}catch(p){c(p,u,Date.now()-f)}return m(s())};return{requestSemantic(u,d){return l("semantic",m=>m.requestSemantic(u,d),m=>m.requestSemantic(u,d))},requestImportDefinitions(u,d){return l("import-definitions",m=>m.requestImportDefinitions(u,d),m=>m.requestImportDefinitions(u,d))},shutdown(){if(o)return;o=!0;let u=[];try{a()}catch(d){u.push(d)}try{n?.shutdown()}catch(d){u.push(d)}if(u.length>0)throw u[0]}}}function SF(e,t,n={worker:()=>CF(),durable:()=>sh(e,{serverPath:Ni(bh()),semanticWorkerPath:Ni(yh())})}){return yF(t)==="durable"?bF(n.durable(),n.worker):n.worker()}function CF(e={}){let t=null,n=null,r=1,i=!1,o=()=>{n&&(jl(n,{recursive:!0,force:!0}),n=null)},s=()=>{let l=t;t=null,l&&l.terminate(),o()},a=()=>{if(t)return t;let l=e.semanticWorkerPath?mF(e.semanticWorkerPath):yh();if(!dF(Ni(l)))throw new Error(`Rust semantic session worker was not found at ${Ni(l)}. Run npm run build before using built semantic Rust queries.`);return n=lh(Bl(Hl(),"scip-query-rust-session-")),t=new pF(l,e.shareEnvironment?{env:fF}:void 0),t.unref(),t},c=()=>{let l=n??lh(Bl(Hl(),"scip-query-rust-session-"));return n=l,Bl(l,`${r++}.json`)};return{requestSemantic(l,u){if(i)throw new Error("Rust semantic session was already disposed.");let d=a(),m=c(),f=new SharedArrayBuffer(4),p=new Int32Array(f);if(d.postMessage({kind:"semantic",request:l,responsePath:m,sharedBuffer:f}),Atomics.wait(p,0,0,u)==="timed-out")throw s(),new Error(`Rust semantic session worker timed out after ${(u/1e3).toFixed(0)}s`);try{let y=xF(uh(m,"utf8"));if(!y.ok)throw new Error(y.error);return y.response}finally{jl(m,{force:!0})}},requestImportDefinitions(l,u){if(i)throw new Error("Rust semantic session was already disposed.");let d=a(),m=c(),f=new SharedArrayBuffer(4),p=new Int32Array(f);if(d.postMessage({kind:"import-definitions",request:l,responsePath:m,sharedBuffer:f}),Atomics.wait(p,0,0,u)==="timed-out")throw s(),new Error(`Rust semantic import-definition session worker timed out after ${(u/1e3).toFixed(0)}s`);try{let y=RF(uh(m,"utf8"));if(!y.ok)throw new Error(y.error);return y.response}finally{jl(m,{force:!0})}},shutdown(){if(i)return;if(i=!0,!t){o();return}let l=c(),u=new SharedArrayBuffer(4),d=new Int32Array(u);t.postMessage({kind:"shutdown",responsePath:l,sharedBuffer:u}),Atomics.wait(d,0,0,5e3),s()}}}function xF(e){let t=JSON.parse(e);if(!t||typeof t!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=t;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof t.error=="string"?t.error:"Rust semantic session worker failed."}}function RF(e){let t=JSON.parse(e);if(!t||typeof t!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=t;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof t.error=="string"?t.error:"Rust semantic session worker failed."}}function vF(e){let t=e instanceof Error?`${e.name} ${e.message}`.toLowerCase():String(e).toLowerCase();return t.includes("readiness")?"readiness":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("helper")?"helper":"request"}function Fi(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Li(e){return new Map(e.map(t=>[t.symbolId,[]]))}function fh(e){return new Map(e.map(t=>[t.symbolId,null]))}function $l(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function IF(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function wF(e){let t=0;return e.includeReferences!==!1&&(t+=(e.referenceDefinitions??e.definitions).length),e.includeCallees===!0&&(t+=(e.calleeDefinitions??e.definitions).length),e.includeSignatures===!0&&(t+=(e.signatureDefinitions??e.definitions).length),Math.max(1,t)}function Wl(e,t){return t&&t>0?Math.max(e,t):e}function yh(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function bh(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function Bs(e,t){return Rn(e)??t}function $s(e,t){return Sh(e)??t}function Sh(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var Vl=15e3,ql=8;function vh(e,t={}){let n=t.status??Ls,r=PF(e,n),i=TF(e,n),o=_F(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!EF(t)?null:gh(e,n,{fallbackReferenceResolver:r,fallbackCalleeResolver:i,fallbackSignatureResolver:o}),a=t.referenceResolver??s??r,c=t.calleeResolver??s??i,l=t.signatureResolver??s??o,u=t.importUsageResolver??xg(t.sourceImportUsageResolver??kF(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,m=t.sourceZeroCalleeOracle,f=t.scipOccurrenceCalleeOracle,p=new Map,g=new Map,y=null,h=null,C=()=>(y??=n(e),y),x=()=>{let E=C();return E.dependencyAvailable?h??E:E},S=E=>{if(E.length===0)return new Map;let D=Mi(E);try{let k=a.referencesForDefinitions(D),L=C();return h={...L,available:k.available,resolvedBinary:k.resolvedBinary??L.resolvedBinary,reason:k.reason??L.reason},k.available?new Map(k.references):vn(D,k.references)}catch(k){return h={...C(),available:!1,reason:k instanceof Error?k.message:String(k)},Jn(D)}},b=E=>{if(E.length===0)return new Map;let D=Mi(E),k=D.filter(Ch);if(k.length===0)return Yn(D);let L=new Map,ne=Rh(k,f),X=[];for(let F of k)g.has(F.symbolId)?L.set(F.symbolId,g.get(F.symbolId)??[]):ne.has(F.symbolId)?L.set(F.symbolId,ne.get(F.symbolId)??[]):xh(F,m)?L.set(F.symbolId,[]):X.push(F);if(X.length===0)return Lr(D,L,void 0);try{let F=c.calleesForDefinitions(X),ae=C();h={...ae,available:F.available,resolvedBinary:F.resolvedBinary??ae.resolvedBinary,reason:F.reason??ae.reason};let Z=Lr(X,F.callees,d);for(let[un,bc]of Z)L.set(un,bc);return Lr(D,L,void 0)}catch(F){return h={...C(),available:!1,reason:F instanceof Error?F.message:String(F)},Yn(D)}},v=(E,D)=>{let k=Mi(E),L=Mi(D),ne=L.filter(Ch),X=new Map,F=Rh(ne,f),ae=[];for(let Z of ne)F.has(Z.symbolId)?X.set(Z.symbolId,F.get(Z.symbolId)??[]):xh(Z,m)?X.set(Z.symbolId,[]):ae.push(Z);if(k.length===0&&ae.length===0)return{references:Jn(k),callees:Lr(L,X,void 0)};try{let Z=s?s.referencesAndCalleesForDefinitions(k,ae):AF(a,c,{referenceDefinitions:k,calleeDefinitions:ae}),un=C();h={...un,available:Z.available,resolvedBinary:Z.resolvedBinary??un.resolvedBinary,reason:Z.reason??un.reason};let bc=Z.available?new Map(Z.references):vn(k,Z.references);for(let[Sc,Cc]of Z.callees)X.set(Sc,Cc);let Wm=Lr(L,X,d);for(let[Sc,Cc]of Wm)g.set(Sc,Cc);return{references:bc,callees:Wm}}catch(Z){return h={...C(),available:!1,reason:Z instanceof Error?Z.message:String(Z)},{references:Jn(k),callees:Yn(L)}}},R=E=>{if(E.length===0)return new Map;let D=Mi(E);try{let k=l.signaturesForDefinitions(D),L=C();return h={...L,available:k.available,resolvedBinary:k.resolvedBinary??L.resolvedBinary,reason:k.reason??L.reason},Ih(D,k.signatures)}catch(k){return h={...C(),available:!1,reason:k instanceof Error?k.message:String(k)},Hs(D)}};return{language:"rust",availability:x,dispose:()=>{s?.dispose()},importUsage:E=>{let D=p.get(E);if(D)return D;try{let k=u.importUsage(E);return p.set(E,k),k}catch(k){return h={...C(),available:!1,reason:k instanceof Error?k.message:String(k)},[]}},referencesFor:E=>S([E]).get(E.symbolId)??[],referencesForDefinitions:S,referencesAndCalleesForDefinitions:v,calleesFor:E=>b([E]).get(E.symbolId)??[],calleesForDefinitions:b,signatureFor:E=>R([E]).get(E.symbolId)??null}}function EF(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function kF(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function Mi(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:T(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:ee(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function Ch(e){return e.isFunctionLike}function xh(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function Rh(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function PF(e,t){return{referencesForDefinitions:n=>FF(e,t,n)}}function TF(e,t){return{calleesForDefinitions:n=>LF(e,t,n)}}function _F(e,t){return{signaturesForDefinitions:n=>NF(e,t,n)}}function FF(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,references:Jn(n)};let i=Kl();if(!zl(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,references:Jn(n)};let o=Nr(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Vl),s=Us(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=Nr(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ql),c=Us(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=Ai(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!0}),u={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,...s>0?{referenceRetryTimeoutMs:s}:{},diagnosticsTimeoutMs:c,settleDelayMs:l,concurrency:a},d=Gl(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:qn(n.length,Wl(o,u.referenceRetryTimeoutMs),a)}),m=Jl(d.stdout);if(m)return{available:m.available,resolvedBinary:r.resolvedBinary,reason:m.reason,references:vn(n,new Map(m.references),new Set(m.incompleteReferenceSymbolIds??[]))};let f=d.error instanceof Error?d.error.message:d.stderr.trim()||`Rust semantic worker exited with status ${d.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:f,references:Jn(n)}}function LF(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,callees:Yn(n)};let i=Kl();if(!zl(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,callees:Yn(n)};let o=Nr(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Vl),s=Nr(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ql),a=Us(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=Ai(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!0},u=Gl(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:qn(n.length,o,s)}),d=Jl(u.stdout);if(d)return{available:d.available,resolvedBinary:r.resolvedBinary,reason:d.reason,callees:Lr(n,new Map(d.callees??[]),void 0)};let m=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,callees:Yn(n)}}function NF(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,signatures:Hs(n)};let i=Kl();if(!zl(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,signatures:Hs(n)};let o=Nr(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Vl),s=Nr(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ql),a=Us(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=Ai(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!1,includeSignatures:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!1,includeSignatures:!0},u=Gl(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:qn(n.length,o,s)}),d=Jl(u.stdout);if(d)return{available:d.available,resolvedBinary:r.resolvedBinary,reason:d.reason,signatures:Ih(n,new Map(d.signatures??[]))};let m=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,signatures:Hs(n)}}function AF(e,t,n){let r=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:Jn(n.referenceDefinitions)},i=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:Yn(n.calleeDefinitions)};return{available:r.available&&i.available,resolvedBinary:r.resolvedBinary??i.resolvedBinary,reason:r.reason??i.reason,references:r.references,callees:i.callees}}function Jn(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Yn(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Hs(e){return new Map(e.map(t=>[t.symbolId,null]))}function Lr(e,t,n){let r=0,i=0;return w("rust.semantic.callees.complete-map",()=>{let o=new Map;for(let s of e){let a=t.get(s.symbolId)??[];a.length>0&&(r+=1),i+=a.length,o.set(s.symbolId,a.map(c=>({...c,symbol:n?n(c):c.symbol})))}return o},()=>({definitions:e.length,rows:r,callees:i,resolveSymbols:!!n}))}function Ih(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function Kl(){return DF(new URL("./rust-semantic-worker.js",import.meta.url))}function Jl(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return typeof n.available!="boolean"||!Array.isArray(n.references)?null:{available:n.available,reason:typeof n.reason=="string"?n.reason:void 0,references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(r=>typeof r=="number"):void 0,callees:Array.isArray(n.callees)?n.callees:void 0,signatures:Array.isArray(n.signatures)?n.signatures:void 0}}catch{return null}}function Nr(e,t){return Rn(e)??t}function Us(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as MF,readFileSync as OF}from"fs";import{deserializeSCIP as jF,SymbolRole as BF}from"@c4312/scip";var Yl=new WeakMap;function Dh(e,t){let n=t.filter($F);if(n.length===0)return new Map;let r=!1,i=0,o=0;return w("rust.scip-occurrence.callees",()=>{let s=WF(e);if(r=!!s,!s)return new Map;let a=new Map;for(let c of n){let l=HF(e,s,c);l!==null&&(a.set(c.symbolId,l),i+=1,o+=l.length)}return a},()=>({definitions:t.length,candidates:n.length,indexAvailable:r,resolvedDefinitions:i,resolvedCallees:o}))}function $F(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||Ie(e.symbol))}function HF(e,t,n){let r=G(e,n.relativePath);if(!r||r.language!=="rust")return null;let i=r.callables.find(l=>l.startLine!==n.startLine||l.endLine!==n.endLine?!1:l.name===n.leaf||n.leaf.endsWith(l.name)||l.name.endsWith(n.leaf));if(!i)return null;let o=r.callSites.filter(l=>l.line>=i.startLine&&l.line<=i.endLine);if(o.length===0)return null;let s=(t.occurrencesByFile.get(n.relativePath)??[]).filter(l=>l.line>=i.startLine&&l.line<=i.endLine&&l.callee.symbol!==n.symbol);if(s.some(l=>l.traitImplMember)||!UF(o,s))return null;let a=[],c=new Set;for(let l of s){let u=`${l.callee.symbol}\0${l.callee.file}\0${l.callee.line}`;c.has(u)||(c.add(u),a.push(l.callee))}return a}function UF(e,t){let n=wh(e),r=wh(t);if(n.size!==r.size)return!1;for(let[i,o]of n)if(r.get(i)!==o)return!1;return!0}function wh(e){let t=new Map;for(let n of e){let r=n.calleeLeaf??n.leaf;if(!r)continue;let i=`${n.line}\0${r}`;t.set(i,(t.get(i)??0)+1)}return t}function WF(e){if(Yl.has(e))return Yl.get(e)??null;let t=GF(e);return Yl.set(e,t),t}function GF(e){if(!MF(e.config.indexPath))return null;try{let t=xe(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),r=jF(OF(e.config.indexPath)),i=new Map;for(let o of r.documents??[]){let s=o.relativePath;if(!s||!s.endsWith(".rs")||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&BF.Definition)!==0)continue;let l=n.get(c.symbol);if(!l)continue;let u=c.range?.[0];Number.isInteger(u)&&a.push({line:u,leaf:l.leaf,traitImplMember:Ie(l.symbol),callee:{symbol:l.symbol,file:l.relativePath,line:l.startLine}})}i.set(s,a)}return{occurrencesByFile:i}}catch{return null}}var Ws=class{sessions=new WeakMap;getOrCreate(t,n,r){let i=zF(t,n),o=this.sessions.get(t);o||(o=new Map,this.sessions.set(t,o));let s=o.get(i);if(s)return s.hits+=1,s.lastUsedAtMs=Date.now(),s.provider;let a=Date.now(),c=r();return o.set(i,{key:i,language:n,projectRoot:t.config.projectRoot,provider:c,createdAtMs:a,lastUsedAtMs:a,hits:1}),c}sessionsFor(t){return[...this.sessions.get(t)?.values()??[]]}clear(t){let n=this.sessions.get(t);if(n)for(let r of n.values())r.provider.dispose?.();this.sessions.delete(t)}};function zF(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as FL}from"crypto";import{existsSync as LL,mkdirSync as ey,readFileSync as NL,rmSync as ty}from"fs";import{dirname as AL,resolve as ny}from"path";import{readFileSync as VF}from"fs";import{join as Xl}from"path";var g6=4,Eh=5e3,qF="watch.lock",KF="watch-state.json",JF="watch-activity.json";function kh(e){return{lockPath:Xl(e,qF),statePath:Xl(e,KF),activityPath:Xl(e,JF)}}function Ql(e){try{return YF(JSON.parse(VF(e,"utf8")))}catch{return null}}function YF(e){if(!e||typeof e!="object")return null;let t=e;return t.version!==1||typeof t.protocolVersion!="number"||typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0||typeof t.projectRoot!="string"||t.worktreeId!==void 0&&(typeof t.worktreeId!="string"||t.worktreeId.length===0)||typeof t.cliVersion!="string"||!Ze(t.startedAt)||!Ze(t.heartbeatAt)||!Ze(t.lastActivityAt)||!XF(t.watcher)||t.idleDeadlineAt!==void 0&&!Ze(t.idleDeadlineAt)||t.indexGeneration!==void 0&&!/^[a-f0-9]{64}$/.test(t.indexGeneration)||t.lastError!==void 0&&!QF(t.lastError)||t.lastRefresh!==void 0&&!ZF(t.lastRefresh)||t.reindexActivity!==void 0&&!eL(t.reindexActivity)||t.typescriptSemantic!==void 0&&!tL(t.typescriptSemantic)||t.typescriptIndex!==void 0&&!nL(t.typescriptIndex)?null:t}function Ze(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function XF(e){if(!e||typeof e!="object"||!("state"in e))return!1;let t=e;switch(t.state){case"idle":return!0;case"waiting":return Qe(t.changedFiles)&&Qe(t.reindexAt);case"indexing":return Qe(t.startedAt);case"cooldown":return Qe(t.until)&&typeof t.dirty=="boolean";default:return!1}}function QF(e){if(!e||typeof e!="object")return!1;let t=e;return Ze(t.at)&&typeof t.message=="string"}function ZF(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.trigger?.kind=="string"&&typeof t.result=="string"&&Ze(t.startedAt)&&Ze(t.completedAt)&&Qe(t.durationMs)}function eL(e){if(!e||typeof e!="object")return!1;let t=e;return!Ze(t.windowStartedAt)||!Ze(t.windowEndedAt)||!Xe(t.runs)||!Xe(t.rebuilt)||!Xe(t.reused)||!Xe(t.failed)||!Xe(t.suppressed)||!Qe(t.estimatedLogicalOutputBytes)||t.estimatedLogicalOutputBytes<0||!t.byTrigger||typeof t.byTrigger!="object"?!1:Object.values(t.byTrigger).every(n=>n===void 0||Xe(n))}function tL(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.protocolVersion=="number"&&(t.state==="idle"||t.state==="ready"||t.state==="unavailable"||t.state==="error")&&Qe(t.requests)&&Qe(t.sessionsCreated)&&Qe(t.sessionsReused)&&Qe(t.sessionsRefreshed)&&Qe(t.sessionsReplaced)&&Qe(t.projectsCreated)&&(t.lastRequestAt===void 0||Ze(t.lastRequestAt))&&(t.lastError===void 0||typeof t.lastError=="string")&&(t.busyUntil===void 0||Ze(t.busyUntil))}function nL(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.protocolVersion=="number"&&(t.state==="idle"||t.state==="ready"||t.state==="unavailable"||t.state==="error")&&Xe(t.requests)&&Xe(t.sessionsCreated)&&Xe(t.sessionsReplaced)&&Xe(t.initializations)&&Xe(t.programUpdates)&&Xe(t.documentsEmitted)&&Xe(t.documentsRemoved)&&(t.lastRequestAt===void 0||Ze(t.lastRequestAt))&&(t.lastDurationMs===void 0||Qe(t.lastDurationMs)&&t.lastDurationMs>=0)&&(t.lastError===void 0||typeof t.lastError=="string")&&(t.busyUntil===void 0||Ze(t.busyUntil))}function Qe(e){return typeof e=="number"&&Number.isFinite(e)}function Xe(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}import{performance as W}from"perf_hooks";function mt(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import Ph from"path";function rL(e,t){return e.getReferences().map(n=>{let r=n.getNode();return Gs(r,t)})}function iL(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function Th(e,t,n,r){let i=[];for(let o of iL(e))for(let s of rL(o,r))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||i.push(s);for(let o of n)i.push(o);return Ar(i)}function _h(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();Mr(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:Gs(a,r),node:a}))}return i}function Gs(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:Mr(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function Fh(e,t,n){let r=e.getSourceFile(),i=eu(r,e),o=e.getText(),s=new RegExp(`\\b${$(o)}\\b`,"g"),a=r.getFullText().split(`
|
|
286
|
+
`),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 Ar(c.filter(l=>Mr(n,Ph.join(n,l.file))===t))}function Zl(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 eu(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Ar(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 Mr(e,t){let n=Ph.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function Lh(e,t,n,r){let i=oL(t,r);return i.size===0?new Map:sL(e,n,i)}function oL(e,t){let n=new Map;for(let r of Q(e,t)){let i=T(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function sL(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of aL(e,o)){let a=n.get(s);if(!a)continue;let c=eu(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 aL(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 cL=j("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function Nh(e,t,n,r){let i=ru(e,t),o=tu(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||T(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return tu(s,n)}function nu(e,t,n,r){return tu(ru(e,t).get(r)??[],n)}function Ah(e,t){let n=new Map;for(let[r,i]of ru(e,t)){let o=i[0];o&&n.set(r,o)}return n}function ru(e,t){return cL.get(e,t,()=>{let n=new Map;for(let r of Q(e,t)){let i=r.leaf||T(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 tu(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 iu from"path";var Oi=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function Pt(e){let t=e.toLowerCase();return Oi.some(n=>t.endsWith(n))}function Mh(e,t){let n=new Map,r=null,i=null,o=()=>(i??=N(e,{extensions:Oi}),i),s=()=>(r??=w("typescript.source-file-index",()=>lL(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),r),a=c=>Pt(c)?mt(n,c,()=>{let l=ji(iu.resolve(e.config.projectRoot,c));for(let{project:u,sourceFiles:d}of s()){let m=d.get(l)??null;if(m||(m=u.addSourceFileAtPathIfExists(l)??null,m&&d.set(ji(m.getFilePath()),m)),m)return{project:u,sourceFile:m}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function lL(e,t,n){let r=t.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[ji(o.getFilePath()),o]))}));for(let i of n){let o=ji(iu.resolve(e,i));for(let s of r){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){s.sourceFiles.set(ji(a.getFilePath()),a);break}}}return r}function ji(e){return iu.resolve(e)}function ou(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Oh(e){let t=`${e.relativeDir}/src`;return[`${t}/index.ts`,`${t}/index.tsx`,`${t}/index.mts`,`${t}/index.cts`]}import{existsSync as Bi,readFileSync as uL}from"fs";import Fe from"path";var su=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function au(e,t){let r=t?Fe.dirname(Fe.join(e,t)):e,i=Fe.resolve(e);for(;r.startsWith(i);){for(let s of su){let a=Fe.join(r,s);if(Bi(a))return a}let o=Fe.dirname(r);if(o===r)break;r=o}for(let o of su){let s=Fe.join(e,o);if(Bi(s))return s}return null}function jh(e){let t=e.config.projectRoot,n=new Set(dL(t,e.config.semantic?.typescript?.tsconfigs)),r=N(e,{includeIgnored:!1,extensions:Oi});for(let i of r){let o=au(t,i);o&&n.add(Fe.resolve(o))}if(n.size===0){let i=au(t);i&&n.add(Fe.resolve(i))}return[...n].filter(i=>!Bh(t,i)).sort((i,o)=>i.localeCompare(o))}function dL(e,t=[]){let n=new Set;for(let r of t){let i=Fe.isAbsolute(r)?r:Fe.join(e,r);Bi(i)&&n.add(Fe.resolve(i))}for(let r of mL(e))for(let i of su){let o=Fe.join(r,i);Bi(o)&&n.add(Fe.resolve(o))}if(n.size===0){let r=au(e);r&&n.add(Fe.resolve(r))}return[...n].filter(r=>!Bh(e,r)).sort((r,i)=>r.localeCompare(i))}function mL(e){let t=Fe.join(e,"package.json");if(!Bi(t))return[];let n;try{n=JSON.parse(uL(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>Xc(e,i))}function Bh(e,t){let n=Fe.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 fL}from"module";var $h=fL(import.meta.url),$i,zs;function cu(){if($i!==void 0)return $i;try{$i=$h("ts-morph")}catch{$i=null}return $i}function Vs(){if(zs)return zs;let e=cu();if(!e)return"ts-morph:unavailable";let t="unknown";try{t=$h("ts-morph/package.json").version??"unknown"}catch{}return zs=`ts-morph:${t}:typescript:${e.ts.version}`,zs}function Hh(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!0})}))}function qs(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function Ks(e,t){let n=new Map(e.map(i=>[i.symbol,i])),r=new Map(e.map(i=>[i.symbolId,[]]));for(let i of t.values())for(let o of i){let s=n.get(o.targetSymbol);s&&r.get(s.symbolId).push(o.location)}for(let[i,o]of r)r.set(i,pL(o));return r}function Gh(e,t,n){let r=Wh(e,t),i=Wh(e,n),o=[...r].filter(d=>!i.has(d)).sort(),s=[...i].filter(d=>!r.has(d)).sort(),a=Uh(e,t),c=Uh(e,n),l=[...a].filter(d=>!c.has(d)).sort(),u=[...c].filter(d=>!a.has(d)).sort();return{passed:o.length===0&&s.length===0,expectedCount:r.size,actualCount:i.size,missing:o,extra:s,callerFiles:{passed:l.length===0&&u.length===0,expectedCount:a.size,actualCount:c.size,missing:l,extra:u}}}function Uh(e,t){let n=new Set;for(let r of e)for(let i of t.get(r.symbolId)??[])i.file!==r.relativePath&&n.add(`${r.symbol}\0${i.file}`);return n}function zh(e,t,n){let r=new Set(n),i=new Map(n.map(o=>[o,[]]));for(let o of e)for(let s of t.get(o.symbolId)??[])r.has(s.file)&&i.get(s.file).push({targetSymbol:o.symbol,location:s});for(let[o,s]of i)i.set(o,gL(s));return i}function Wh(e,t){let n=new Set;for(let r of e)for(let i of t.get(r.symbolId)??[])n.add(`${r.symbol}\0${i.file}\0${i.line}\0${i.column}`);return n}function pL(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}\0${n.column}`,n);return[...t.values()].sort(Vh)}function gL(e){let t=new Map;for(let n of e){let{location:r}=n;t.set(`${n.targetSymbol}\0${r.file}\0${r.line}\0${r.column}`,n)}return[...t.values()].sort((n,r)=>n.targetSymbol.localeCompare(r.targetSymbol)||Vh(n.location,r.location))}function Vh(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.column-t.column}var hL=32;function Qh(e,t){let n=w("typescript.provider.load",()=>cu());if(!n)return qs("ts-morph is not installed");let r=w("typescript.provider.tsconfig-discovery",()=>jh(e));if(r.length===0)return qs("no tsconfig found");try{let i=w("typescript.provider.project-bundles",()=>Hh(n,r),()=>({tsconfigs:r.length}));return yL(e,n,i)}catch(i){return qs(i instanceof Error?i.message:String(i),r[0],r)}}function yL(e,t,n,r={}){return w("typescript.provider.construct",()=>new uu(e,t,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var uu=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Rr(t.config.projectRoot),this.sourceFiles=Mh(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;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return mt(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=SL();return w("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,r),()=>({file:t,...r}))})}referencesFor(t){return mt(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){let r=new Map,i=U(),o=[];for(let u of t){let d=this.referencesCache.get(u.symbolId);d?r.set(u.symbolId,d):o.push(u)}if(o.length===0)return r;let s=o,a=n.exact?[]:o.filter(u=>!Kh(u));if(a.length>=hL){let u=this.referencesForDefinitionsBySymbolScan(a);for(let d of a){let m=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}if(s=o.filter(d=>Kh(d)),s.length===0)return r}let c=new Map;for(let u of s){let d=c.get(u.relativePath);d?d.push(u):c.set(u.relativePath,[u])}let l=[];for(let[u,d]of c){let m=Jh();w("typescript.references-map.file",()=>{let f=this.definitionNodesForFile(u);for(let p of d){i&&(m.cacheMisses+=1);let g=f.get(p.symbolId)??null;i&&(g?m.nodeHits+=1:m.nodeMisses+=1);try{let y=this.referencesForDefinitionNode(p,g,i?m:void 0);this.referencesCache.set(p.symbolId,y),r.set(p.symbolId,y)}catch{m.preciseSearchFailures+=1,l.push(p)}}},()=>({relativePath:u,definitions:d.length,...Yh(m)}))}if(l.length>0){let u=this.referencesForDefinitionsBySymbolScan(l);for(let d of l){let m=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}}return r}referenceFragmentsForFiles(t){let n=xe(this.db).filter(o=>Pt(o.relativePath)),r=t.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(n,r);return zh(n,i,r)}referencesForDefinitionsBySymbolScan(t,n){let r=U(),i=Jh(),o=new Map,s=new Set(t.map(c=>c.symbolId)),a=new Map(t.map(c=>[c.symbolId,c]));for(let c of t)o.set(c.symbolId,[]);return w("typescript.references-map.inverted-scan",()=>{let c=r?W.now():0,l=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let y of t){let h=l.get(y.symbolId)??[];if(h.length>0){let C=o.get(y.symbolId)??[];C.push(...h),o.set(y.symbolId,C)}r&&(i.packageReferenceCount+=h.length)}r&&(i.packageRefsMs+=W.now()-c);let u=new Map,d=new Map,m=this.hierarchyTargetsForDefinitions(t),f=new Set(t.map(y=>y.leaf).filter(Boolean)),p=r?W.now():0;for(let y of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(y))continue;let h=this.sourceFiles.sourceFile(y);h&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(h,y,s,a,m,f,u,d,o,r?i:void 0))}r&&(i.scanMs+=W.now()-p);let g=r?W.now():0;this.addHierarchyMemberReferences(t,o,r?i:void 0),r&&(i.hierarchyMs+=W.now()-g);for(let[y,h]of o){let C=Ar(h);o.set(y,C),r&&(i.referenceCount+=C.length)}},()=>({definitions:t.length,...Yh(i)})),o}addReferencesFromSourceFileScan(t,n,r,i,o,s,a,c,l,u){let d=this.compilerCheckerForSourceFile(t),m=t.compilerNode,f=RL(t),p=g=>{if(this.tsMorph.ts.isIdentifier(g)){if(u&&(u.identifiers+=1),!s.has(g.text)&&!f.has(g.text)){this.tsMorph.ts.forEachChild(g,p);return}let y=this.compilerReferenceSymbol(d,g,u);if(y){let h;a.has(y)?h=a.get(y)??null:(h=this.referenceDefinitionFromCompilerSymbol(y),a.set(y,h)),u&&(h?u.targetHits+=1:u.targetMisses+=1);let C=mt(c,y,()=>this.compilerSymbolKeys(y)),x=null,S=null,b=h&&r.has(h.symbolId)?i.get(h.symbolId):void 0;if(b&&(x=lu(m,g),!qh(b,n,x))){let v=m.getLineAndCharacterOfPosition(g.getStart(m));S={file:n,line:v.line,column:v.character};let R=l.get(b.symbolId)??[];R.push(S),l.set(b.symbolId,R),u&&(u.requestedHits+=1)}for(let v of C)for(let R of o.get(v)?.values()??[]){if(x??=lu(m,g),qh(R,n,x))continue;if(!S){let D=m.getLineAndCharacterOfPosition(g.getStart(m));S={file:n,line:D.line,column:D.character}}let E=l.get(R.symbolId)??[];E.push(S),l.set(R.symbolId,E),u&&(u.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(g,p)};p(m)}hierarchyTargetsForDefinitions(t){let n=new Map;for(let r of t){let i=this.nodeForDefinition(r),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(a,s,c))for(let u of this.compilerSymbolKeys(l)){let d=n.get(u)??new Map;d.set(r.symbolId,r),n.set(u,d)}}return n}hierarchyMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(!o.has(a)){o.add(a),i.add(c);for(let u of l){let d=u.getProperty(r.name);d&&s(u,d,this.hierarchyAncestorTypesForType(t,u))}}};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}addHierarchyMemberReferences(t,n,r){let i=new Map;for(let o of t){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(s.getSourceFile()),u=l.getSymbolAtLocation(a.name);if(!u)continue;let d=a.getSourceFile(),m=d.getLineAndCharacterOfPosition(a.name.getStart(d)),f={definition:o,location:{file:o.relativePath,line:m.line,column:m.character}},p=n.get(o.symbolId)??[];for(let y of this.hierarchyMemberSymbols(l,c,u))if(y!==u)for(let h of this.compilerSymbolLocations(y))p.push(h),r&&(r.hierarchyReferences+=1);n.set(o.symbolId,p);let g=this.hierarchyRootMemberSymbols(l,c,u);for(let y of g){let h=i.get(y)??new Map;h.set(o.symbolId,f),i.set(y,h)}r&&(r.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){r&&(r.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=n.get(s.symbolId)??[];for(let c of o.values())c.definition.symbolId!==s.symbolId&&(a.push(c.location),r&&(r.hierarchyReferences+=1));n.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(o.has(a))return;o.add(a);let u=!1;for(let d of l){let m=d.getProperty(r.name);m&&(u=!0,s(d,m,this.hierarchyAncestorTypesForType(t,d)))}if(!u)for(let d of this.compilerSymbolKeys(c))i.add(d)};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}compilerSymbolKeys(t){return(t.declarations??[]).map(n=>{let r=n.getSourceFile();return`${r.fileName}\0${n.getStart(r)}\0${t.name}`})}compilerSymbolLocations(t){let n=[];for(let r of t.declarations??[]){let i=r.getSourceFile(),o=Mr(this.db.config.projectRoot,i.fileName);if(!o)continue;let s=r.name,a=i.getLineAndCharacterOfPosition((s??r).getStart(i));n.push({file:o,line:a.line,column:a.character})}return n}baseTypes(t,n){try{return t.getBaseTypes(n)??[]}catch{return[]}}hierarchyAncestorTypes(t,n){let r=new Set(this.hierarchyAncestorTypesForType(t,t.getTypeAtLocation(n)));for(let i of n.heritageClauses??[])for(let o of i.types)r.add(t.getTypeAtLocation(o));return[...r]}hierarchyAncestorTypesForType(t,n){let r=new Set(this.baseTypes(t,n));for(let i of n.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let s of o.types)r.add(t.getTypeAtLocation(s));return[...r]}isHierarchyMethod(t){return this.tsMorph.ts.isMethodDeclaration(t)||this.tsMorph.ts.isMethodSignature(t)}isHierarchyContainer(t){return this.tsMorph.ts.isClassDeclaration(t)||this.tsMorph.ts.isClassExpression(t)||this.tsMorph.ts.isInterfaceDeclaration(t)}compilerReferenceSymbol(t,n,r){r&&(r.symbolLookups+=1);let i=t.getSymbolAtLocation(n);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return r&&(r.aliasResolutions+=1),t.getAliasedSymbol(i)}catch{return i}}}calleesFor(t){return mt(this.calleesCache,t.symbolId,()=>mt(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}calleesForDefinitions(t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i])}for(let[i,o]of r){let s=this.fileCalleesCache.get(i),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(i,a);for(let l of o){let u=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,u),n.set(l.symbolId,u)}}return n}referencesForDefinitionNode(t,n,r){let i=r?W.now():0,o=this.packageImportReferencesForDefinition(t);if(r&&(r.packageRefsMs+=W.now()-i,r.packageReferenceCount+=o.length),!n)return o;let s=r?W.now():0,a=Th(n,t,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=W.now()-s,r.referenceCount+=a.length),a}signatureFor(t){return mt(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 Xh(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${Xh(o)}`})}importUsageForSourceFile(t,n,r){let i=[],o=new Map;for(let s of n.getImportDeclarations()){r.declarations+=1;let a=Je(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of du(s)){r.entries+=1;let u=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(u?r.bindingSymbols+=1:r.missingBindingSymbols+=1);let d={sourcePath:a,entry:l,typeOnlyDeclaration:c,bindingSymbol:u,references:[]};if(i.push(d),c||!l.localName||!u)continue;let m=o.get(l.localName);m?m.push(d):o.set(l.localName,[d])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||CL(s))return;r.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(r.symbolLookups+=1,!!c){for(let l of a)if(l.bindingSymbol===c){l.references.push({location:Gs(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?bL(t,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(r.fallbackEntries+=1,this.valueImportUsageForEntry(t,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(t,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let s of i)for(let a of _h(s,t,r.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(t,n,r,o)}valueImportUsageFromLocations(t,n,r,i){let o=i.some(c=>!Zl(c.node)),s=i.some(c=>Zl(c.node)),a=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:a,isUsed:a||i.length>0,isTypeUsed:a||s,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferencesForFiles(t){let n=new Map,r=new Set;for(let o of t){let s=this.sourceFiles.sourceFile(o);if(s)for(let a of s.getImportDeclarations()){let c=ou(this.workspacePackages,a.getModuleSpecifierValue());c&&r.add(c)}}if(r.size===0)return n;let i=this.packageExportsForNames(r);for(let o of t)this.addPackageImportReferencesForDocument(n,i,o);for(let[o,s]of n)n.set(o,Ar(s));return n}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,Ar(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=ou(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=Fh(a.identifier,r,this.db.config.projectRoot);l.length>0&&DL(t,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(t=>t.name))),this.packageExportIndex)}packageExportsForNames(t){let n=new Map;for(let r of this.workspacePackages){if(!t.has(r.name))continue;let i=new Map;for(let o of Oh(r))this.collectPackageExports(r,o,i,new Set);i.size>0&&n.set(r.name,i)}return n}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.relativeDir}/src/`))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 p=r.get(m);p||(p=new Set,r.set(m,p)),p.add(f.symbolId)}}}indexedDefinitionByLeaf(t,n){return mt(this.indexedDefinitionLeafCache,t,()=>Ah(this.db,t)).get(n)??null}nodeForDefinition(t){return mt(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return mt(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?Lh(this.tsMorph,this.db,n,t):new Map})}referenceDefinitionFromCompilerSymbol(t){return this.definitionFromCompilerSymbol(t,void 0,!0)}definitionFromCompilerSymbol(t,n,r=!1){let i=t.name,o=n?W.now():0,s=t.declarations??[];n&&(n.declarationsMs+=W.now()-o,n.declarationChecks+=s.length);for(let a of s){let c=n?W.now():0,l=a.getSourceFile(),u=Mr(this.db.config.projectRoot,l.fileName),d=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(n&&(n.declarationLocationMs+=W.now()-c),!u||this.db.isIgnored(u))continue;let m=n?W.now():0,f=this.compilerDeclarationName(a),p=r?nu(this.db,u,d,i)??(f&&f!==i?nu(this.db,u,d,f):null):Nh(this.db,u,d,i);if(n&&(n.indexedLookupMs+=W.now()-m),p)return{symbolId:p.symbolId,symbol:p.symbol,file:p.relativePath,line:p.startLine}}return null}compilerDeclarationName(t){let n=t.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(t,n){let r=U(),i=0,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=r?IL():void 0;return w("typescript.callee-map.file",()=>{let f=r?W.now():0,p=this.sourceFiles.sourceFile(t);if(r&&(c=Math.round(W.now()-f)),!p)return new Map;let g=r?W.now():0,y=Q(this.db,t).sort((E,D)=>E.startLine-D.startLine||D.endLine-E.endLine);if(r&&(l=Math.round(W.now()-g)),i=y.length,y.length===0)return new Map;let h=new Map,C=r?W.now():0,x=this.compilerCheckerForSourceFile(p),S=p.compilerNode;r&&(u=Math.round(W.now()-C));let b=new Map,v=E=>{if(this.tsMorph.ts.isCallExpression(E)||this.tsMorph.ts.isNewExpression(E)){r&&(o+=1);let D=this.semanticCalleeForCallNode(x,S,y,E,b,n,m);D&&(r&&(s+=1),xL(h,D.callerId,D.target))}this.tsMorph.ts.forEachChild(E,v)},R=r?W.now():0;v(S),r&&(d=Math.round(W.now()-R));for(let[E,D]of h)h.set(E,EL(D));return a=h.size,h},()=>({relativePath:t,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:u,traversalMs:d,...m?wL(m):{}}))}semanticCalleeForCallNode(t,n,r,i,o,s,a){let c=a?W.now():0,l=vL(r,lu(n,i));if(a&&(a.callerLookupMs+=W.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let u=i.expression,d=this.compilerSymbolForExpression(t,u,a),m=null;if(d)if(a&&(a.targetSymbolHits+=1),o.has(d))a&&(a.compilerSymbolCacheHits+=1),m=o.get(d)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let f=a?W.now():0;m=this.definitionFromCompilerSymbol(d,a),a&&(a.targetLookupMs+=W.now()-f),o.set(d,m)}else a&&(a.targetMisses+=1);return m?{callerId:l.symbolId,target:{symbol:m.symbol,file:m.file,line:m.line}}:null}compilerSymbolForExpression(t,n,r){let i=r?W.now():0,o=t.getSymbolAtLocation(n);if(r&&(r.expressionSymbolMs+=W.now()-i),o)return o;r&&(r.typeFallbacks+=1);let s=r?W.now():0,a=t.getTypeAtLocation(n).getSymbol();return r&&(r.typeSymbolMs+=W.now()-s),a}compilerCheckerForSourceFile(t){let n=t.getProject(),r=this.compilerCheckerCache.get(n);return r||(r=n.getTypeChecker().compilerObject,this.compilerCheckerCache.set(n,r)),r}};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 bL(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 SL(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function CL(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function xL(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function RL(e){let t=new Set;for(let n of e.getImportDeclarations())for(let r of du(n))r.localName&&t.add(r.localName);return t}function vL(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 lu(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function qh(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function Kh(e){return e.symbol.includes("#")?ue(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function IL(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function wL(e){return{...e,callerLookupMs:Math.round(e.callerLookupMs),expressionSymbolMs:Math.round(e.expressionSymbolMs),typeSymbolMs:Math.round(e.typeSymbolMs),targetLookupMs:Math.round(e.targetLookupMs),declarationsMs:Math.round(e.declarationsMs),declarationLocationMs:Math.round(e.declarationLocationMs),indexedLookupMs:Math.round(e.indexedLookupMs)}}function Jh(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function Yh(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function DL(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function EL(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 Xh(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}import{createHash as kL}from"crypto";import{readFileSync as PL}from"fs";import{dirname as TL,join as Js}from"path";var Ys=2,_L="typescript-semantic";function Zh(e){let t=Js(e,_L);return{rootDir:t,requestDir:Js(t,"requests"),responseDir:Js(t,"responses")}}function Xs(e){try{let t=JSON.parse(PL(Js(TL(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||typeof t.status!="string"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:kL("sha256").update(JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages})).digest("hex")}catch{return null}}var ML=12e4,OL=5;function oy(e,t,n={}){let r=new mu(e,n),i=null,o=null,s=process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1",a=()=>(i??=Qh(e,t),i),c=(d,m,f)=>{if(s)return f();try{return m(r.request(d))}catch{return s=!0,f()}},l=(d,m)=>c({kind:"references",definitions:[...d],...m?.exact?{exact:!0}:{}},f=>iy(f),()=>a().referencesForDefinitions?.(d,m)??new Map(d.map(f=>[f.symbolId,a().referencesFor(f)]))),u=d=>c({kind:"callees",definitions:[...d]},m=>iy(m),()=>a().calleesForDefinitions?.(d)??new Map(d.map(m=>[m.symbolId,a().calleesFor(m)])));return{language:"typescript",availability:()=>(o??=c({kind:"availability"},$L,()=>a().availability()),o),importUsage:d=>c({kind:"import-usage",file:d},m=>m,()=>a().importUsage(d)),referencesFor:d=>l([d]).get(d.symbolId)??[],referencesForDefinitions:l,referenceFragmentsForFiles:d=>c({kind:"reference-fragments",files:[...d]},m=>BL(m),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>u([d]).get(d.symbolId)??[],calleesForDefinitions:u,signatureFor:d=>c({kind:"signature",definition:d},HL,()=>a().signatureFor(d)),dispose:()=>i?.dispose?.()}}var mu=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??WL,this.timeoutMs=n.timeoutMs??UL(),this.cacheDir=AL(t.config.dbPath),this.projectRoot=vt(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;request(t){let n=kh(this.cacheDir),r=Zh(this.cacheDir),i=Ql(n.statePath);if(!ry(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript semantic service is not running.");let o=Xs(this.db.config.dbPath);if(!o)throw new Error("Published TypeScript generation identity is unavailable.");let s=this.runtime.randomId(),a=ny(r.requestDir,`${s}.json`),c=ny(r.responseDir,`${s}.json`),l=this.runtime.now()+this.timeoutMs;ey(r.requestDir,{recursive:!0}),ey(r.responseDir,{recursive:!0}),_e(a,{protocolVersion:Ys,id:s,generation:o,deadlineAtMs:l,profileEnvironment:hf(),request:t});try{for(;this.runtime.now()<=l;){if(LL(c))return jL(NL(c,"utf8"),s,o);let u=Ql(n.statePath);if(!ry(u,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(OL)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}finally{ty(a,{force:!0}),ty(c,{force:!0})}}};function ry(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Eh,i=e?.typescriptSemantic?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptSemantic.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===Ys&&n.isProcessAlive(e.pid)&&(r||i)}function jL(e,t,n){let r=JSON.parse(e);if(r.protocolVersion!==Ys||r.id!==t||r.ok===!0&&r.generation!==n)throw new Error("TypeScript semantic service wrote an incompatible response.");if(r.ok===!0)return r.response;throw new Error(typeof r.error=="string"?r.error:"TypeScript semantic service request failed.")}function iy(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function BL(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function $L(e){if(!e||typeof e!="object"||typeof e.available!="boolean")throw new Error("TypeScript semantic service wrote invalid availability.");return e}function HL(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function UL(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:ML}var WL={now:Date.now,randomId:FL,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:dt};var sy=new Ws;dn({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>sy.clear(e)});function Or(e,t){let n=De(t)??"typescript";return sy.getOrCreate(e,n,()=>n==="rust"?vh(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>Cg(e,r)},calleeSymbolResolver:Sg(e),sourceZeroCalleeOracle:r=>GL(e,r),scipOccurrenceCalleeOracle:r=>Dh(e,r)}):oy(e,t))}function De(e){return e?M(e)==="rust"?"rust":Pt(e)?"typescript":null:"typescript"}function GL(e,t){let n=G(e,t.relativePath);if(!n||n.language!=="rust")return!1;let r=n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine&&i.name===t.leaf)??n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return r?!n.callSites.some(i=>i.line>=r.startLine&&i.line<=r.endLine):!1}import{existsSync as zL,readFileSync as VL}from"fs";import{resolve as qL}from"path";var KL=/^[A-Za-z_][A-Za-z0-9_]*$/,ay=/\bDefault::default\b/g,JL=/^\.\.\s*Default::default\b/;function cy(e,t){let n=new Map,r=new Map;for(let i of t){let o=fu(e,i,r);o!==null&&n.set(i.symbolId,o)}return n}function fu(e,t,n=new Map){let r=XL(t.symbol);if(!r)return null;let i=_r(e,[t.symbolId]);if(i.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${$(r)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${$(r)}\\s*$`),a=YL(e,t.symbolId),c=[];for(let l of i){let u=QL(e,l.relative_path,n);if(u===null)return null;let d=u.split(/\r?\n/),m=0,f=[],p=0;for(let g=l.chunk_start;g<=l.chunk_end&&g<d.length;g+=1){let h=d[g]??"",C=new Set;o.lastIndex=0;let x;for(;x=o.exec(h);)c.push({file:l.relative_path,line:g,column:x.index+x[1].length+r.length+2}),p+=1;for(let S=0;S<h.length;S+=1){let b=JL.exec(h.slice(S));if(b){if(a&&f.includes(m)){let R=S+b[0].lastIndexOf("default");c.push({file:l.relative_path,line:g,column:R}),C.add(R),p+=1}S+=b[0].length-1;continue}let v=h[S];if(v==="{"){let R=s.test(h.slice(0,S));m+=1,R&&f.push(m);continue}if(v==="}")for(m=Math.max(0,m-1);f.length>0&&f[f.length-1]>m;)f.pop()}for(ay.lastIndex=0;x=ay.exec(h);){let S=x.index+9;if(!C.has(S))return null}}if(p===0)return null}return Ns(c)}function YL(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function XL(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!KL.test(t)?null:t}function QL(e,t,n){if(n.has(t))return n.get(t)??null;let r=e.get("SELECT text FROM documents WHERE relative_path = ?",t),i=typeof r?.text=="string"?r.text:ZL(e,t);return n.set(t,i),i}function ZL(e,t){let n=qL(e.config.projectRoot,t);if(!zL(n))return null;try{return VL(n,"utf8")}catch{return null}}import{readFileSync as rN}from"fs";import{dirname as iN,join as oN}from"path";function Zs(e){let t=Qs(e.projectFiles),n=new Set(t),r=new Map(e.snapshot.files.map(d=>[d.path,d])),i=e.snapshot.files.filter(d=>{let m=Nl(d.path,["typescript"]);return m==="config"||m==="ambient"}).map(d=>d.path),o=Qs([...t,...i]),s=o.find(d=>!r.has(d)),a=new Set(e.snapshot.files.map(d=>d.path)).size!==e.snapshot.files.length,c=!s&&o.some(d=>ly(r.get(d))),l=he(JSON.stringify({pnpmWorkspaces:e.snapshot.pnpmWorkspaces,typescriptProjectMode:e.snapshot.typescriptProjectMode,typescriptProjects:Qs(e.snapshot.typescriptProjects),membership:t})),u=new Map;return{identityFor(d,m){if(!n.has(d))return jr("target-outside-project");if(a)return jr("duplicate-input-path");if(s)return jr("missing-input-fingerprint");if(c)return jr("unreadable-input");let f=[],p,g;if(e.graph===null)f.push("dependency-graph-unavailable"),g="whole-project",p=o;else{let C=tN(d,e.graph,u);if(C.find(S=>!r.has(S)))return jr("missing-input-fingerprint");if(p=Qs([...C,...i]),p.some(S=>ly(r.get(S))))return jr("unreadable-input");g="dependency-closure"}let y=p.map(C=>nN(r.get(C)));return{version:1,key:he(JSON.stringify({version:1,engineIdentity:e.engineIdentity,schemaVersion:m,projectIdentity:l,inputs:y})),mode:g,inputFiles:p,reasons:f}}}}function eN(e,t){let n=new Set,r=[e];for(let i=0;i<r.length;i+=1){let o=r[i];if(!(o===void 0||n.has(o))){n.add(o);for(let s of[...t.get(o)??[]].sort())n.has(s)||r.push(s)}}return[...n].sort()}function tN(e,t,n){let r=n.get(e);if(r)return r;let i=eN(e,t);return n.set(e,i),i}function nN(e){return{path:e.path,size:e.size,hash:e.hash}}function ly(e){return e.size<0||e.hash==="unreadable"}function jr(e){return{version:1,key:null,mode:"unkeyed",inputFiles:[],reasons:[e]}}function Qs(e){return[...new Set(e)].sort()}var sN=J("typescript-semantic-identity-context",{clearGroups:["whole-project"]});function In(e,t,n){let r=sN.get(e,()=>aN(e));if(!r)return null;let i=`${n}\0${t}`,o=r.identities.get(i);if(o)return o;let s=r.builder.identityFor(t,n);return r.identities.set(i,s),s}function Hi(e){return N(e,{includeIgnored:!1}).filter(Pt).sort()}function aN(e){try{let t=JSON.parse(rN(oN(iN(e.config.dbPath),"meta.json"),"utf8")),n=Wg(t.fingerprint);return n?{builder:Zs({projectFiles:Hi(e),snapshot:n,graph:ie(e),engineIdentity:Vs()}),identities:new Map}:null}catch{return null}}var pu="typescript-reference-fragment-v2",ta=oe({kind:"typescript-reference-fragments",invalidation:K("typescript-reference-fragments"),serialize:e=>JSON.stringify(e),deserialize:lN});function l7(e,t,n,r=e){let i=Hi(e),o=Zs({projectFiles:i,snapshot:t,graph:ie(e),engineIdentity:Vs()}),s=[...n].map(([a,c])=>({relativePath:a,contentHash:o.identityFor(a,pu).key,value:[...c]}));if(s.some(a=>a.contentHash===null))throw new Error("TypeScript reference fragment identity is unavailable for an affected document.");return ta.writeBatch(r,s.map(a=>({...a,contentHash:a.contentHash}))),s.length}function gu(e,t,n){let r=t.filter(o=>Pt(o.relativePath));if(r.length===0)return ea("no TypeScript definitions");let i=ea("shadow did not run");return w("typescript.reference-fragments.shadow",()=>{try{let o=Or(e,r[0].relativePath);if(!o.availability().available||!o.referenceFragmentsForFiles)return i=ea("TypeScript reference fragment provider is unavailable"),i;let s=Hi(e),a=new Set(s),c=o.referenceFragmentsForFiles(s),l=Ks(r,c),u=Gh(r,cN(n,a),l);if(!u.passed)return i={state:"failing",files:s.length,keyedFiles:0,writtenFiles:0,...u},i;let d=[];for(let m of s){let f=In(e,m,pu);f?.key&&d.push({relativePath:m,contentHash:f.key,value:c.get(m)??[]})}return ta.writeBatch(e,d),i={state:"passing",files:s.length,keyedFiles:d.length,writtenFiles:d.length,...u},i}catch(o){return i=ea(o instanceof Error?o.message:String(o)),i}},()=>({...i}))}function cN(e,t){return new Map([...e].map(([n,r])=>[n,r.filter(i=>t.has(i.file))]))}function hu(e,t){if(t.length===0)return{references:new Map,files:0,cacheHits:0,cacheMisses:0,computedFiles:0};let n="fallback",r=0,i=0,o=0,s=0;return w("typescript.reference-fragments.materialize",()=>{try{let a=Hi(e);r=a.length;let c=new Map,l=new Map,u=[];for(let f of a){let p=In(e,f,pu);if(!p?.key)return null;c.set(f,p.key);let g=ta.read(e,f,p.key);g===null?(o+=1,u.push(f)):(i+=1,l.set(f,g))}if(o===0)return n="hit",{references:Ks(t,l),files:r,cacheHits:i,cacheMisses:o,computedFiles:s};let d=Or(e,t[0].relativePath);if(!d.availability().available||!d.referenceFragmentsForFiles)return null;let m=d.referenceFragmentsForFiles(u);if(u.some(f=>!m.has(f)))return null;s=m.size,ta.writeBatch(e,u.map(f=>({relativePath:f,contentHash:c.get(f),value:m.get(f)??[]})));for(let[f,p]of m)l.set(f,p);return n="computed",{references:Ks(t,l),files:r,cacheHits:i,cacheMisses:o,computedFiles:s}}catch{return null}},()=>({state:n,files:r,cacheHits:i,cacheMisses:o,computedFiles:s}))}function ea(e){return{state:"unavailable",files:0,keyedFiles:0,writtenFiles:0,expectedCount:0,actualCount:0,missing:[],extra:[],reason:e}}function lN(e){try{let t=JSON.parse(e);return!Array.isArray(t)||!t.every(uN)?null:t}catch{return null}}function uN(e){if(!e||typeof e!="object")return!1;let t=e,n=t.location;return typeof t.targetSymbol=="string"&&!!n&&typeof n.file=="string"&&typeof n.line=="number"&&typeof n.column=="number"}var dN="typescript-import-usage-v1",mN="typescript-signatures-v1",yu=J("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),uy=jn({kind:"semantic-import-usage",invalidation:K("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:xy}),dy=jn({kind:"semantic-signatures",invalidation:K("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:xN}),my=oe({kind:"typescript-import-usage",invalidation:K("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:xy}),fy=oe({kind:"typescript-signatures",invalidation:K("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:RN});function We(e){let t=new Map,n=new Set;return{capability:(r,i)=>Ry(e,r,i),importUsage:r=>pN(e,r),references:r=>hy(e,r),materializeReferences:(r,i)=>by(e,r,t,n,i),callerMap:r=>gN(e,r,t,n),calleeMap:r=>bN(e,r),signature:r=>SN(e,r)}}function fN(e,t){if(t.size===0)return;let n=yu.get(e,()=>new Map);for(let[r,i]of t)n.set(r,[...i])}function gy(e,t){if(!yu.has(e))return{hits:[],misses:[...t]};let n=yu.get(e,()=>new Map),r=[],i=[];for(let o of t)n.has(o.symbolId)?r.push({definition:o,callees:n.get(o.symbolId)??[]}):i.push(o);return{hits:r,misses:i}}function Wi(e,t){return We(e).importUsage(t)}function pN(e,t){if(De(t)==="typescript"){let o="fallback",s=0,a=0,c=0,l=0;return w("typescript.import-usage.materialize",()=>{let u=In(e,t,dN);if(u?.key){s=1;let m=my.read(e,t,u.key);if(m)return o="hit",a=1,m;c=1;let f=Tt(e,t);if(!f)return o="unavailable",[];let p=f.importUsage(t);return my.write(e,t,u.key,p),o="computed",p}l=1;let d=Tt(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:l}))}let n=Cy(e,"semantic-import-usage",t);if(n){let o=uy.read(e,t,n);if(o)return o}let r=Tt(e,t);if(!r)return[];let i=r.importUsage(t);return n&&uy.write(e,t,n,i),i}function na(e,t){return We(e).references(t)}function hy(e,t){let n=fu(e,t);if(n)return n;let r=Ng(e,t);if(r)return r;let i=Tt(e,t.relativePath);return i?i.referencesFor(t):[]}function wn(e,t){return We(e).callerMap(t)}function yy(e,t){let n=new Map,r=new Map;for(let i of t){if(De(i.relativePath)==="typescript"){let o=Tt(e,i.relativePath);if(!o)continue;let s=r.get(o)??[];s.push(i),r.set(o,s);continue}bu(e,n,i,hy(e,i))}for(let[i,o]of r){let s=hu(e,o),a=s?.references??(i.referencesForDefinitions?i.referencesForDefinitions(o,{exact:!0}):new Map(o.map(c=>[c.symbolId,i.referencesFor(c)])));!s&&U()&&gu(e,o,a);for(let c of o)bu(e,n,c,a.get(c.symbolId)??[])}return n}function gN(e,t,n=new Map,r=new Set){let i=new Map,o=by(e,t,n,r),s=0;return w("semantic.callers.from-references",()=>{for(let a of t)s+=bu(e,i,a,n.get(a.symbolId)??[])},()=>({definitions:t.length,materialized:o.definitions,inMemoryHits:o.inMemoryHits,incompleteInMemoryHits:o.incompleteInMemoryHits,resultRows:i.size,callerFiles:s})),i}function by(e,t,n,r,i={}){let o=Te(e),s=[],a=[],c=[],l=0,u=0,d=0,m=0,f=0,p=0,g=0,y=0,h=0,C=0,x=0,S=0,b=[],v=new Map,R=t.filter(D=>De(D.relativePath)==="typescript"&&!n.has(D.symbolId)&&!r.has(D.symbolId)),E=hu(e,R);if(E){h=R.length,C=E.cacheHits,x=E.cacheMisses,S=E.computedFiles;for(let D of R)n.set(D.symbolId,E.references.get(D.symbolId)??[])}if(w("semantic.references.cache-scan",()=>{for(let[D,k]of Ts(t)){let L=[];for(let F of k)n.has(F.symbolId)?u+=1:r.has(F.symbolId)?y+=1:L.push(F);if(L.length===0){g+=1;continue}let ne=hN(e,o,D);if(!ne){for(let F of L)De(F.relativePath)||(l+=1),c.push(F);continue}p+=1;let X=Zm(e,D,ne);for(let F of L){let ae=X.get(F.symbol)??null;if(ae!==null){let Z=yN(ae);if(Z){d+=1,n.set(F.symbolId,Z);continue}m+=1}a.push({definition:F,cacheFingerprint:ne})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:l,cacheHits:d,parseFailures:m,misses:a.length,unkeyed:c.length,inMemoryHits:u,incompleteInMemoryHits:y,fullyInMemoryFiles:g,cacheReadFiles:p})),a.length>0||c.length>0){b=[...c,...a.map(D=>D.definition)],v=w("semantic.references.compute-misses",()=>{let D=Su(e,b,i);return f=D.size,D},()=>({definitions:b.length,misses:a.length,unkeyed:c.length,rows:f}));for(let D of b)v.has(D.symbolId)?(n.set(D.symbolId,v.get(D.symbolId)??[]),r.delete(D.symbolId)):r.add(D.symbolId);for(let{definition:D,cacheFingerprint:k}of a)v.has(D.symbolId)&&Ry(e,"semantic-references",D.relativePath).available&&s.push({relativePath:D.relativePath,symbol:D.symbol,projectFingerprint:k,payload:JSON.stringify(v.get(D.symbolId)??[])})}return s.length>0&&w("semantic.references.cache-write",()=>tf(e,s),()=>({entries:s.length})),v.size>0&&gu(e,b,v),{definitions:t.length,inMemoryHits:u,incompleteInMemoryHits:y,cacheHits:d,misses:a.length,unkeyed:c.length,skippedUnsupportedLanguage:l,parseFailures:m,computed:f,incomplete:r.size,cacheWrites:s.length,fragmentDefinitions:h,fragmentCacheHits:C,fragmentCacheMisses:x,fragmentComputedFiles:S}}function hN(e,t,n){if(!t)return null;let r=De(n);return r==="typescript"?t:r==="rust"?he(JSON.stringify({kind:"semantic-references",language:r,engine:Kn(e.config.projectRoot),projectFingerprint:t})):null}function Su(e,t,n={}){let r=U(),i=new Map,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=0,f=0;return w("semantic.references.provider-loop",()=>{let p=cy(e,t),g=Lg(e,t),y=new Map,h=n.prefetchCallees?new Map:null,C=[];for(let S of t){let b,v=()=>(b??=Tt(e,S.relativePath),b);if(h){let k=v();if(k?.referencesAndCalleesForDefinitions){let L=h.get(k);L?L.push(S):h.set(k,[S]),f+=1}}let R=p.get(S.symbolId);if(R){a+=1,c+=R.length,Ui(i,S.symbolId,R,r,k=>{d+=1,m+=k});continue}let E=g.get(S.symbolId);if(E){l+=1,u+=E.length,Ui(i,S.symbolId,E,r,k=>{d+=1,m+=k});continue}let D=v();if(!D){r&&(s+=1);continue}if(r&&(o+=1),D.referencesForDefinitions){let k=y.get(D);k?k.push(S):y.set(D,[S])}else C.push({provider:D,definition:S})}let x=new Set;if(h)for(let[S,b]of h){if(!S.referencesAndCalleesForDefinitions)continue;let v=y.get(S)??[],R=S.referencesAndCalleesForDefinitions(v,b);x.add(S),fN(e,R.callees);for(let E of v){if(!R.references.has(E.symbolId))continue;let D=R.references.get(E.symbolId)??[];Ui(i,E.symbolId,D,r,k=>{d+=1,m+=k})}}for(let[S,b]of y){if(x.has(S))continue;let v=S.referencesForDefinitions(b);for(let R of b){if(!v.has(R.symbolId))continue;let E=v.get(R.symbolId)??[];Ui(i,R.symbolId,E,r,D=>{d+=1,m+=D})}}for(let{provider:S,definition:b}of C){let v=S.referencesFor(b);Ui(i,b.symbolId,v,r,R=>{d+=1,m+=R})}return i},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:c,rustScipOccurrenceFastPathRows:l,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:f,definitionsWithReferences:d,referenceCount:m,rows:i.size}))}function Ui(e,t,n,r,i){e.set(t,n),r&&n.length>0&&i(n.length)}function bu(e,t,n,r){let i=0;for(let o of r){if(o.file===n.relativePath||e.isIgnored(o.file))continue;let s=t.get(n.symbolId);s||(s=new Set,t.set(n.symbolId,s));let a=s.size;s.add(o.file),s.size!==a&&(i+=1)}return i}function yN(e){try{return JSON.parse(e)}catch{return null}}function ra(e,t){return We(e).calleeMap(t)}function bN(e,t){let n=U(),r=new Map,i=0,o=0,s=0,a=0;return w("semantic.callees.provider-loop",()=>{let c=new Map,l=[];for(let u of t){let d=Tt(e,u.relativePath);if(!d){n&&(o+=1);continue}n&&(i+=1);let m=u;if(d.calleesForDefinitions){let f=c.get(d);f?f.push(m):c.set(d,[m])}else l.push({provider:d,definition:m})}for(let[u,d]of c){let m=u.calleesForDefinitions(d);for(let f of d){let p=m.get(f.symbolId)??[];py(r,f.symbolId,p,n,g=>{s+=1,a+=g})}}for(let{provider:u,definition:d}of l){let m=u.calleesFor(d);py(r,d.symbolId,m,n,f=>{s+=1,a+=f})}return r},()=>({definitions:t.length,providerHits:i,providerMisses:o,definitionsWithCallees:s,calleeCount:a,rows:r.size}))}function py(e,t,n,r,i){n.length>0&&(e.set(t,n),r&&i(n.length))}function Sy(e,t){return We(e).signature(t)}function SN(e,t){if(De(t.relativePath)==="typescript"){let s="fallback",a=0,c=0,l=0,u=0;return w("typescript.signature.materialize",()=>{let d=In(e,t.relativePath,mN);if(d?.key){a=1;let f=fy.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(f,t.symbol))return s="hit",c=1,f[t.symbol]??null;l=1;let p=Tt(e,t.relativePath);if(!p)return s="unavailable",null;let g=p.signatureFor(t);return fy.write(e,t.relativePath,d.key,{...f,[t.symbol]:g}),s="computed",g}u=1;let m=Tt(e,t.relativePath);return m?(s="direct-fallback",m.signatureFor(t)):(s="unavailable",null)},()=>({state:s,eligible:a,cacheHits:c,cacheMisses:l,fallbacks:u}))}let n=Cy(e,"semantic-signatures",t.relativePath),r=CN(t);if(n){let s=dy.read(e,r,n);if(s)return s.signature}let i=Tt(e,t.relativePath);if(!i)return null;let o=i.signatureFor(t);return n&&dy.write(e,r,n,{signature:o}),o}function Cy(e,t,n){let r=Te(e);if(!r)return null;let i=De(n);return i!=="rust"?null:he(JSON.stringify({kind:t,language:i,engine:Kn(e.config.projectRoot),projectFingerprint:r}))}function CN(e){return`${e.relativePath}\0${e.symbol}`}function xy(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function xN(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t.signature;return n!==null&&typeof n!="string"?null:{signature:n}}catch{return null}}function RN(e){try{let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return null;for(let n of Object.values(t))if(n!==null&&typeof n!="string")return null;return t}catch{return null}}function Ry(e,t,n){let r=De(n);if(!r)return{slot:t,language:"typescript",available:!1,reason:"semantic evidence is only available for TypeScript or Rust files"};try{return{slot:t,language:r,...Or(e,n).availability()}}catch(i){return{slot:t,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function Tt(e,t){if(!De(t))return null;let n=Or(e,t);return n.availability().available?n:null}var H={references:na,referenceMap:Su,callerMap:(e,t)=>We(e).callerMap(t),calleeMap:Cu};function Cu(e,t){let n=U(),r=new Map,i=gy(e,t),o=[],s=[],a=0,c=0,l=0,u=0,d=0,m=0,f=0;for(let{definition:x,callees:S}of i.hits)d+=1,S.length>0&&(m+=1,f+=S.length,r.set(x.symbolId,S));let p=vN(e,i.hits);if(p.entries.length>0&&w("semantic.callees.prefetch-cache-write",()=>Dc(e,p.entries),()=>({entries:p.entries.length,sourceMissing:p.sourceMissing,skippedUnsupportedLanguage:p.skippedUnsupportedLanguage})),w("semantic.callees.cache-scan",()=>{for(let[x,S]of Ts(i.misses)){if(!De(x)){n&&(a+=S.length);continue}let b=P(e,x);if(!b){n&&(c+=S.length),s.push(...S);continue}let v=ce(e,x,b),R=vy(e,x);if(!R){s.push(...S);continue}let E=Qm(e,x,v,R);for(let D of S){let k=E.get(D.symbol)??null;if(k!==null){let L=wN(k);if(L){n&&(l+=1),L.length>0&&r.set(D.symbolId,L);continue}n&&(u+=1)}o.push({def:D,contentHash:v,depsDigest:R})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:a,sourceMissing:c,cacheHits:l,parseFailures:u,misses:o.length,unkeyed:s.length,inMemoryHits:d,inMemoryRows:m,inMemoryCalleeCount:f,resultRows:r.size})),o.length===0&&s.length===0)return r;let g=[...s,...o.map(x=>x.def)],y=0,h=w("semantic.callees.compute-misses",()=>{let x=ra(e,g);return y=x.size,x},()=>({definitions:g.length,misses:o.length,unkeyed:s.length,rows:y}));for(let[x,S]of h)r.set(x,S);let C=o.filter(x=>We(e).capability("semantic-callees",x.def.relativePath).available).map(x=>({relativePath:x.def.relativePath,symbol:x.def.symbol,contentHash:x.contentHash,depsDigest:x.depsDigest,payload:JSON.stringify(h.get(x.def.symbolId)??[])}));return C.length>0?w("semantic.callees.cache-write",()=>Dc(e,C),()=>({entries:C.length})):w("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:o.length})),r}function vN(e,t){let n=[],r=new Map,i=0,o=0;for(let{definition:s,callees:a}of t){if(!De(s.relativePath)){o+=1;continue}if(!r.has(s.relativePath)){let l=P(e,s.relativePath),u=l?vy(e,s.relativePath):null;r.set(s.relativePath,l&&u?{contentHash:ce(e,s.relativePath,l),depsDigest:u}:null)}let c=r.get(s.relativePath);if(!c){i+=1;continue}n.push({relativePath:s.relativePath,symbol:s.symbol,contentHash:c.contentHash,depsDigest:c.depsDigest,payload:JSON.stringify(a)})}return{entries:n,sourceMissing:i,skippedUnsupportedLanguage:o}}var IN="typescript-callees-v1";function vy(e,t){let n=De(t);if(n==="typescript")return In(e,t,IN)?.key??null;let r=EN(e,t);return n==="rust"?he(JSON.stringify({kind:"semantic-callees",language:n,engine:Kn(e.config.projectRoot),positionMapping:"nearby-leaf-v1",depsDigest:r})):r}function wN(e){try{return JSON.parse(e)}catch{return null}}var DN=j("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function EN(e,t){return DN.get(e,t,()=>{let r=[...ie(e).get(t)??[]].sort().map(i=>`${i}:${ce(e,i,P(e,i))}`);return he(r.join("|"))})}function $7(e,t,n={}){let r=B(e,t);if(!r)return[];let o=!ee(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=Et(e,r,{semantic:n.semantic,semanticEvidence:H}).map(u=>({relativePath:u.file,line:u.line})),a=kN(e,r),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 kN(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=PN(t.symbol);if(n.length===0)return[];let r=[];for(let i of N(e,{extensions:[".rb"],includeIgnored:!1})){let o=P(e,i);if(!o)continue;let s=o.split(`
|
|
287
|
+
`);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&r.push({relativePath:i,line:a})}}return r}function PN(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,""),r=n.split("_").filter(Boolean),i=new Set;return n&&i.add(n),r.length>=1&&i.add(r[r.length-1]),r.length>=2&&i.add(r.slice(-2).join("_")),[...i]}import{existsSync as TN}from"fs";import{basename as Iy,isAbsolute as _N,join as FN}from"path";function Oe(e,t){let n=wy(e,t,{allowMultiple:!1})[0]?.relativePath;return n||LN(e,t)}function Br(e,t){return wy(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function LN(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=_N(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=FN(e.config.projectRoot,r);return TN(i)?r:null}function wy(e,t,n){let r=Dy(t);if(!r)return[];let i=N(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:NN(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 NN(e,t){let n=Dy(e),r=Iy(n),i=Iy(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 Dy(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}function Y7(e,t){let n=Br(e,t),r=ys(e,n,{sort:!0});if(r.length===0)return[];let i=r.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 i)o.set(a.symbol,a);let s=[];for(let a=0;a<r.length;a++){let c=r[a],l=i[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 i)if(m!==l&&m.startLine<=l.startLine&&m.endLine>=l.endLine){if(m.startLine===l.startLine&&m.endLine===l.endLine&&!vf(m.symbol,l.symbol))continue;let p=m.endLine-m.startLine;p<d&&(d=p,u=m)}u?u.children.push(l):s.push(l)}return s}import{readFileSync as Ey}from"fs";import{extname as AN,join as ky}from"path";function ree(e,t,n={}){let{context:r=0}=n,i=MN(t);if(i)return jN(e,i.filePath,i.startLine,i.endLine,r);let o=B(e,t);return o?ON(e,o,r):null}function MN(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 ON(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=ky(e.config.projectRoot,t.relativePath),o;try{o=Ey(i,"utf-8")}catch{return null}let s=o.split(`
|
|
288
288
|
`),a=Math.max(0,t.startLine-n),c=Math.min(s.length-1,t.endLine+n),l=s.slice(a,c+1).join(`
|
|
289
|
-
`);return{symbol:t.symbol,shortName:I(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:r?.language??Py(t.relativePath),source:l}}function
|
|
289
|
+
`);return{symbol:t.symbol,shortName:I(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:r?.language??Py(t.relativePath),source:l}}function jN(e,t,n,r,i){let o=Oe(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=ky(e.config.projectRoot,s.relative_path),c;try{c=Ey(a,"utf-8")}catch{return null}let l=c.split(`
|
|
290
290
|
`),u=Math.max(0,n-1-i),d=Math.min(l.length-1,r-1+i),m=l.slice(u,d+1).join(`
|
|
291
|
-
`);return{symbol:`${s.relative_path}:${n}-${r}`,shortName:`${s.relative_path}:${n}-${r}`,relativePath:s.relative_path,startLine:u,endLine:d,language:s.language??Py(s.relative_path),source:m}}function Py(e){switch(
|
|
291
|
+
`);return{symbol:`${s.relative_path}:${n}-${r}`,shortName:`${s.relative_path}:${n}-${r}`,relativePath:s.relative_path,startLine:u,endLine:d,language:s.language??Py(s.relative_path),source:m}}function Py(e){switch(AN(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}}import{createRequire as BN}from"module";var $N=BN(import.meta.url),Xn=HN().version;function HN(){for(let e of["../package.json","../../package.json"])try{return $N(e)}catch{}return{version:"0.0.0"}}import{existsSync as rd,statSync as t0}from"fs";import{join as n0}from"path";import{createHash as UN}from"crypto";import{mkdirSync as WN,realpathSync as GN}from"fs";import{homedir as zN}from"os";import{join as Qn,resolve as Ty}from"path";function VN(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return xu(n);if(t?.dbPath)return xu(Ty(e,t.dbPath));let r=ia(e);return xu(r)}function _y(){let e=process.env.XDG_CACHE_HOME;return Qn(e||Qn(zN(),".cache"),"scip-query")}function ia(e){let t=Ty(e);try{t=GN(t)}catch{}let n=UN("sha256").update(t).digest("hex").slice(0,12);return Qn(_y(),"projects",n)}function Gi(e){if(!/^[a-f0-9]{24}$/.test(e))throw new Error(`invalid repository cache identity: ${e}`);return Qn(_y(),"repositories",e)}function Ru(e){return process.env.SCIP_QUERY_SHARED_CACHE!=="0"&&!process.env.SCIP_QUERY_CACHE_DIR&&!process.env.SCIP_QUERY_INDEX_DB&&!e?.dbPath}function Fy(e,t){let n=VN(e,t);return{cacheDir:n,dbPath:Qn(n,"index.db"),indexPath:Qn(n,"index.scip"),metaPath:Qn(n,"meta.json")}}function xu(e){return WN(e,{recursive:!0}),e}import qN from"better-sqlite3";var KN=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".nbb",".cpcache",".shadow-cljs",".scipquery-cache","__pycache__",".venv","venv"],oa=class{db;config;pathFilter;statementCache=new Map;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new qN(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000"),this.db.pragma("query_only = ON"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("cache_size = -64000"),this.db.pragma("mmap_size = 268435456")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
|
|
292
292
|
EXISTS (
|
|
293
293
|
SELECT 1
|
|
294
294
|
FROM defn_enclosing_ranges local_der
|
|
@@ -305,9 +305,9 @@ ${m}`,l+=1+m.length,u+=Ci(m),r+=m.length+1}let d=eP(c);d&&n.push({...d,start:a,e
|
|
|
305
305
|
AND local_m.role = 1
|
|
306
306
|
${this.pathExclusionsFor("local_d").trimStart()}
|
|
307
307
|
)
|
|
308
|
-
)`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>
|
|
309
|
-
`)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.statement(t).all(...n)}get(t,...n){return this.statement(t).get(...n)}close(){this.statementCache.clear(),this.db.close()}statement(t){let n=this.statementCache.get(t);return n||(n=this.db.prepare(t),this.statementCache.set(t,n)),n}};import
|
|
310
|
-
`)}function
|
|
308
|
+
)`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>KN.flatMap(r=>[`AND ${n}.relative_path NOT LIKE '${r}/%'`,`AND ${n}.relative_path NOT LIKE '%/${r}/%'`])).join(`
|
|
309
|
+
`)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.statement(t).all(...n)}get(t,...n){return this.statement(t).get(...n)}close(){this.statementCache.clear(),this.db.close()}statement(t){let n=this.statementCache.get(t);return n||(n=this.db.prepare(t),this.statementCache.set(t,n)),n}};import JN from"ignore";import{readFileSync as YN,existsSync as Ly,readdirSync as XN}from"fs";import{dirname as vu,isAbsolute as Ny,join as sa,relative as QN,resolve as ZN}from"path";function Ay(e){let t=JN();return eA(e,t)||t.add(rA),{isIgnored:r=>Iu(t,e,r),filter:r=>r.filter(i=>!Iu(t,e,i))}}function eA(e,t){let n=new Set,r=(s,a)=>{if(!(n.has(s)||!Ly(s)))try{let c=YN(s,"utf-8");t.add(a?tA(c,a):c),n.add(s)}catch{}},i=vu(e),o=0;for(;i!==vu(i)&&o<5&&(r(sa(i,".gitignore"),""),!Ly(sa(i,".git")));)i=vu(i),o++;return My(e,"",t,r),n.size>0}function My(e,t,n,r){let i=t?sa(e,t):e;r(sa(i,".gitignore"),t);let o;try{o=XN(i,{withFileTypes:!0})}catch{return}for(let s of o){if(!s.isDirectory()||s.name===".git")continue;let a=t?`${t}/${s.name}`:s.name;Iu(n,e,`${a}/`)||My(e,a,n,r)}}function tA(e,t){let n=t.replaceAll("\\","/").replace(/\/+$/,"");return e.split(/\r?\n/).map(r=>nA(r,n)).join(`
|
|
310
|
+
`)}function nA(e,t){let n=e.trimStart();if(!n||n.startsWith("#"))return e;let r=e.slice(0,e.length-n.length),i=n.startsWith("!"),o=i?n.slice(1):n;if(!o||o.startsWith("#"))return e;let s=o.startsWith("/"),a=s?o.slice(1):o,u=(a.endsWith("/")?a.slice(0,-1):a).includes("/")||s?`${t}/${a}`:`${t}/**/${a}`;return`${r}${i?"!":""}${u}`}var rA=`
|
|
311
311
|
# Dependencies
|
|
312
312
|
node_modules/
|
|
313
313
|
vendor/
|
|
@@ -364,21 +364,21 @@ Thumbs.db
|
|
|
364
364
|
|
|
365
365
|
# Type definitions (often noise in queries)
|
|
366
366
|
*.d.ts
|
|
367
|
-
`;function Iu(e,t,n){let r=rA(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function rA(e,t){if(!t||t===".")return null;if(!Ny(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=Ny(t)?t:QN(e,t),r=XN(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readFileSync as iA,writeFileSync as wu,existsSync as Qt}from"fs";import{isAbsolute as Oy,join as Zn,relative as jy,resolve as By}from"path";var $r=".scipquery.json",Uy=250,Wy=0,Gy=10*6e4,oA={enabled:!1,debounceMs:Uy,cooldownMs:Wy,gitPollMs:2e3,idleTimeoutMs:Gy,autoRefresh:!0,ignore:[]},zy=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"],sA=new Set(["languages","indexerConcurrency","watch","hooks","indexer","dbPath","entryRoots","semantic","suppressions","declaredCouplings","locality","architecture","coverageContracts","docs"]),aA=new Set(["enabled","debounceMs","cooldownMs","gitPollMs","idleTimeoutMs","autoRefresh","ignore"]),cA=new Set(["router"]),lA=new Set(["pathPrefixes","files","symbolPatterns","qualifiedVars"]),uA=new Set(["typescript","rust"]),dA=new Set(["tsconfigs"]),mA=new Set(["rustAnalyzerPath"]),$y=new Set(zy),fA=new Set(["pnpmWorkspaces","projectMode","projects","configPath"]),pA=new Set(["architecturalBoundarySegments"]),gA=new Set(["boundaries","allowedDependencies","requireCompletePolicy","requireAcyclic"]),hA=new Set(["name","paths"]),yA=new Set(["snapshotPaths"]),bA=new Set(["name","files","reason"]),SA=new Set(["id","check","file","reason","expiresAt","createdAt"]),CA=new Set(["name","file","keys","mustEqual","allowExtra"]),xA=new Set(["type","identifier","marker"]),RA=new Set(["type","path","pattern"]),vA=new Set(["object-literal-keys","string-array","markdown-list"]),IA=new Set(["top-level-dirs","file-glob","registered-commands","builtin-skills"]);function Vy(e){let t=Zn(e,$r);if(!Qt(t))return{};try{let n=iA(t,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);throw n instanceof SyntaxError?new Error(`invalid ${$r} at ${t}: ${r}`,{cause:n}):new Error(`unable to read ${$r} at ${t}: ${r}`,{cause:n})}}function See(e,t={}){let n=[];PA(e,n);let r=new Set(zy);for(let[c,l]of(e.languages??[]).entries())r.has(l)||n.push({level:"error",path:`languages[${c}]`,message:`Unsupported language: ${l}`});e.indexerConcurrency!==void 0&&(!Number.isInteger(e.indexerConcurrency)||e.indexerConcurrency<=0)&&n.push({level:"error",path:"indexerConcurrency",message:"Must be a positive integer."}),e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&n.push({level:"error",path:"watch.debounceMs",message:"Must be greater than 0."}),e.watch?.cooldownMs!==void 0&&(!Number.isInteger(e.watch.cooldownMs)||e.watch.cooldownMs<0)&&n.push({level:"error",path:"watch.cooldownMs",message:"Must be a non-negative integer; 0 disables cooldown spacing."}),e.watch?.gitPollMs!==void 0&&e.watch.gitPollMs<=0&&n.push({level:"error",path:"watch.gitPollMs",message:"Must be greater than 0."}),e.watch?.idleTimeoutMs!==void 0&&(!Number.isInteger(e.watch.idleTimeoutMs)||e.watch.idleTimeoutMs<0)&&n.push({level:"error",path:"watch.idleTimeoutMs",message:"Must be a non-negative integer; 0 disables idle shutdown."}),e.watch?.autoRefresh!==void 0&&typeof e.watch.autoRefresh!="boolean"&&n.push({level:"error",path:"watch.autoRefresh",message:"Must be a boolean."}),e.hooks?.router!==void 0&&e.hooks.router!=="off"&&e.hooks.router!=="single"&&n.push({level:"error",path:"hooks.router",message:'Must be "off" or "single".'});let i=e.indexer?.typescript;if(i?.projectMode!==void 0&&i.projectMode!=="single"&&i.projectMode!=="workspace"&&n.push({level:"error",path:"indexer.typescript.projectMode",message:'Must be "single" or "workspace".'}),i?.projects!==void 0)if(!Array.isArray(i.projects))n.push({level:"error",path:"indexer.typescript.projects",message:"Must be an array."});else for(let[c,l]of i.projects.entries()){let u=`indexer.typescript.projects[${c}]`;if(typeof l!="string"||l.trim()==="")n.push({level:"error",path:u,message:"Project path must be a non-empty string."});else if(t.projectRoot){let d=By(t.projectRoot,l),m=jy(t.projectRoot,d);m.startsWith("..")||Oy(m)?n.push({level:"error",path:u,message:"Project path must stay inside the project root."}):Qt(d)||n.push({level:"warning",path:u,message:`TypeScript project path does not exist: ${l}`})}}i?.projectMode==="workspace"&&i.pnpmWorkspaces===!0&&n.push({level:"warning",path:"indexer.typescript.pnpmWorkspaces",message:'Ignored when projectMode is "workspace"; explicit TypeScript projects are indexed directly.'});let o=e.semantic?.rust;o?.rustAnalyzerPath!==void 0&&(typeof o.rustAnalyzerPath!="string"||o.rustAnalyzerPath.trim()==="")&&n.push({level:"error",path:"semantic.rust.rustAnalyzerPath",message:"Rust analyzer path must be a non-empty string."});let s=e.indexer?.clojure;if(s?.configPath!==void 0){let c="indexer.clojure.configPath";if(typeof s.configPath!="string"||s.configPath.trim()==="")n.push({level:"error",path:c,message:"Config path must be a non-empty string."});else if(t.projectRoot){let l=By(t.projectRoot,s.configPath),u=jy(t.projectRoot,l);u.startsWith("..")||Oy(u)?n.push({level:"error",path:c,message:"Config path must stay inside the project root."}):Qt(l)||n.push({level:"warning",path:c,message:`Clojure indexer config path does not exist: ${s.configPath}`})}}if(e.locality!==void 0)if(!Xe(e.locality))n.push({level:"error",path:"locality",message:"Must be an object."});else{let c=e.locality.architecturalBoundarySegments;if(c!==void 0)if(!Array.isArray(c))n.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});else for(let[l,u]of c.entries()){let d=`locality.architecturalBoundarySegments[${l}]`;typeof u!="string"||u.trim()===""?n.push({level:"error",path:d,message:"Boundary segment must be a non-empty string."}):(u.includes("/")||u.includes("\\"))&&n.push({level:"error",path:d,message:"Boundary segment must be a single folder name, not a path."})}}if(wA(e,n),e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings))n.push({level:"error",path:"declaredCouplings",message:"Must be an array."});else for(let[c,l]of(e.declaredCouplings??[]).entries()){let u=`declaredCouplings[${c}]`;if((!l.name||l.name.trim()==="")&&n.push({level:"error",path:`${u}.name`,message:"Declared coupling name is required."}),!Array.isArray(l.files)||l.files.length<2)n.push({level:"error",path:`${u}.files`,message:"Declared coupling needs at least two files."});else for(let[d,m]of l.files.entries())!m||m.trim()===""?n.push({level:"error",path:`${u}.files[${d}]`,message:"Declared coupling file path is required."}):t.projectRoot&&!Qt(Zn(t.projectRoot,m))&&n.push({level:"warning",path:`${u}.files[${d}]`,message:`Declared coupling file does not exist: ${m}`});l.reason!==void 0&&l.reason.trim()===""&&n.push({level:"error",path:`${u}.reason`,message:"Declared coupling reason cannot be blank."})}let a=t.now??new Date;e.suppressions!==void 0&&!Array.isArray(e.suppressions)&&n.push({level:"error",path:"suppressions",message:"Must be an array."});for(let[c,l]of(Array.isArray(e.suppressions)?e.suppressions:[]).entries()){let u=`suppressions[${c}]`;if(!Xe(l)){n.push({level:"error",path:u,message:"Suppression must be an object."});continue}if((!l.reason||l.reason.trim()==="")&&n.push({level:"error",path:`${u}.reason`,message:"Suppression reason is required."}),l.id!==void 0&&l.id.trim()===""&&n.push({level:"error",path:`${u}.id`,message:"Suppression id cannot be blank."}),l.check!==void 0&&l.check.trim()===""&&n.push({level:"error",path:`${u}.check`,message:"Suppression check cannot be blank."}),!l.id&&(!l.check||!l.file)?n.push({level:"error",path:u,message:"Suppression must include id or both check and file."}):!l.id&&l.check&&l.file&&n.push({level:"warning",path:u,message:"Check+file suppressions waive every matching finding in that file; prefer a stable id when available."}),l.file!==void 0&&(l.file.trim()===""?n.push({level:"error",path:`${u}.file`,message:"Suppression file path cannot be blank."}):t.projectRoot&&!Qt(Zn(t.projectRoot,l.file))&&n.push({level:"warning",path:`${u}.file`,message:`Suppression file does not exist: ${l.file}`})),l.expiresAt){let d=Date.parse(l.expiresAt);Number.isNaN(d)?n.push({level:"error",path:`${u}.expiresAt`,message:"Must be an ISO date string."}):d<=a.getTime()&&n.push({level:"warning",path:`${u}.expiresAt`,message:"Suppression has expired."})}}return kA(e,n,t),EA(e,n),n}function wA(e,t){if(e.architecture===void 0)return;if(!Xe(e.architecture)){t.push({level:"error",path:"architecture",message:"Must be an object."});return}let n=e.architecture.boundaries;if(!Array.isArray(n)||n.length===0){t.push({level:"error",path:"architecture.boundaries",message:"Must be a non-empty array."});return}let r=new Set,i=new Set;for(let[s,a]of n.entries()){let c=`architecture.boundaries[${s}]`;if(!Xe(a)){t.push({level:"error",path:c,message:"Architecture boundary must be an object."});continue}let l=a.name;typeof l!="string"||l.trim()===""?t.push({level:"error",path:`${c}.name`,message:"Boundary name is required."}):r.has(l)?t.push({level:"error",path:`${c}.name`,message:`Duplicate boundary name: ${l}`}):r.add(l);let u=a.paths;if(!Array.isArray(u)||u.length===0){t.push({level:"error",path:`${c}.paths`,message:"Boundary paths must be a non-empty array."});continue}for(let[d,m]of u.entries()){let f=`${c}.paths[${d}]`;if(typeof m!="string"||m.trim()===""){t.push({level:"error",path:f,message:"Boundary path must be a non-empty string."});continue}DA(m)||t.push({level:"error",path:f,message:"Boundary path must be project-relative and may use only one trailing /* or /** glob."}),i.has(m)?t.push({level:"error",path:f,message:`Duplicate boundary path: ${m}`}):i.add(m)}}let o=e.architecture.allowedDependencies;if(o!==void 0&&!Xe(o))t.push({level:"error",path:"architecture.allowedDependencies",message:"Must be an object keyed by boundary name."});else if(Xe(o))for(let[s,a]of Object.entries(o)){let c=`architecture.allowedDependencies.${s}`;if(r.has(s)||t.push({level:"error",path:c,message:`Unknown source boundary: ${s}`}),!Array.isArray(a)){t.push({level:"error",path:c,message:"Dependency row must be an array."});continue}let l=new Set;for(let[u,d]of a.entries()){let m=`${c}[${u}]`;typeof d!="string"||d.trim()===""?t.push({level:"error",path:m,message:"Target boundary name is required."}):r.has(d)?l.has(d)?t.push({level:"error",path:m,message:`Duplicate target boundary: ${d}`}):l.add(d):t.push({level:"error",path:m,message:`Unknown target boundary: ${d}`})}}if(e.architecture.requireAcyclic!==void 0&&typeof e.architecture.requireAcyclic!="boolean"&&t.push({level:"error",path:"architecture.requireAcyclic",message:"Must be a boolean."}),e.architecture.requireCompletePolicy!==void 0&&typeof e.architecture.requireCompletePolicy!="boolean")t.push({level:"error",path:"architecture.requireCompletePolicy",message:"Must be a boolean."});else if(e.architecture.requireCompletePolicy===!0){let s=Xe(o)?o:{};for(let a of[...r].sort())Object.hasOwn(s,a)||t.push({level:"error",path:`architecture.allowedDependencies.${a}`,message:"A dependency row is required by architecture.requireCompletePolicy."})}}function DA(e){let t=e.replace(/\\/g,"/");if(t.startsWith("/")||t==="."||t===".."||t.split("/").includes(".."))return!1;let n=t.replace(/\/\*\*?$/,"");return n.length>0&&!/[*?[\]]/.test(n)}function EA(e,t){let n=e.docs?.snapshotPaths;if(n!==void 0){if(!Array.isArray(n)){t.push({level:"error",path:"docs.snapshotPaths",message:"Must be an array."});return}for(let[r,i]of n.entries())(typeof i!="string"||i.trim()==="")&&t.push({level:"error",path:`docs.snapshotPaths[${r}]`,message:"Snapshot path glob must be a non-empty string."})}}function kA(e,t,n){if(e.coverageContracts!==void 0){if(!Array.isArray(e.coverageContracts)){t.push({level:"error",path:"coverageContracts",message:"Must be an array."});return}for(let[r,i]of e.coverageContracts.entries()){let o=`coverageContracts[${r}]`;if(!Xe(i)){t.push({level:"error",path:o,message:"Coverage contract must be an object."});continue}(typeof i.name!="string"||i.name.trim()==="")&&t.push({level:"error",path:`${o}.name`,message:"Coverage contract name is required."}),typeof i.file!="string"||i.file.trim()===""?t.push({level:"error",path:`${o}.file`,message:"Coverage contract file is required."}):n.projectRoot&&!Qt(Zn(n.projectRoot,i.file))&&t.push({level:"warning",path:`${o}.file`,message:`Coverage contract file does not exist: ${i.file}`}),Hy(t,i.keys,`${o}.keys`,vA,"Unknown coverage-contract key extractor type."),Hy(t,i.mustEqual,`${o}.mustEqual`,IA,"Unknown coverage-contract ground-truth source type."),i.allowExtra!==void 0&&typeof i.allowExtra!="boolean"&&t.push({level:"error",path:`${o}.allowExtra`,message:"Must be a boolean."})}}}function Hy(e,t,n,r,i){if(!Xe(t)){e.push({level:"error",path:n,message:'Must be an object with a "type" field.'});return}if(typeof t.type!="string"||!r.has(t.type)){e.push({level:"error",path:`${n}.type`,message:`${i} Got: ${String(t.type)}`});return}let o={"object-literal-keys":["identifier"],"string-array":["identifier"],"markdown-list":["marker"],"top-level-dirs":["path"],"file-glob":["pattern"],"registered-commands":[],"builtin-skills":[]};for(let s of o[t.type]??[])(typeof t[s]!="string"||t[s].length===0)&&e.push({level:"error",path:`${n}.${s}`,message:`"${t.type}" requires a non-empty string "${s}".`})}function Cee(e){return{...oA,...e.watch}}function xee(e,t){let n=Zn(e,$r);return Qt(n)||wu(n,JSON.stringify({languages:t,watch:{enabled:!0,debounceMs:Uy,cooldownMs:Wy,gitPollMs:2e3,idleTimeoutMs:Gy,autoRefresh:!0}},null,2)+`
|
|
368
|
-
`),n}function
|
|
369
|
-
`),{configPath:r,config:i,changed:o}}function
|
|
370
|
-
`),{configPath:r,config:i,changed:o}}function
|
|
371
|
-
`)){if(!r||r.split("/").some(o=>Xy.has(o)))continue;let i=Jy(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function
|
|
372
|
-
`)}finally{cb(a)}return{release:()=>pb(e,s)}}catch(a){if(a.code!=="EEXIST")return null;let c=fb(e);if(c&&(c.pid===void 0||!
|
|
373
|
-
`)}finally{cb(i)}try{let o=fb(e);return!o||o.raw!==t.raw||o.pid!==void 0&&ct(o.pid)?!1:(db(e),!0)}catch{return!1}finally{pb(n,r)}}function pb(e,t){try{let n=JSON.parse(ub(e,"utf8"));n.pid===process.pid&&n.token===t&&db(e)}catch{}}function eM(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}import{lstatSync as gM,readdirSync as hM}from"fs";import{join as yM,relative as bM,resolve as ju,sep as SM}from"path";import{createHash as tM}from"crypto";import{existsSync as _u,mkdirSync as nM,readFileSync as ma,readdirSync as qee,renameSync as rM,rmSync as Kee,writeFileSync as iM}from"fs";import{join as Ur}from"path";import{create as hb,fromBinary as yb,toBinary as oM}from"@bufbuild/protobuf";import{deserializeSCIP as fa,DocumentSchema as Fu,IndexSchema as bb,serializeSCIP as Sb}from"@c4312/scip";var pa=1,Ki="typescript-scip-fragments";function Zee(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let o of e){let s=er(o.relativePath);if(t.has(s))throw new Error(`duplicate TypeScript fragment replacement: ${s}`);if(t.add(s),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${s}`);let a=yb(Fu,o.bytes);if(a.relativePath!==s)throw new Error(`TypeScript fragment path mismatch: expected ${s}, got ${a.relativePath}`);n.push(a)}let r=Sb(hb(bb,{documents:n,externalSymbols:[]})),i=fa(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function ga(e){let t=Ur(e,Ki);return{rootDir:t,blobDir:Ur(t,"blobs"),generationDir:Ur(t,"generations")}}function sM(e){let t=fa(e.indexBytes);kb(t.metadata,Pb(e)),Eb(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let s=er(o.relativePath);if(n.has(s))throw new Error(`duplicate TypeScript SCIP document path: ${s}`);n.add(s);let a=oM(Fu,o),c=e.documentIdentities.get(s)??(e.allowUntrackedDocuments?tr(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:s,contentHash:tr(a)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${s}`);r.push(vb(e.cacheDir,{relativePath:s,bytes:a,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=Ib(e,r);return wb(e.cacheDir,i),i}function ete(e){let t=ga(e.cacheDir);if(!_u(Lu(t,e.generationIdentity)))return sM(e);let n=Cb({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&n.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let r of n.manifest.documents){let i=e.documentIdentities.get(r.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==r.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${r.relativePath}`)}return n.manifest}function tte(e){let t=Cb({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let s=er(o.relativePath);if(r.has(s))throw new Error(`duplicate TypeScript fragment replacement: ${s}`);if(r.add(s),!n.has(s))throw new Error(`TypeScript fragment replacement has no prior document: ${s}`);let a=e.documentIdentities.get(s);if(!a)throw new Error(`missing TypeScript document identity: ${s}`);o.bytes===null?n.delete(s):n.set(s,vb(e.cacheDir,o,a))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Ib(e,[...n.values()]);return wb(e.cacheDir,i),i}function Cb(e){let t=ga(e.cacheDir),n=Lu(t,e.generationIdentity),r;try{r=Db(ma(n,"utf8"))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of r.documents){let s=Ur(t.blobDir,`${o.blobHash}.scipdoc`),a=ma(s);if(a.byteLength!==o.byteLength||tr(a)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,a)}return{manifest:r,fragments:i}}function xb(e){let t=Rb(e);return Tu(t.baseIndex,t.completeDocuments,"assembled")}function nte(e){let t=Rb(e);return aM(t.deletedAffectedPaths),{completeIndexBytes:Tu(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:Tu(t.baseIndex,t.affectedDocuments,"affected")}}function Rb(e){let t=fa(e.baseIndexBytes);kb(t.metadata,Pb(e)),Eb(t.externalSymbols);let n=new Map;for(let a of e.fragments){let c=er(a.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,a)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],o=[],s=[];for(let a of t.documents){let c=er(a.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let l=n.get(c);if(!l){i.push(a);continue}if(n.delete(c),l.bytes===null){s.push(c);continue}let u=yb(Fu,l.bytes);if(u.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${u.relativePath}`);i.push(u),o.push(u)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:s}}function Tu(e,t,n){let r=Sb(hb(bb,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=fa(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function aM(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function vb(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=er(t.relativePath),i=Buffer.from(t.bytes),o=tr(i),s=ga(e);nM(s.blobDir,{recursive:!0});let a=Ur(s.blobDir,`${o}.scipdoc`);if(_u(a)){let c=ma(a);if(c.byteLength!==i.byteLength||tr(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${a}.${process.pid}.${Date.now()}.tmp`;iM(c,i),rM(c,a)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function Ib(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let n=[...t].sort((r,i)=>r.relativePath.localeCompare(i.relativePath));if(new Set(n.map(r=>r.relativePath)).size!==n.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:pa,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function wb(e,t){let n=ga(e),r=Lu(n,t.generationIdentity);if(_u(r)){let i=Db(ma(r,"utf8"));if(gb(i)!==gb(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}_e(r,t,{spacing:2,trailingNewline:!0})}function gb(e){return tr(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Db(e){let t=JSON.parse(e);if(t.version!==pa||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(er(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function Lu(e,t){return Ur(e.generationDir,cM(t))}function cM(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${tr(e)}.json`}function Eb(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function kb(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let n=e,r=n.toolInfo??n.tool_info;if(!r||typeof r!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=r;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function Pb(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function er(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}function tr(e){return tM("sha256").update(e).digest("hex")}import{createHash as lM}from"crypto";import{existsSync as Ji,mkdirSync as uM,readFileSync as Xi,readdirSync as Nu,renameSync as dM,rmSync as Tb,writeFileSync as mM}from"fs";import{join as bt}from"path";var ha=1,lte=64*1024*1024,Qi="typescript-scip-overlays";function ute(e){let t=Fb(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let n=new Map((t?.overlays??[]).map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let s=Ou(o.relativePath);if(r.has(s))throw new Error(`duplicate TypeScript overlay: ${s}`);r.add(s),n.set(s,fM(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:ha,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((o,s)=>o.relativePath.localeCompare(s.relativePath))};return pM(e.cacheDir,i),i}function dte(e){let t=Fb(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let n=t.overlays.map(r=>{if(r.blobHash===null)return{relativePath:r.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=Xi(bt(Zi(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||Yi(i)!==r.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${r.relativePath}`);return{relativePath:r.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return xb({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function mte(e,t){let n=Zi(e),r=bt(n,"generations");if(!Ji(r))return;let i=new Set(t.map(Mu)),o=new Set;for(let a of Nu(r).filter(c=>i.has(c))){let c=Au(Xi(bt(r,a),"utf8"));for(let l of c.overlays)l.blobHash&&o.add(`${l.blobHash}.scipdoc`)}for(let a of Nu(r))i.has(a)||Tb(bt(r,a),{force:!0});let s=bt(n,"blobs");if(Ji(s))for(let a of Nu(s))o.has(a)||Tb(bt(s,a),{force:!0})}function Fb(e,t){let n=bt(Zi(e),"generations",Mu(t));if(!Ji(n))return null;let r=Au(Xi(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function fM(e,t){let n=Ou(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=Yi(r),o=bt(Zi(e),"blobs");uM(o,{recursive:!0});let s=bt(o,`${i}.scipdoc`);if(Ji(s)){let a=Xi(s);if(a.byteLength!==r.byteLength||Yi(a)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let a=`${s}.${process.pid}.${Date.now()}.tmp`;mM(a,r),dM(a,s)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function pM(e,t){let n=bt(Zi(e),"generations",Mu(t.generationIdentity));if(Ji(n)){let r=Au(Xi(n,"utf8"));if(_b(r)!==_b(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}_e(n,t,{spacing:2,trailingNewline:!0})}function Au(e){let t=JSON.parse(e);if(t.version!==ha||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let n=new Set;for(let r of t.overlays){if(!r||typeof r.relativePath!="string"||r.blobHash!==null&&(typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash))||!Number.isInteger(r.byteLength)||r.byteLength<0||r.blobHash===null&&r.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(Ou(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function Zi(e){return bt(e,Qi)}function Mu(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${Yi(e)}.json`}function _b(e){return Yi(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Ou(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function Yi(e){return lM("sha256").update(e).digest("hex")}var eo=1,Bu="language-indexes",Lb=["index.db","index.scip","meta.json"],Nb=[Bu,Ki,Qi];function ya(e){let t=[];for(let n of Lb)CM(e,n),t.push(n);for(let n of Nb)Ab(e,n,t);return{version:eo,files:t.sort()}}function ba(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."))throw new Error(`invalid index artifact path: ${e}`);let n=t[0];if(!Lb.includes(e)&&!Nb.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function Tt(e,t){let n=ba(t),r=ju(e),i=ju(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${SM}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function Ab(e,t,n){let r=yM(e,t),i;try{i=hM(r,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let s=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${s}`);o.isDirectory()?Ab(e,s,n):o.isFile()&&n.push(ba(s))}}function CM(e,t){let n=Tt(e,t),r;try{r=gM(n)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!r.isFile()||r.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(bM(ju(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{readFileSync as Hu,writeFileSync as Uu}from"fs";import{create as to}from"@bufbuild/protobuf";import{deserializeSCIP as Wu,serializeSCIP as Gu,DocumentSchema as kM,IndexSchema as Ob,MetadataSchema as PM,SymbolInformationSchema as TM}from"@c4312/scip";import{readFileSync as xM,writeFileSync as RM}from"fs";import{create as Mb}from"@bufbuild/protobuf";import{deserializeSCIP as vM,DocumentSchema as IM,IndexSchema as wM,serializeSCIP as DM,SymbolRole as EM}from"@c4312/scip";function Rte(e){let t;try{t=vM(xM(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=$u(t);return n.removedDefinitionOccurrences>0&&RM(e,Buffer.from(DM(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function $u(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,r=0,i=[];for(let o of e.documents){let s=o.occurrences.filter(a=>(a.symbolRoles&EM.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(Mb(IM,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Mb(wM,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function jb(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=FM(e),n=LM(e.flatMap(i=>i.documents??[])),r=$b(e.flatMap(i=>i.externalSymbols??[]));return to(Ob,{metadata:t,documents:n,externalSymbols:r})}function kte(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Wu(Hu(i))),r=jb(n);return Uu(t,Buffer.from(Gu(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function Pte(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Wu(Hu(i))),r=$u(jb(n));return Uu(t,Buffer.from(Gu(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function _M(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return to(Ob,{metadata:to(PM,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function Bb(e,t,n){let r=Wu(Hu(e)),i=_M(r,t,n);Uu(e,Buffer.from(Gu(i)))}function FM(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function LM(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,to(kM,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:NM([...r.occurrences,...n.occurrences]),symbols:$b([...r.symbols,...n.symbols]),text:MM(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function NM(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function $b(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,to(TM,{symbol:r.symbol,documentation:OM([...r.documentation,...n.documentation]),relationships:AM([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function AM(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function MM(e,t){return e?t?e.length>=t.length?e:t:e:t}function OM(e){return[...new Set(e)]}var Yu=1,Wb="SCIP_QUERY_SHARED_CACHE",Vu=JSON.stringify({cliVersion:Xn,artifactCatalogVersion:eo,sqliteGenerationStoreVersion:Hr,typescriptFragmentStoreVersion:pa,typescriptOverlayStoreVersion:ha}),Qb="manifest.json",Zb="shared-cache.json",Xu=[Bu,Ki,Qi];function Sa(e,t){if(!e.clean||!e.treeOid)return;let n=io(JSON.stringify({version:Yu,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Vu}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Vu,generationId:n,repositoryCacheDir:Gi(e.repositoryId)}}function eS(e,t,n){if(process.env[Wb]==="0")return`${Wb}=0`;if(!Ru(n))return"explicit cache or database override";if(St(t)!==St(A(ia(e),"index.db")))return"index database is outside the managed worktree cache"}function tS(e,t,n){if(!Ru(t))return;let r=n??gr(e);return r?A(Gi(r.repositoryId),"evidence.db"):void 0}function rr(e,t=!0){let n=ed(e),r;try{r=zM(Qe(A(n,Qb),"utf8"))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||JSON.stringify(r.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return r;try{for(let i of r.artifacts){let o=Tt(n,i.path),s=UM(o);if(!s.isFile()||s.size!==i.size||io(Qe(o))!==i.sha256)return null}}catch{return null}return r}function nS(e){let t=rr(e.snapshot);if(t)return t;if(!Wr(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=Gb(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=ya(e.sourceCacheDir),i=A(e.snapshot.repositoryCacheDir,"generations");Zt(i,{recursive:!0});let o=qb(A(i,`.tmp-${process.pid}-`));try{let s=[];for(let d of r.files){let m=Tt(e.sourceCacheDir,d),f=Tt(o,d);ro(m,f);let p=Qe(f);s.push({path:d,size:p.byteLength,sha256:io(p)})}let a=Xb(Qe(A(o,"index.scip"))).metadata?.projectRoot;if(!a)throw new Error("shared SCIP generation has no project root metadata");let c=td(e.sourceProjectRoot);if(a!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(Gb(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let l={version:Yu,artifactCatalogVersion:eo,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:a,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:s.sort((d,m)=>d.path.localeCompare(m.path))};_e(A(o,Qb),l,{spacing:2,trailingNewline:!0});let u=ed(e.snapshot);try{if(En(u)&&!rr(e.snapshot)){let d=`${u}.corrupt-${process.pid}-${Date.now()}`;nr(u,d),Dn(d,{recursive:!0,force:!0})}nr(o,u)}catch(d){let m=rr(e.snapshot);if(m)return m;throw d}return l}finally{Dn(o,{recursive:!0,force:!0})}}function qu(e){let t=ed(e.snapshot);Zt(e.targetCacheDir,{recursive:!0});let n=Pu(A(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=qb(A(e.targetCacheDir,".shared-hydrate-")),QM(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let l=Tt(t,c.path),u=Tt(r,c.path);ro(l,u);let d=Qe(u);if(d.byteLength!==c.size||io(d)!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let s=td(e.targetProjectRoot);if(s!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&Bb(Tt(r,c.path),e.manifest.scipProjectRoot,s);if(!Wr(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=JM(e.targetCacheDir,r),o=!0,YM(r,e.targetCacheDir,i),rb({tempOutputScip:A(r,"index.scip"),tempOutputDb:A(r,"index.db"),tempMetaPath:A(r,"meta.json"),outputScip:A(e.targetCacheDir,"index.scip"),outputDb:A(e.targetCacheDir,"index.db"),metaPath:A(e.targetCacheDir,"meta.json"),now:e.now});let a=qi(A(e.targetCacheDir,"index.db"),A(e.targetCacheDir,"meta.json"));if(a.state==="invalid"||a.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${a.reason}`);Ku(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(s){throw o&&i&&XM(e.targetCacheDir,i),s}finally{r&&Dn(r,{recursive:!0,force:!0}),n.release()}}function rS(e,t,n,r){let i=eS(e,n.dbPath,t);if(i)return{kind:"bypassed",reason:i};try{let o=r??gr(e);if(!o)return{kind:"missed",reason:"Git worktree identity is unavailable"};if(!o.clean)return Ca(o,n.cacheDir,"missed",void 0,"worktree has uncommitted changes"),{kind:"missed",reason:"worktree has uncommitted changes"};let s=t.languages??zi(e),a=Pi(e,s,oS(t)),c=Sa(o,a);if(!c)return{kind:"missed",reason:"clean committed snapshot is unavailable"};let l=rr(c);if(l)return qu({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:c.generationId};let u=VM(c,e);return u?(l=u.manifest,qu({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e,action:"peer-imported"}),{kind:"peer-imported",generationId:c.generationId,sourceProjectRoot:u.sourceProjectRoot}):(Ca(o,n.cacheDir,"missed",void 0,"no exact shared or peer generation exists"),{kind:"missed",reason:"no exact shared or peer generation exists"})}catch(o){return{kind:"failed",reason:o instanceof Error?o.message:String(o)}}}function Qu(e,t,n,r){let i=eS(e,n.dbPath,t);if(i)return{kind:"bypassed",reason:i};try{let o=r??gr(e);if(!o)return{kind:"missed",reason:"Git worktree identity is unavailable"};if(!o.clean)return Ca(o,n.cacheDir,"missed",void 0,"worktree is not a clean committed snapshot"),{kind:"missed",reason:"worktree is not a clean committed snapshot"};let s=t.languages??zi(e),a=Pi(e,s,oS(t)),c=Sa(o,a);if(!c)return Ca(o,n.cacheDir,"missed",void 0,"worktree is not a clean committed snapshot"),{kind:"missed",reason:"worktree is not a clean committed snapshot"};let l=rr(c);if(l)return Wr(n.cacheDir,e,a)?(Ku(c,n.cacheDir,"local-fresh"),{kind:"local-fresh"}):(qu({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:c.generationId});let u=xa(n.cacheDir);return u?.status!=="complete"||JSON.stringify(u.fingerprint)!==JSON.stringify(a)||JSON.stringify([...u.indexedLanguages??[]].sort())!==JSON.stringify([...s].sort())?{kind:"missed",reason:"local metadata does not match the clean worktree snapshot"}:Wr(n.cacheDir,e,a)?(nS({snapshot:c,sourceCacheDir:n.cacheDir,sourceProjectRoot:e,sourceStillValid:()=>{let d=gr(e);return(d?Sa(d,a):void 0)?.generationId===c.generationId}}),Ku(c,n.cacheDir,"built"),{kind:"built",generationId:c.generationId}):{kind:"missed",reason:"local index artifacts are incomplete or incompatible"}}catch(o){return{kind:"failed",reason:o instanceof Error?o.message:String(o)}}}async function Xte(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??Date.now,o=i()+n,s=A(e.repositoryCacheDir,"locks"),a=A(s,`${e.generationId}.lock`);for(Zt(s,{recursive:!0});i()<=o;){if(rr(e))return{kind:"generation-ready"};let c=Ju();try{let l=Kb(a,"wx");try{Jb(l,`${JSON.stringify({version:1,pid:process.pid,token:c,generationId:e.generationId,startedAt:new Date(i()).toISOString()})}
|
|
374
|
-
`)}finally{Vb(l)}return{kind:"owner",release:()=>{try{let u=JSON.parse(
|
|
375
|
-
`)}finally{Vb(i)}try{let o=sS(e);return!o||o.raw!==t.raw||o.pid!==void 0&&ct(o.pid)?!1:(zu(e),!0)}catch{return!1}finally{try{let o=JSON.parse(Qe(n,"utf8"));o.pid===process.pid&&o.token===r&&zu(n)}catch{}}}function aS(e,t,n){let r=ku(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!En(A(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=A(e,"worktrees");Zt(i,{recursive:!0}),_e(A(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),qM(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function JM(e,t){let n=A(t,".rollback"),r=new Map,i=new Map;Zt(n,{recursive:!0});for(let a of["index.scip","index.db","meta.json"]){let c=A(e,a),l=En(c);r.set(a,l),l&&ro(c,A(n,"stable",a))}for(let a of Xu){let c=A(e,a),l=En(c);if(l){let u=BM(c);if(!u.isDirectory()||u.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${a}`)}i.set(a,l)}let o=A(e,la),s=En(o);return s&&cS(o,A(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:s}}function YM(e,t,n){for(let r of Xu){let i=A(t,r);if(n.managedDirectories.get(r)){let s=A(n.root,"managed",r);Zt(Yb(s),{recursive:!0}),nr(i,s)}let o=A(e,r);En(o)&&nr(o,i)}}function XM(e,t){for(let i of Xu){let o=A(e,i),s=A(t.root,"managed",i);t.managedDirectories.get(i)?En(s)&&(Dn(o,{recursive:!0,force:!0}),nr(s,o)):Dn(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let s=A(e,i);if(!o){Dn(s,{force:!0});continue}let a=`${s}.shared-restore-${Ju()}`;ro(A(t.root,"stable",i),a),Dn(s,{force:!0}),nr(a,s)}let n=A(e,la);Dn(n,{recursive:!0,force:!0});let r=A(t.root,"sqlite-generations");t.generationStoreExisted&&En(r)&&nr(r,n)}function cS(e,t){Zt(t,{recursive:!0});for(let n of $M(e,{withFileTypes:!0})){let r=A(e,n.name),i=A(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?cS(r,i):n.isFile()&&ro(r,i)}}function QM(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function Wr(e,t,n,r=!0,i=!0){try{let o=xa(e);if(o?.status!=="complete"||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return no("source validation rejected metadata"),!1;let s=ya(e),a=qi(A(e,"index.db"),A(e,"meta.json"));if(r?a.state!=="current":a.state==="invalid"||a.state==="drifted")return no(`source validation rejected SQLite generation state ${a.state}`),!1;let c=new GM(A(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let l=td(t),d=(i?s.files.filter(m=>m.endsWith(".scip")):["index.scip"]).every(m=>{let f=Xb(Qe(Tt(e,m))).metadata?.projectRoot;return f!==l&&no(`source validation rejected SCIP root for ${m}: ${String(f)}`),f===l});return d||no("source validation rejected SCIP project roots"),d}catch(o){return no(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function no(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function td(e){try{return Ub(HM(e)).href}catch{return Ub(St(e)).href}}function ZM(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===2&&Array.isArray(t.languages)&&typeof t.pnpmWorkspaces=="boolean"&&(t.typescriptProjectMode==="single"||t.typescriptProjectMode==="workspace")&&Array.isArray(t.typescriptProjects)&&Array.isArray(t.files)&&t.files.every(n=>n!==null&&typeof n=="object"&&typeof n.path=="string"&&typeof n.size=="number"&&typeof n.hash=="string")}function io(e){return zb("sha256").update(e).digest("hex")}function lS(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var nd;function cne(e){nd=e}function uS(e=lS(),t=void 0){if(t===void 0&&nd?.projectRoot===e)return nd;let n=Vy(e),r=Fy(e,n),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:e,config:n,paths:r,dbPath:i,dbPathSource:"env",gitContext:t};if(rd(r.dbPath))return{projectRoot:e,config:n,paths:r,dbPath:r.dbPath,dbPathSource:"configured",gitContext:t};let o=t0(e,"index.db");return{projectRoot:e,config:n,paths:r,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:o0(o,r.dbPath),gitContext:t}}function lne(e){return uS(e).dbPath}function une(e,t,n,r={}){return rd(n.dbPath)&&iS(e,n.cacheDir,void 0,r.gitContext)?{kind:"local-fresh"}:r.gitContext?.clean===!1&&r.watcherGeneration!==void 0&&Xs(n.dbPath)===r.watcherGeneration?Qu(e,t,n,r.gitContext):sb(e,t,n).state==="fresh"?Qu(e,t,n,r.gitContext):rS(e,t,n,r.gitContext)}function dne(e){return!e.startsWith("__")&&!n0.has(e)}var n0=new Set(["bench","config-validate","hook-context","hook-stop","init","setup","setup-agent","setup-ci","setup-hooks","uninstall","work-audit"]);function r0(){try{return i0(lS(),{warnOnRootFallback:!0})}catch(e){console.error(`error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}function i0(e,t={}){let{config:n,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:s,gitContext:a}=uS(e);if(!rd(i))throw new Error("No index.db found. Run: scip-query reindex");t.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:e,sharedEvidenceDbPath:tS(e,n,a),entryRoots:n.entryRoots,semantic:n.semantic,suppressions:n.suppressions,declaredCouplings:n.declaredCouplings,locality:n.locality,architecture:n.architecture,coverageContracts:n.coverageContracts,docs:n.docs},l=Ay(e);return new oa(c,l)}function o0(e,t){let n="unknown time";try{n=e0(e).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${e}, modified ${n}) because the configured index was not found at ${t}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}function en(e){let t=r0();try{return e(t)}finally{t.close()}}function mne(e,t){return t.concat([e])}function dS(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 fne(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 s0(e)}}function s0(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}function mS(e){return e+1}function a0(e,t){return`${mS(e)}-${mS(t)}`}function gne(e,t,n){return`${e}:${a0(t,n)}`}function hne(e,t=180){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var _t={empty(e){console.log(e)},list(e,t){for(let n of e)console.log(t(n))},groupedByFile(e,t,n=r=>r.relativePath){let r="";for(let i of e){let o=n(i);o!==r&&(r&&console.log(""),console.log(o),r=o),console.log(t(i))}},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 r of n.rows)console.log(r)}},table(e,t,n){console.log(` ${e.join(" ")}`);let r=n??e.map(i=>i.length);console.log(` ${r.map(i=>"\u2500".repeat(i)).join(" ")}`);for(let i of t)console.log(i)}};import{availableParallelism as WJ}from"os";import{fileURLToPath as Hm}from"url";import{existsSync as Ra,readFileSync as c0,readdirSync as pS}from"fs";import{join as oo}from"path";var l0={files:new Set,pathPrefixes:[]},id=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,u0=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,gS=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],d0=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),m0=4,f0=J("package-surface",{clearGroups:["whole-project"]});function p0(e){return f0.get(e,()=>g0(e.config.projectRoot))}function ir(e,t){let n=p0(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function g0(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of h0(e))for(let o of y0(r))b0(e,i,o,t,n);return t.size===0&&n.length===0?l0:{files:t,pathPrefixes:n}}function h0(e){let t=[],n=yS(e,"");return n&&t.push({manifest:n,packageRoot:""}),hS(e,"",t,0),t}function hS(e,t,n,r){if(r>=m0)return;let i=oo(e,t);if(Ra(i))for(let o of pS(i,{withFileTypes:!0})){if(!o.isDirectory()||d0.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=yS(e,s);a&&n.push({manifest:a,packageRoot:s}),hS(e,s,n,r+1)}}function yS(e,t){try{let n=c0(oo(e,t,"package.json"),"utf-8"),r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function y0(e){let t=[];for(let r of["main","module","types","browser"])typeof e[r]=="string"&&t.push(e[r]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let r of Object.values(n))typeof r=="string"&&t.push(r);return bS(e.exports,t),t}function bS(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))bS(n,t)}function b0(e,t,n,r,i){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 fS(c))l!==""&&i.push(tn(t,l));return}let a=o.replace(u0,"");for(let c of fS(a)){c===a&&c===o&&r.add(tn(t,o));for(let l of gS)S0(e,r,t,c+l)}r.add(tn(t,o))}function fS(e){let t=[e];return id.test(e)&&(t.push(e.replace(id,"src/")),t.push(e.replace(id,""))),t}function S0(e,t,n,r){let i=tn(n,r);if(t.add(i),!r.startsWith("src/")||Ra(oo(e,i)))return;let o=gS.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);C0(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 SS(e,n,c,`${l}${o}`))t.add(u)}function C0(e,t,n,r,i){let o=tn(n,`${r}/index${i}`);Ra(oo(e,o))&&t.add(o)}function SS(e,t,n,r){let i=oo(e,t,n);if(!Ra(i))return[];let o=[];for(let s of pS(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...SS(e,t,a,r)):s.isFile()&&s.name===r&&o.push(tn(t,a))}return o}function tn(e,t){return e?`${e}/${t}`:t}import{existsSync as va,readFileSync as x0,readdirSync as R0}from"fs";import{dirname as v0,join as Ia}from"path";var I0={rootFiles:new Set,sourcePrefixes:[]},w0=new Set([".git",".scipquery","node_modules","target"]),D0=6,E0=J("rust-library-surface",{clearGroups:["whole-project"]});function CS(e,t,n){if(!n.endsWith(".rs")||!T0(k0(e),n))return!1;let r=Q(e,n).find(i=>i.symbol===t);return r?_0(Ce(e,n)[r.startLine]??""):!1}function k0(e){return E0.get(e,()=>P0(e.config.projectRoot))}function P0(e){let t=new Set,n=new Set;for(let r of F0(e)){let i=Ia(e,r,"Cargo.toml"),o=x0(i,"utf8"),s=L0(o),a=tn(r,"src/lib.rs"),c=s?tn(r,s):!N0(o)&&va(Ia(e,a))?a:null;if(!c)continue;t.add(c);let l=v0(c).replaceAll("\\","/");n.add(l==="."?"":`${l}/`)}return t.size===0?I0:{rootFiles:t,sourcePrefixes:[...n].sort()}}function T0(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:A0(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function _0(e){return/^\s*pub\s+(?!\()/.test(e)}function F0(e){if(!va(e))return[];let t=[];return xS(e,"",t,0),t}function xS(e,t,n,r){let i=Ia(e,t);if(va(i)&&(va(Ia(i,"Cargo.toml"))&&n.push(t),!(r>=D0)))for(let o of R0(i,{withFileTypes:!0})){if(!o.isDirectory()||w0.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;xS(e,s,n,r+1)}}function L0(e){let t=!1;for(let n of e.split(`
|
|
376
|
-
`)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="lib";continue}if(!t)continue;let o=/^path\s*=\s*["']([^"']+)["']/.exec(r)?.[1];if(o)return o.replaceAll("\\","/").replace(/^\.\//,"")}return null}function
|
|
377
|
-
`)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="package";continue}if(t&&/^autolib\s*=\s*false\b/.test(r))return!0}return!1}function
|
|
367
|
+
`;function Iu(e,t,n){let r=iA(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function iA(e,t){if(!t||t===".")return null;if(!Ny(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=Ny(t)?t:ZN(e,t),r=QN(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readFileSync as oA,writeFileSync as wu,existsSync as Zt}from"fs";import{isAbsolute as Oy,join as Zn,relative as jy,resolve as By}from"path";var $r=".scipquery.json",Uy=250,Wy=0,Gy=10*6e4,sA={enabled:!1,debounceMs:Uy,cooldownMs:Wy,gitPollMs:2e3,idleTimeoutMs:Gy,autoRefresh:!0,ignore:[]},zy=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"],aA=new Set(["languages","indexerConcurrency","watch","hooks","indexer","dbPath","entryRoots","semantic","suppressions","declaredCouplings","locality","architecture","coverageContracts","docs"]),cA=new Set(["enabled","debounceMs","cooldownMs","gitPollMs","idleTimeoutMs","autoRefresh","ignore"]),lA=new Set(["router"]),uA=new Set(["pathPrefixes","files","symbolPatterns","qualifiedVars"]),dA=new Set(["typescript","rust"]),mA=new Set(["tsconfigs"]),fA=new Set(["rustAnalyzerPath"]),$y=new Set(zy),pA=new Set(["pnpmWorkspaces","projectMode","projects","configPath"]),gA=new Set(["architecturalBoundarySegments"]),hA=new Set(["boundaries","allowedDependencies","requireCompletePolicy","requireAcyclic"]),yA=new Set(["name","paths"]),bA=new Set(["snapshotPaths"]),SA=new Set(["name","files","reason"]),CA=new Set(["id","check","file","reason","expiresAt","createdAt"]),xA=new Set(["name","file","keys","mustEqual","allowExtra"]),RA=new Set(["type","identifier","marker"]),vA=new Set(["type","path","pattern"]),IA=new Set(["object-literal-keys","string-array","markdown-list"]),wA=new Set(["top-level-dirs","file-glob","registered-commands","builtin-skills"]);function Vy(e){let t=Zn(e,$r);if(!Zt(t))return{};try{let n=oA(t,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);throw n instanceof SyntaxError?new Error(`invalid ${$r} at ${t}: ${r}`,{cause:n}):new Error(`unable to read ${$r} at ${t}: ${r}`,{cause:n})}}function Cee(e,t={}){let n=[];TA(e,n);let r=new Set(zy);for(let[c,l]of(e.languages??[]).entries())r.has(l)||n.push({level:"error",path:`languages[${c}]`,message:`Unsupported language: ${l}`});e.indexerConcurrency!==void 0&&(!Number.isInteger(e.indexerConcurrency)||e.indexerConcurrency<=0)&&n.push({level:"error",path:"indexerConcurrency",message:"Must be a positive integer."}),e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&n.push({level:"error",path:"watch.debounceMs",message:"Must be greater than 0."}),e.watch?.cooldownMs!==void 0&&(!Number.isInteger(e.watch.cooldownMs)||e.watch.cooldownMs<0)&&n.push({level:"error",path:"watch.cooldownMs",message:"Must be a non-negative integer; 0 disables cooldown spacing."}),e.watch?.gitPollMs!==void 0&&e.watch.gitPollMs<=0&&n.push({level:"error",path:"watch.gitPollMs",message:"Must be greater than 0."}),e.watch?.idleTimeoutMs!==void 0&&(!Number.isInteger(e.watch.idleTimeoutMs)||e.watch.idleTimeoutMs<0)&&n.push({level:"error",path:"watch.idleTimeoutMs",message:"Must be a non-negative integer; 0 disables idle shutdown."}),e.watch?.autoRefresh!==void 0&&typeof e.watch.autoRefresh!="boolean"&&n.push({level:"error",path:"watch.autoRefresh",message:"Must be a boolean."}),e.hooks?.router!==void 0&&e.hooks.router!=="off"&&e.hooks.router!=="single"&&n.push({level:"error",path:"hooks.router",message:'Must be "off" or "single".'});let i=e.indexer?.typescript;if(i?.projectMode!==void 0&&i.projectMode!=="single"&&i.projectMode!=="workspace"&&n.push({level:"error",path:"indexer.typescript.projectMode",message:'Must be "single" or "workspace".'}),i?.projects!==void 0)if(!Array.isArray(i.projects))n.push({level:"error",path:"indexer.typescript.projects",message:"Must be an array."});else for(let[c,l]of i.projects.entries()){let u=`indexer.typescript.projects[${c}]`;if(typeof l!="string"||l.trim()==="")n.push({level:"error",path:u,message:"Project path must be a non-empty string."});else if(t.projectRoot){let d=By(t.projectRoot,l),m=jy(t.projectRoot,d);m.startsWith("..")||Oy(m)?n.push({level:"error",path:u,message:"Project path must stay inside the project root."}):Zt(d)||n.push({level:"warning",path:u,message:`TypeScript project path does not exist: ${l}`})}}i?.projectMode==="workspace"&&i.pnpmWorkspaces===!0&&n.push({level:"warning",path:"indexer.typescript.pnpmWorkspaces",message:'Ignored when projectMode is "workspace"; explicit TypeScript projects are indexed directly.'});let o=e.semantic?.rust;o?.rustAnalyzerPath!==void 0&&(typeof o.rustAnalyzerPath!="string"||o.rustAnalyzerPath.trim()==="")&&n.push({level:"error",path:"semantic.rust.rustAnalyzerPath",message:"Rust analyzer path must be a non-empty string."});let s=e.indexer?.clojure;if(s?.configPath!==void 0){let c="indexer.clojure.configPath";if(typeof s.configPath!="string"||s.configPath.trim()==="")n.push({level:"error",path:c,message:"Config path must be a non-empty string."});else if(t.projectRoot){let l=By(t.projectRoot,s.configPath),u=jy(t.projectRoot,l);u.startsWith("..")||Oy(u)?n.push({level:"error",path:c,message:"Config path must stay inside the project root."}):Zt(l)||n.push({level:"warning",path:c,message:`Clojure indexer config path does not exist: ${s.configPath}`})}}if(e.locality!==void 0)if(!et(e.locality))n.push({level:"error",path:"locality",message:"Must be an object."});else{let c=e.locality.architecturalBoundarySegments;if(c!==void 0)if(!Array.isArray(c))n.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});else for(let[l,u]of c.entries()){let d=`locality.architecturalBoundarySegments[${l}]`;typeof u!="string"||u.trim()===""?n.push({level:"error",path:d,message:"Boundary segment must be a non-empty string."}):(u.includes("/")||u.includes("\\"))&&n.push({level:"error",path:d,message:"Boundary segment must be a single folder name, not a path."})}}if(DA(e,n),e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings))n.push({level:"error",path:"declaredCouplings",message:"Must be an array."});else for(let[c,l]of(e.declaredCouplings??[]).entries()){let u=`declaredCouplings[${c}]`;if((!l.name||l.name.trim()==="")&&n.push({level:"error",path:`${u}.name`,message:"Declared coupling name is required."}),!Array.isArray(l.files)||l.files.length<2)n.push({level:"error",path:`${u}.files`,message:"Declared coupling needs at least two files."});else for(let[d,m]of l.files.entries())!m||m.trim()===""?n.push({level:"error",path:`${u}.files[${d}]`,message:"Declared coupling file path is required."}):t.projectRoot&&!Zt(Zn(t.projectRoot,m))&&n.push({level:"warning",path:`${u}.files[${d}]`,message:`Declared coupling file does not exist: ${m}`});l.reason!==void 0&&l.reason.trim()===""&&n.push({level:"error",path:`${u}.reason`,message:"Declared coupling reason cannot be blank."})}let a=t.now??new Date;e.suppressions!==void 0&&!Array.isArray(e.suppressions)&&n.push({level:"error",path:"suppressions",message:"Must be an array."});for(let[c,l]of(Array.isArray(e.suppressions)?e.suppressions:[]).entries()){let u=`suppressions[${c}]`;if(!et(l)){n.push({level:"error",path:u,message:"Suppression must be an object."});continue}if((!l.reason||l.reason.trim()==="")&&n.push({level:"error",path:`${u}.reason`,message:"Suppression reason is required."}),l.id!==void 0&&l.id.trim()===""&&n.push({level:"error",path:`${u}.id`,message:"Suppression id cannot be blank."}),l.check!==void 0&&l.check.trim()===""&&n.push({level:"error",path:`${u}.check`,message:"Suppression check cannot be blank."}),!l.id&&(!l.check||!l.file)?n.push({level:"error",path:u,message:"Suppression must include id or both check and file."}):!l.id&&l.check&&l.file&&n.push({level:"warning",path:u,message:"Check+file suppressions waive every matching finding in that file; prefer a stable id when available."}),l.file!==void 0&&(l.file.trim()===""?n.push({level:"error",path:`${u}.file`,message:"Suppression file path cannot be blank."}):t.projectRoot&&!Zt(Zn(t.projectRoot,l.file))&&n.push({level:"warning",path:`${u}.file`,message:`Suppression file does not exist: ${l.file}`})),l.expiresAt){let d=Date.parse(l.expiresAt);Number.isNaN(d)?n.push({level:"error",path:`${u}.expiresAt`,message:"Must be an ISO date string."}):d<=a.getTime()&&n.push({level:"warning",path:`${u}.expiresAt`,message:"Suppression has expired."})}}return PA(e,n,t),kA(e,n),n}function DA(e,t){if(e.architecture===void 0)return;if(!et(e.architecture)){t.push({level:"error",path:"architecture",message:"Must be an object."});return}let n=e.architecture.boundaries;if(!Array.isArray(n)||n.length===0){t.push({level:"error",path:"architecture.boundaries",message:"Must be a non-empty array."});return}let r=new Set,i=new Set;for(let[s,a]of n.entries()){let c=`architecture.boundaries[${s}]`;if(!et(a)){t.push({level:"error",path:c,message:"Architecture boundary must be an object."});continue}let l=a.name;typeof l!="string"||l.trim()===""?t.push({level:"error",path:`${c}.name`,message:"Boundary name is required."}):r.has(l)?t.push({level:"error",path:`${c}.name`,message:`Duplicate boundary name: ${l}`}):r.add(l);let u=a.paths;if(!Array.isArray(u)||u.length===0){t.push({level:"error",path:`${c}.paths`,message:"Boundary paths must be a non-empty array."});continue}for(let[d,m]of u.entries()){let f=`${c}.paths[${d}]`;if(typeof m!="string"||m.trim()===""){t.push({level:"error",path:f,message:"Boundary path must be a non-empty string."});continue}EA(m)||t.push({level:"error",path:f,message:"Boundary path must be project-relative and may use only one trailing /* or /** glob."}),i.has(m)?t.push({level:"error",path:f,message:`Duplicate boundary path: ${m}`}):i.add(m)}}let o=e.architecture.allowedDependencies;if(o!==void 0&&!et(o))t.push({level:"error",path:"architecture.allowedDependencies",message:"Must be an object keyed by boundary name."});else if(et(o))for(let[s,a]of Object.entries(o)){let c=`architecture.allowedDependencies.${s}`;if(r.has(s)||t.push({level:"error",path:c,message:`Unknown source boundary: ${s}`}),!Array.isArray(a)){t.push({level:"error",path:c,message:"Dependency row must be an array."});continue}let l=new Set;for(let[u,d]of a.entries()){let m=`${c}[${u}]`;typeof d!="string"||d.trim()===""?t.push({level:"error",path:m,message:"Target boundary name is required."}):r.has(d)?l.has(d)?t.push({level:"error",path:m,message:`Duplicate target boundary: ${d}`}):l.add(d):t.push({level:"error",path:m,message:`Unknown target boundary: ${d}`})}}if(e.architecture.requireAcyclic!==void 0&&typeof e.architecture.requireAcyclic!="boolean"&&t.push({level:"error",path:"architecture.requireAcyclic",message:"Must be a boolean."}),e.architecture.requireCompletePolicy!==void 0&&typeof e.architecture.requireCompletePolicy!="boolean")t.push({level:"error",path:"architecture.requireCompletePolicy",message:"Must be a boolean."});else if(e.architecture.requireCompletePolicy===!0){let s=et(o)?o:{};for(let a of[...r].sort())Object.hasOwn(s,a)||t.push({level:"error",path:`architecture.allowedDependencies.${a}`,message:"A dependency row is required by architecture.requireCompletePolicy."})}}function EA(e){let t=e.replace(/\\/g,"/");if(t.startsWith("/")||t==="."||t===".."||t.split("/").includes(".."))return!1;let n=t.replace(/\/\*\*?$/,"");return n.length>0&&!/[*?[\]]/.test(n)}function kA(e,t){let n=e.docs?.snapshotPaths;if(n!==void 0){if(!Array.isArray(n)){t.push({level:"error",path:"docs.snapshotPaths",message:"Must be an array."});return}for(let[r,i]of n.entries())(typeof i!="string"||i.trim()==="")&&t.push({level:"error",path:`docs.snapshotPaths[${r}]`,message:"Snapshot path glob must be a non-empty string."})}}function PA(e,t,n){if(e.coverageContracts!==void 0){if(!Array.isArray(e.coverageContracts)){t.push({level:"error",path:"coverageContracts",message:"Must be an array."});return}for(let[r,i]of e.coverageContracts.entries()){let o=`coverageContracts[${r}]`;if(!et(i)){t.push({level:"error",path:o,message:"Coverage contract must be an object."});continue}(typeof i.name!="string"||i.name.trim()==="")&&t.push({level:"error",path:`${o}.name`,message:"Coverage contract name is required."}),typeof i.file!="string"||i.file.trim()===""?t.push({level:"error",path:`${o}.file`,message:"Coverage contract file is required."}):n.projectRoot&&!Zt(Zn(n.projectRoot,i.file))&&t.push({level:"warning",path:`${o}.file`,message:`Coverage contract file does not exist: ${i.file}`}),Hy(t,i.keys,`${o}.keys`,IA,"Unknown coverage-contract key extractor type."),Hy(t,i.mustEqual,`${o}.mustEqual`,wA,"Unknown coverage-contract ground-truth source type."),i.allowExtra!==void 0&&typeof i.allowExtra!="boolean"&&t.push({level:"error",path:`${o}.allowExtra`,message:"Must be a boolean."})}}}function Hy(e,t,n,r,i){if(!et(t)){e.push({level:"error",path:n,message:'Must be an object with a "type" field.'});return}if(typeof t.type!="string"||!r.has(t.type)){e.push({level:"error",path:`${n}.type`,message:`${i} Got: ${String(t.type)}`});return}let o={"object-literal-keys":["identifier"],"string-array":["identifier"],"markdown-list":["marker"],"top-level-dirs":["path"],"file-glob":["pattern"],"registered-commands":[],"builtin-skills":[]};for(let s of o[t.type]??[])(typeof t[s]!="string"||t[s].length===0)&&e.push({level:"error",path:`${n}.${s}`,message:`"${t.type}" requires a non-empty string "${s}".`})}function xee(e){return{...sA,...e.watch}}function Ree(e,t){let n=Zn(e,$r);return Zt(n)||wu(n,JSON.stringify({languages:t,watch:{enabled:!0,debounceMs:Uy,cooldownMs:Wy,gitPollMs:2e3,idleTimeoutMs:Gy,autoRefresh:!0}},null,2)+`
|
|
368
|
+
`),n}function vee(e,t,n){let r=Zn(e,$r),i={...t,languages:[...n]},o=!Zt(r)||JSON.stringify(i)!==JSON.stringify(t);return o&&wu(r,JSON.stringify(i,null,2)+`
|
|
369
|
+
`),{configPath:r,config:i,changed:o}}function Iee(e,t,n){let r=Zn(e,$r),i={...t,watch:{...t.watch,enabled:n,...n&&t.watch?.autoRefresh===void 0?{autoRefresh:!0}:{}}},o=!Zt(r)||JSON.stringify(i)!==JSON.stringify(t);return o&&wu(r,JSON.stringify(i,null,2)+`
|
|
370
|
+
`),{configPath:r,config:i,changed:o}}function TA(e,t){if(!et(e))return;let n=e;if(Re(t,n,"",aA),Re(t,n.watch,"watch",cA),Re(t,n.hooks,"hooks",lA),Re(t,n.entryRoots,"entryRoots",uA),Re(t,n.semantic,"semantic",dA),Re(t,n.semantic?.typescript,"semantic.typescript",mA),Re(t,n.semantic?.rust,"semantic.rust",fA),Re(t,n.locality,"locality",gA),Re(t,n.architecture,"architecture",hA),Re(t,n.docs,"docs",bA),Array.isArray(n.architecture?.boundaries))for(let[r,i]of n.architecture.boundaries.entries())Re(t,i,`architecture.boundaries[${r}]`,yA);if(et(n.indexer)){Re(t,n.indexer,"indexer",$y);for(let[r,i]of Object.entries(n.indexer))$y.has(r)&&Re(t,i,`indexer.${r}`,pA)}if(Array.isArray(n.declaredCouplings))for(let[r,i]of n.declaredCouplings.entries())Re(t,i,`declaredCouplings[${r}]`,SA);if(Array.isArray(n.suppressions))for(let[r,i]of n.suppressions.entries())Re(t,i,`suppressions[${r}]`,CA);if(Array.isArray(n.coverageContracts))for(let[r,i]of n.coverageContracts.entries()){let o=`coverageContracts[${r}]`;Re(t,i,o,xA),et(i)&&(Re(t,i.keys,`${o}.keys`,RA),Re(t,i.mustEqual,`${o}.mustEqual`,vA))}}function Re(e,t,n,r){if(et(t))for(let i of Object.keys(t))r.has(i)||e.push({level:"warning",path:n?`${n}.${i}`:i,message:"Unknown config key."})}function et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as ob,readFileSync as JA}from"fs";import{execFileSync as _A}from"child_process";import{existsSync as FA,readdirSync as Ky}from"fs";import{extname as Jy,join as Yy}from"path";var Xy=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),LA=[{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:"clojure",files:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],extensions:[".clj",".cljs",".cljc"]},{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 zi(e){let t=[],n=NA(e),r=jA(e);for(let i of LA){if(AA(e,i.files)){t.push(i.language);continue}if(MA(n,i.globs)){t.push(i.language);continue}$A(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&qy(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&qy(t,"c"),t}function NA(e){try{return Ky(e)}catch{return[]}}function AA(e,t){return t?.length?t.some(n=>FA(Yy(e,n))):!1}function MA(e,t){return t?.length?e.some(n=>t.some(r=>OA(n,r))):!1}function OA(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function jA(e){let t=BA(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o;try{o=Ky(i,{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=Yy(i,s.name);if(s.isDirectory()){Xy.has(s.name)||r.push(a);continue}let c=Jy(s.name).toLowerCase();c&&n.add(c)}}return n}function BA(e){try{let t=_A("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let r of t.split(`
|
|
371
|
+
`)){if(!r||r.split("/").some(o=>Xy.has(o)))continue;let i=Jy(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function $A(e,t){return t?.length?t.some(n=>e.has(n)):!1}function qy(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{createHash as HA}from"crypto";import{copyFileSync as Qy,existsSync as Dn,linkSync as UA,mkdirSync as Zy,readFileSync as nb,readdirSync as eb,renameSync as Eu,rmSync as ca,statSync as WA}from"fs";import{basename as aa,dirname as Vi,join as Ge,relative as tb}from"path";var Hr=1,la=".scipquery-generations";function rb(e){let t=ua(e.outputDb),n=GA(e,t);e.onStage?.("after-recovery-retained"),e.preserveOutputScip||Du(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),Du(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),Du(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let r=da(e.metaPath,e.outputDb),i={version:Hr,currentGeneration:r,...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:(e.now??(()=>new Date))().toISOString()};return _e(Ge(t,"state.json"),i,{spacing:2,trailingNewline:!0}),{currentGeneration:r,...n?{previousGeneration:n}:{}}}function ib(e){try{let t=JSON.parse(nb(Ge(ua(e),"state.json"),"utf8"));return t.version!==Hr||typeof t.currentGeneration!="string"||!t.currentGeneration||typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt))||!qA(t.previousGeneration)||!KA(t.publication)?null:t}catch{return null}}function Nee(e,t,n=()=>new Date){if(!Dn(e)||!Dn(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=ib(e),i={version:Hr,currentGeneration:da(t,e),...r?.previousGeneration?{previousGeneration:r.previousGeneration}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return _e(Ge(ua(e),"state.json"),i,{spacing:2,trailingNewline:!0}),i}function qi(e,t=Ge(Vi(e),"meta.json")){let n=Ge(ua(e),"state.json");if(!Dn(n))return{state:"legacy",statePath:n};let r=ib(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=da(t,e),o=r.currentGeneration===i,s=r.previousGeneration?Dn(Ge(Vi(e),r.previousGeneration.databasePath)):!0;return!o||!s?{state:"drifted",statePath:n,currentMatches:o,recoveryExists:s,generation:r,reason:o?"retained recovery database is missing":"stable database or metadata no longer matches the published generation"}:{state:"current",statePath:n,currentMatches:o,recoveryExists:s,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function ua(e){return Ge(Vi(e),la)}function GA(e,t){if(!Dn(e.outputDb))return;let n=da(e.metaPath,e.outputDb),r=Ge(t,n),i=Ge(r,aa(e.outputDb)),o=Dn(e.metaPath)?Ge(r,aa(e.metaPath)):void 0;if(!Dn(i)){let s=`${r}.${process.pid}.${Date.now()}.tmp`;ca(s,{recursive:!0,force:!0}),Zy(s,{recursive:!0});let a=Ge(s,aa(e.outputDb));try{UA(e.outputDb,a)}catch{Qy(e.outputDb,a)}o&&Qy(e.metaPath,Ge(s,aa(e.metaPath))),Zy(t,{recursive:!0}),Eu(s,r)}return zA(t,n),{generationIdentity:n,databasePath:tb(Vi(e.outputDb),i),...o?{metadataPath:tb(Vi(e.outputDb),o)}:{}}}function zA(e,t){for(let n of eb(e,{withFileTypes:!0}))!n.isDirectory()||n.name===t||n.name.endsWith(".tmp")||ca(Ge(e,n.name),{recursive:!0,force:!0});for(let n of eb(e,{withFileTypes:!0}))n.isDirectory()&&n.name.endsWith(".tmp")&&ca(Ge(e,n.name),{recursive:!0,force:!0})}function da(e,t){let n=HA("sha256").update(`sqlite-generation-v${Hr}\0`);Dn(e)&&n.update(VA(nb(e,"utf8")));let r=WA(t);return n.update(`\0${r.size}`),n.digest("hex")}function VA(e){try{let t=JSON.parse(e);if((t.version===2||t.version===3)&&t.status==="complete"&&typeof t.updatedAt=="string"&&t.fingerprint!==void 0)return JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages,scipCompanion:t.scipCompanion})}catch{}return e}function Du(e,t){ca(`${t}.tmp-replace`,{force:!0}),Eu(e,`${t}.tmp-replace`),Eu(`${t}.tmp-replace`,t)}function qA(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e;return typeof t.generationIdentity=="string"&&!!t.generationIdentity&&typeof t.databasePath=="string"&&!!t.databasePath&&(t.metadataPath===void 0||typeof t.metadataPath=="string"&&!!t.metadataPath)}function KA(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e,n=[t.converterDurationMs,t.affectedDocumentCount,t.changedDocumentCount,t.producerDurationMs,t.materializationDurationMs,t.patchDurationMs].filter(r=>r!==void 0);return(t.mode==="incremental"||t.mode==="full")&&t.validation==="passed"&&t.converterDurationMs!==void 0&&n.every(r=>typeof r=="number"&&Number.isFinite(r)&&r>=0)&&(t.scipCompanion===void 0||t.scipCompanion==="current"||t.scipCompanion==="deferred")&&(t.typescriptOverlayGeneration===void 0||typeof t.typescriptOverlayGeneration=="string"&&!!t.typescriptOverlayGeneration)&&(t.scipCompanion!=="deferred"||!!t.typescriptOverlayGeneration)&&(t.fallbackReason===void 0||typeof t.fallbackReason=="string")}function sb(e,t,n){let r=new Date().toISOString();if(!ob(n.dbPath))return{state:"missing",checkedAt:r,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!ob(n.metaPath))return{state:"unknown",checkedAt:r,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=JSON.parse(JA(n.metaPath,"utf-8")),o=t.languages??zi(e),s=YA(e,o,t),a=Array.isArray(i.indexedLanguages)?[...i.indexedLanguages].sort():[],c=(i.version===2||i.version===3)&&i.status==="complete"&&JSON.stringify(i.fingerprint)===JSON.stringify(s)&&JSON.stringify(a)===JSON.stringify(s.languages),l=qi(n.dbPath,n.metaPath),u=l.state==="invalid"||l.state==="drifted",d=c&&!u;return{state:d?"fresh":"stale",checkedAt:r,metaPath:n.metaPath,updatedAt:i.updatedAt,lastRefresh:i.lastRefresh,reason:u?`SQLite generation requires repair: ${l.reason}`:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:d?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:r,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function YA(e,t,n){return Pi(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath})}import{createHash as zb,randomUUID as Ju}from"crypto";import{closeSync as Vb,constants as BM,copyFileSync as Hb,existsSync as kn,lstatSync as $M,mkdirSync as en,mkdtempSync as qb,openSync as Kb,readdirSync as HM,readFileSync as tt,realpathSync as UM,renameSync as nr,rmSync as En,statSync as WM,unlinkSync as zu,writeFileSync as Jb}from"fs";import{dirname as Yb,join as A,resolve as Ct}from"path";import{setTimeout as GM}from"timers/promises";import{pathToFileURL as Ub}from"url";import{deserializeSCIP as Xb}from"@c4312/scip";import zM from"better-sqlite3";import{randomUUID as ab}from"crypto";import{closeSync as cb,mkdirSync as XA,openSync as lb,readFileSync as ub,unlinkSync as db,writeFileSync as mb}from"fs";import{dirname as QA,join as ZA}from"path";function ku(e,t={}){return Pu(ZA(e,"gc.lock"),t)}function Pu(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??Date.now,o=Date.now()+n;XA(QA(e),{recursive:!0});do{let s=ab();try{let a=lb(e,"wx");try{let c={version:1,pid:process.pid,token:s,startedAt:new Date(i()).toISOString()};mb(a,`${JSON.stringify(c)}
|
|
372
|
+
`)}finally{cb(a)}return{release:()=>pb(e,s)}}catch(a){if(a.code!=="EEXIST")return null;let c=fb(e);if(c&&(c.pid===void 0||!dt(c.pid))){eM(e,c);continue}if(Date.now()>=o)return null;tM(Math.min(r,Math.max(1,o-Date.now())))}}while(Date.now()<=o);return null}function fb(e){try{let t=ub(e,"utf8"),n=JSON.parse(t),r=typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0?n.pid:void 0;return{raw:t,...r===void 0?{}:{pid:r}}}catch{return null}}function eM(e,t){let n=`${e}.reclaim`,r=ab(),i;try{i=lb(n,"wx")}catch{return!1}try{mb(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
|
|
373
|
+
`)}finally{cb(i)}try{let o=fb(e);return!o||o.raw!==t.raw||o.pid!==void 0&&dt(o.pid)?!1:(db(e),!0)}catch{return!1}finally{pb(n,r)}}function pb(e,t){try{let n=JSON.parse(ub(e,"utf8"));n.pid===process.pid&&n.token===t&&db(e)}catch{}}function tM(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}import{lstatSync as hM,readdirSync as yM}from"fs";import{join as bM,relative as SM,resolve as ju,sep as CM}from"path";import{createHash as nM}from"crypto";import{existsSync as _u,mkdirSync as rM,readFileSync as ma,readdirSync as Kee,renameSync as iM,rmSync as Jee,writeFileSync as oM}from"fs";import{join as Ur}from"path";import{create as hb,fromBinary as yb,toBinary as sM}from"@bufbuild/protobuf";import{deserializeSCIP as fa,DocumentSchema as Fu,IndexSchema as bb,serializeSCIP as Sb}from"@c4312/scip";var pa=1,Ki="typescript-scip-fragments";function ete(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let o of e){let s=er(o.relativePath);if(t.has(s))throw new Error(`duplicate TypeScript fragment replacement: ${s}`);if(t.add(s),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${s}`);let a=yb(Fu,o.bytes);if(a.relativePath!==s)throw new Error(`TypeScript fragment path mismatch: expected ${s}, got ${a.relativePath}`);n.push(a)}let r=Sb(hb(bb,{documents:n,externalSymbols:[]})),i=fa(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function ga(e){let t=Ur(e,Ki);return{rootDir:t,blobDir:Ur(t,"blobs"),generationDir:Ur(t,"generations")}}function aM(e){let t=fa(e.indexBytes);kb(t.metadata,Pb(e)),Eb(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let s=er(o.relativePath);if(n.has(s))throw new Error(`duplicate TypeScript SCIP document path: ${s}`);n.add(s);let a=sM(Fu,o),c=e.documentIdentities.get(s)??(e.allowUntrackedDocuments?tr(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:s,contentHash:tr(a)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${s}`);r.push(vb(e.cacheDir,{relativePath:s,bytes:a,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=Ib(e,r);return wb(e.cacheDir,i),i}function tte(e){let t=ga(e.cacheDir);if(!_u(Lu(t,e.generationIdentity)))return aM(e);let n=Cb({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&n.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let r of n.manifest.documents){let i=e.documentIdentities.get(r.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==r.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${r.relativePath}`)}return n.manifest}function nte(e){let t=Cb({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let s=er(o.relativePath);if(r.has(s))throw new Error(`duplicate TypeScript fragment replacement: ${s}`);if(r.add(s),!n.has(s))throw new Error(`TypeScript fragment replacement has no prior document: ${s}`);let a=e.documentIdentities.get(s);if(!a)throw new Error(`missing TypeScript document identity: ${s}`);o.bytes===null?n.delete(s):n.set(s,vb(e.cacheDir,o,a))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Ib(e,[...n.values()]);return wb(e.cacheDir,i),i}function Cb(e){let t=ga(e.cacheDir),n=Lu(t,e.generationIdentity),r;try{r=Db(ma(n,"utf8"))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of r.documents){let s=Ur(t.blobDir,`${o.blobHash}.scipdoc`),a=ma(s);if(a.byteLength!==o.byteLength||tr(a)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,a)}return{manifest:r,fragments:i}}function xb(e){let t=Rb(e);return Tu(t.baseIndex,t.completeDocuments,"assembled")}function rte(e){let t=Rb(e);return cM(t.deletedAffectedPaths),{completeIndexBytes:Tu(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:Tu(t.baseIndex,t.affectedDocuments,"affected")}}function Rb(e){let t=fa(e.baseIndexBytes);kb(t.metadata,Pb(e)),Eb(t.externalSymbols);let n=new Map;for(let a of e.fragments){let c=er(a.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,a)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],o=[],s=[];for(let a of t.documents){let c=er(a.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let l=n.get(c);if(!l){i.push(a);continue}if(n.delete(c),l.bytes===null){s.push(c);continue}let u=yb(Fu,l.bytes);if(u.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${u.relativePath}`);i.push(u),o.push(u)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:s}}function Tu(e,t,n){let r=Sb(hb(bb,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=fa(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function cM(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function vb(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=er(t.relativePath),i=Buffer.from(t.bytes),o=tr(i),s=ga(e);rM(s.blobDir,{recursive:!0});let a=Ur(s.blobDir,`${o}.scipdoc`);if(_u(a)){let c=ma(a);if(c.byteLength!==i.byteLength||tr(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${a}.${process.pid}.${Date.now()}.tmp`;oM(c,i),iM(c,a)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function Ib(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let n=[...t].sort((r,i)=>r.relativePath.localeCompare(i.relativePath));if(new Set(n.map(r=>r.relativePath)).size!==n.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:pa,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function wb(e,t){let n=ga(e),r=Lu(n,t.generationIdentity);if(_u(r)){let i=Db(ma(r,"utf8"));if(gb(i)!==gb(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}_e(r,t,{spacing:2,trailingNewline:!0})}function gb(e){return tr(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Db(e){let t=JSON.parse(e);if(t.version!==pa||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(er(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function Lu(e,t){return Ur(e.generationDir,lM(t))}function lM(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${tr(e)}.json`}function Eb(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function kb(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let n=e,r=n.toolInfo??n.tool_info;if(!r||typeof r!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=r;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function Pb(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function er(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}function tr(e){return nM("sha256").update(e).digest("hex")}import{createHash as uM}from"crypto";import{existsSync as Ji,mkdirSync as dM,readFileSync as Xi,readdirSync as Nu,renameSync as mM,rmSync as Tb,writeFileSync as fM}from"fs";import{join as St}from"path";var ha=1,ute=64*1024*1024,Qi="typescript-scip-overlays";function dte(e){let t=Fb(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let n=new Map((t?.overlays??[]).map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let s=Ou(o.relativePath);if(r.has(s))throw new Error(`duplicate TypeScript overlay: ${s}`);r.add(s),n.set(s,pM(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:ha,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((o,s)=>o.relativePath.localeCompare(s.relativePath))};return gM(e.cacheDir,i),i}function mte(e){let t=Fb(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let n=t.overlays.map(r=>{if(r.blobHash===null)return{relativePath:r.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=Xi(St(Zi(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||Yi(i)!==r.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${r.relativePath}`);return{relativePath:r.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return xb({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function fte(e,t){let n=Zi(e),r=St(n,"generations");if(!Ji(r))return;let i=new Set(t.map(Mu)),o=new Set;for(let a of Nu(r).filter(c=>i.has(c))){let c=Au(Xi(St(r,a),"utf8"));for(let l of c.overlays)l.blobHash&&o.add(`${l.blobHash}.scipdoc`)}for(let a of Nu(r))i.has(a)||Tb(St(r,a),{force:!0});let s=St(n,"blobs");if(Ji(s))for(let a of Nu(s))o.has(a)||Tb(St(s,a),{force:!0})}function Fb(e,t){let n=St(Zi(e),"generations",Mu(t));if(!Ji(n))return null;let r=Au(Xi(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function pM(e,t){let n=Ou(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=Yi(r),o=St(Zi(e),"blobs");dM(o,{recursive:!0});let s=St(o,`${i}.scipdoc`);if(Ji(s)){let a=Xi(s);if(a.byteLength!==r.byteLength||Yi(a)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let a=`${s}.${process.pid}.${Date.now()}.tmp`;fM(a,r),mM(a,s)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function gM(e,t){let n=St(Zi(e),"generations",Mu(t.generationIdentity));if(Ji(n)){let r=Au(Xi(n,"utf8"));if(_b(r)!==_b(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}_e(n,t,{spacing:2,trailingNewline:!0})}function Au(e){let t=JSON.parse(e);if(t.version!==ha||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let n=new Set;for(let r of t.overlays){if(!r||typeof r.relativePath!="string"||r.blobHash!==null&&(typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash))||!Number.isInteger(r.byteLength)||r.byteLength<0||r.blobHash===null&&r.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(Ou(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function Zi(e){return St(e,Qi)}function Mu(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${Yi(e)}.json`}function _b(e){return Yi(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Ou(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function Yi(e){return uM("sha256").update(e).digest("hex")}var eo=1,Bu="language-indexes",Lb=["index.db","index.scip","meta.json"],Nb=[Bu,Ki,Qi];function ya(e){let t=[];for(let n of Lb)xM(e,n),t.push(n);for(let n of Nb)Ab(e,n,t);return{version:eo,files:t.sort()}}function ba(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."))throw new Error(`invalid index artifact path: ${e}`);let n=t[0];if(!Lb.includes(e)&&!Nb.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function _t(e,t){let n=ba(t),r=ju(e),i=ju(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${CM}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function Ab(e,t,n){let r=bM(e,t),i;try{i=yM(r,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let s=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${s}`);o.isDirectory()?Ab(e,s,n):o.isFile()&&n.push(ba(s))}}function xM(e,t){let n=_t(e,t),r;try{r=hM(n)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!r.isFile()||r.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(SM(ju(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{readFileSync as Hu,writeFileSync as Uu}from"fs";import{create as to}from"@bufbuild/protobuf";import{deserializeSCIP as Wu,serializeSCIP as Gu,DocumentSchema as PM,IndexSchema as Ob,MetadataSchema as TM,SymbolInformationSchema as _M}from"@c4312/scip";import{readFileSync as RM,writeFileSync as vM}from"fs";import{create as Mb}from"@bufbuild/protobuf";import{deserializeSCIP as IM,DocumentSchema as wM,IndexSchema as DM,serializeSCIP as EM,SymbolRole as kM}from"@c4312/scip";function vte(e){let t;try{t=IM(RM(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=$u(t);return n.removedDefinitionOccurrences>0&&vM(e,Buffer.from(EM(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function $u(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,r=0,i=[];for(let o of e.documents){let s=o.occurrences.filter(a=>(a.symbolRoles&kM.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(Mb(wM,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Mb(DM,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function jb(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=LM(e),n=NM(e.flatMap(i=>i.documents??[])),r=$b(e.flatMap(i=>i.externalSymbols??[]));return to(Ob,{metadata:t,documents:n,externalSymbols:r})}function Pte(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Wu(Hu(i))),r=jb(n);return Uu(t,Buffer.from(Gu(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function Tte(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Wu(Hu(i))),r=$u(jb(n));return Uu(t,Buffer.from(Gu(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function FM(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return to(Ob,{metadata:to(TM,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function Bb(e,t,n){let r=Wu(Hu(e)),i=FM(r,t,n);Uu(e,Buffer.from(Gu(i)))}function LM(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function NM(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,to(PM,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:AM([...r.occurrences,...n.occurrences]),symbols:$b([...r.symbols,...n.symbols]),text:OM(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function AM(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function $b(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,to(_M,{symbol:r.symbol,documentation:jM([...r.documentation,...n.documentation]),relationships:MM([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function MM(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function OM(e,t){return e?t?e.length>=t.length?e:t:e:t}function jM(e){return[...new Set(e)]}var Yu=1,Wb="SCIP_QUERY_SHARED_CACHE",Vu=JSON.stringify({cliVersion:Xn,artifactCatalogVersion:eo,sqliteGenerationStoreVersion:Hr,typescriptFragmentStoreVersion:pa,typescriptOverlayStoreVersion:ha}),Qb="manifest.json",Zb="shared-cache.json",Xu=[Bu,Ki,Qi];function Sa(e,t){if(!e.clean||!e.treeOid)return;let n=io(JSON.stringify({version:Yu,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Vu}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Vu,generationId:n,repositoryCacheDir:Gi(e.repositoryId)}}function eS(e,t,n){if(process.env[Wb]==="0")return`${Wb}=0`;if(!Ru(n))return"explicit cache or database override";if(Ct(t)!==Ct(A(ia(e),"index.db")))return"index database is outside the managed worktree cache"}function tS(e,t,n){if(!Ru(t))return;let r=n??gr(e);return r?A(Gi(r.repositoryId),"evidence.db"):void 0}function rr(e,t=!0){let n=ed(e),r;try{r=VM(tt(A(n,Qb),"utf8"))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||JSON.stringify(r.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return r;try{for(let i of r.artifacts){let o=_t(n,i.path),s=WM(o);if(!s.isFile()||s.size!==i.size||io(tt(o))!==i.sha256)return null}}catch{return null}return r}function nS(e){let t=rr(e.snapshot);if(t)return t;if(!Wr(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=Gb(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=ya(e.sourceCacheDir),i=A(e.snapshot.repositoryCacheDir,"generations");en(i,{recursive:!0});let o=qb(A(i,`.tmp-${process.pid}-`));try{let s=[];for(let d of r.files){let m=_t(e.sourceCacheDir,d),f=_t(o,d);ro(m,f);let p=tt(f);s.push({path:d,size:p.byteLength,sha256:io(p)})}let a=Xb(tt(A(o,"index.scip"))).metadata?.projectRoot;if(!a)throw new Error("shared SCIP generation has no project root metadata");let c=td(e.sourceProjectRoot);if(a!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(Gb(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let l={version:Yu,artifactCatalogVersion:eo,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:a,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:s.sort((d,m)=>d.path.localeCompare(m.path))};_e(A(o,Qb),l,{spacing:2,trailingNewline:!0});let u=ed(e.snapshot);try{if(kn(u)&&!rr(e.snapshot)){let d=`${u}.corrupt-${process.pid}-${Date.now()}`;nr(u,d),En(d,{recursive:!0,force:!0})}nr(o,u)}catch(d){let m=rr(e.snapshot);if(m)return m;throw d}return l}finally{En(o,{recursive:!0,force:!0})}}function qu(e){let t=ed(e.snapshot);en(e.targetCacheDir,{recursive:!0});let n=Pu(A(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=qb(A(e.targetCacheDir,".shared-hydrate-")),ZM(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let l=_t(t,c.path),u=_t(r,c.path);ro(l,u);let d=tt(u);if(d.byteLength!==c.size||io(d)!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let s=td(e.targetProjectRoot);if(s!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&Bb(_t(r,c.path),e.manifest.scipProjectRoot,s);if(!Wr(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=YM(e.targetCacheDir,r),o=!0,XM(r,e.targetCacheDir,i),rb({tempOutputScip:A(r,"index.scip"),tempOutputDb:A(r,"index.db"),tempMetaPath:A(r,"meta.json"),outputScip:A(e.targetCacheDir,"index.scip"),outputDb:A(e.targetCacheDir,"index.db"),metaPath:A(e.targetCacheDir,"meta.json"),now:e.now});let a=qi(A(e.targetCacheDir,"index.db"),A(e.targetCacheDir,"meta.json"));if(a.state==="invalid"||a.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${a.reason}`);Ku(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(s){throw o&&i&&QM(e.targetCacheDir,i),s}finally{r&&En(r,{recursive:!0,force:!0}),n.release()}}function rS(e,t,n,r){let i=eS(e,n.dbPath,t);if(i)return{kind:"bypassed",reason:i};try{let o=r??gr(e);if(!o)return{kind:"missed",reason:"Git worktree identity is unavailable"};if(!o.clean)return Ca(o,n.cacheDir,"missed",void 0,"worktree has uncommitted changes"),{kind:"missed",reason:"worktree has uncommitted changes"};let s=t.languages??zi(e),a=Pi(e,s,oS(t)),c=Sa(o,a);if(!c)return{kind:"missed",reason:"clean committed snapshot is unavailable"};let l=rr(c);if(l)return qu({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:c.generationId};let u=qM(c,e);return u?(l=u.manifest,qu({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e,action:"peer-imported"}),{kind:"peer-imported",generationId:c.generationId,sourceProjectRoot:u.sourceProjectRoot}):(Ca(o,n.cacheDir,"missed",void 0,"no exact shared or peer generation exists"),{kind:"missed",reason:"no exact shared or peer generation exists"})}catch(o){return{kind:"failed",reason:o instanceof Error?o.message:String(o)}}}function Qu(e,t,n,r){let i=eS(e,n.dbPath,t);if(i)return{kind:"bypassed",reason:i};try{let o=r??gr(e);if(!o)return{kind:"missed",reason:"Git worktree identity is unavailable"};if(!o.clean)return Ca(o,n.cacheDir,"missed",void 0,"worktree is not a clean committed snapshot"),{kind:"missed",reason:"worktree is not a clean committed snapshot"};let s=t.languages??zi(e),a=Pi(e,s,oS(t)),c=Sa(o,a);if(!c)return Ca(o,n.cacheDir,"missed",void 0,"worktree is not a clean committed snapshot"),{kind:"missed",reason:"worktree is not a clean committed snapshot"};let l=rr(c);if(l)return Wr(n.cacheDir,e,a)?(Ku(c,n.cacheDir,"local-fresh"),{kind:"local-fresh"}):(qu({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:c.generationId});let u=xa(n.cacheDir);return u?.status!=="complete"||JSON.stringify(u.fingerprint)!==JSON.stringify(a)||JSON.stringify([...u.indexedLanguages??[]].sort())!==JSON.stringify([...s].sort())?{kind:"missed",reason:"local metadata does not match the clean worktree snapshot"}:Wr(n.cacheDir,e,a)?(nS({snapshot:c,sourceCacheDir:n.cacheDir,sourceProjectRoot:e,sourceStillValid:()=>{let d=gr(e);return(d?Sa(d,a):void 0)?.generationId===c.generationId}}),Ku(c,n.cacheDir,"built"),{kind:"built",generationId:c.generationId}):{kind:"missed",reason:"local index artifacts are incomplete or incompatible"}}catch(o){return{kind:"failed",reason:o instanceof Error?o.message:String(o)}}}async function Qte(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??Date.now,o=i()+n,s=A(e.repositoryCacheDir,"locks"),a=A(s,`${e.generationId}.lock`);for(en(s,{recursive:!0});i()<=o;){if(rr(e))return{kind:"generation-ready"};let c=Ju();try{let l=Kb(a,"wx");try{Jb(l,`${JSON.stringify({version:1,pid:process.pid,token:c,generationId:e.generationId,startedAt:new Date(i()).toISOString()})}
|
|
374
|
+
`)}finally{Vb(l)}return{kind:"owner",release:()=>{try{let u=JSON.parse(tt(a,"utf8"));u.pid===process.pid&&u.token===c&&zu(a)}catch{}}}}catch(l){if(l.code!=="EEXIST")return{kind:"timeout"};let u=sS(a);if(u&&(u.pid===void 0||!dt(u.pid))){JM(a,u);continue}await GM(r)}}return rr(e)?{kind:"generation-ready"}:{kind:"timeout"}}function Ku(e,t,n,r=void 0){let i={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,activeGenerationId:e.generationId,lastAction:n,lastSeenAt:(r??(()=>new Date))().toISOString()},o={...i,ownershipChecksum:Zu(i)};return aS(e.repositoryCacheDir,o,!0),o}function Ca(e,t,n,r=void 0,i=void 0){let o={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,lastAction:n,...i?{lastReason:i}:{},lastSeenAt:(r??(()=>new Date))().toISOString()},s={...o,ownershipChecksum:Zu(o)};return aS(Gi(e.repositoryId),s,!1),s}function Zu(e){return io(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:Ct(e.projectRoot),localCacheDir:Ct(e.localCacheDir)}))}function iS(e,t,n=void 0,r){try{let i=JSON.parse(tt(A(t,Zb),"utf8"));if(i.version!==1||typeof i.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(i.repositoryId)||typeof i.worktreeId!="string"||!/^[a-f0-9]{24}$/.test(i.worktreeId))return null;let o=A(Gi(i.repositoryId),"worktrees",`${i.worktreeId}.json`),s=JSON.parse(tt(o,"utf8")),a=r??gr(e);if(!a?.clean||!a.treeOid||s.version!==1||s.repositoryId!==i.repositoryId||s.worktreeId!==i.worktreeId||s.repositoryId!==a.repositoryId||s.worktreeId!==a.worktreeId||Ct(s.projectRoot)!==Ct(a.projectRoot)||s.treeOid!==a.treeOid||Ct(s.localCacheDir)!==Ct(t)||s.ownershipChecksum!==Zu(s))return null;let c=xa(t);if(!e0(c?.fingerprint))return null;let l=Sa(a,c.fingerprint);if(!l||s.baseGenerationId!==l.generationId||s.activeGenerationId!==l.generationId||!Wr(t,e,l.fingerprint,!0,!1))return null;let u=(n??(()=>new Date))();if(Number.isFinite(Date.parse(s.lastSeenAt))&&u.getTime()-Date.parse(s.lastSeenAt)<6e4)return s;let d=ku(l.repositoryCacheDir,{waitMs:5e3});if(!d)return null;try{s.lastSeenAt=u.toISOString(),_e(o,s,{spacing:2,trailingNewline:!0})}finally{d.release()}return s}catch{return null}}function VM(e){let t=JSON.parse(e);if(t.version!==Yu||t.artifactCatalogVersion!==eo||typeof t.generationId!="string"||!/^[a-f0-9]{64}$/.test(t.generationId)||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.treeOid!="string"||!t.treeOid||typeof t.producerIdentity!="string"||t.producerIdentity!==Vu||typeof t.sourceProjectRoot!="string"||typeof t.scipProjectRoot!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!t.fingerprint||!Array.isArray(t.artifacts))throw new Error("invalid shared generation manifest");let n=new Set;for(let r of t.artifacts){if(!r||typeof r.path!="string"||typeof r.size!="number"||r.size<0||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new Error("invalid shared generation artifact");if(ba(r.path),n.has(r.path))throw new Error(`duplicate shared generation artifact: ${r.path}`);n.add(r.path)}for(let r of["index.db","index.scip","meta.json"])if(!n.has(r))throw new Error(`shared generation is missing ${r}`);return t}function ro(e,t){en(Yb(t),{recursive:!0});try{Hb(e,t,BM.COPYFILE_FICLONE)}catch{Hb(e,t)}}function qM(e,t){for(let n of Cf(t)){if(Ct(n.path)===Ct(t))continue;let r=ia(n.path),i=xa(r);if(!(i?.status!=="complete"||JSON.stringify(i.fingerprint)!==JSON.stringify(e.fingerprint)||JSON.stringify([...i.indexedLanguages??[]].sort())!==JSON.stringify([...e.fingerprint.languages].sort()))&&Wr(r,n.path,e.fingerprint))try{return{manifest:nS({snapshot:e,sourceCacheDir:r,sourceProjectRoot:n.path}),sourceProjectRoot:n.path}}catch{continue}}return null}function KM(e,t,n){en(e,{recursive:!0}),_e(A(e,Zb),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function Gb(e){try{let t=ya(e),n=zb("sha256");for(let r of t.files){let i=tt(_t(e,r));n.update(r).update("\0").update(String(i.byteLength)).update("\0").update(i).update("\0")}return n.digest("hex")}catch{return null}}function xa(e){try{return JSON.parse(tt(A(e,"meta.json"),"utf8"))}catch{return}}function oS(e){return{pnpmWorkspaces:e.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.indexer?.typescript?.projectMode,typescriptProjects:e.indexer?.typescript?.projects,clojureConfigPath:e.indexer?.clojure?.configPath}}function ed(e){return A(e.repositoryCacheDir,"generations",e.generationId)}function sS(e){try{let t=tt(e,"utf8"),n=JSON.parse(t),r=typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0?n.pid:void 0;return{raw:t,...r===void 0?{}:{pid:r}}}catch{return null}}function JM(e,t){let n=`${e}.reclaim`,r=Ju(),i;try{i=Kb(n,"wx")}catch{return!1}try{Jb(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
|
|
375
|
+
`)}finally{Vb(i)}try{let o=sS(e);return!o||o.raw!==t.raw||o.pid!==void 0&&dt(o.pid)?!1:(zu(e),!0)}catch{return!1}finally{try{let o=JSON.parse(tt(n,"utf8"));o.pid===process.pid&&o.token===r&&zu(n)}catch{}}}function aS(e,t,n){let r=ku(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!kn(A(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=A(e,"worktrees");en(i,{recursive:!0}),_e(A(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),KM(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function YM(e,t){let n=A(t,".rollback"),r=new Map,i=new Map;en(n,{recursive:!0});for(let a of["index.scip","index.db","meta.json"]){let c=A(e,a),l=kn(c);r.set(a,l),l&&ro(c,A(n,"stable",a))}for(let a of Xu){let c=A(e,a),l=kn(c);if(l){let u=$M(c);if(!u.isDirectory()||u.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${a}`)}i.set(a,l)}let o=A(e,la),s=kn(o);return s&&cS(o,A(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:s}}function XM(e,t,n){for(let r of Xu){let i=A(t,r);if(n.managedDirectories.get(r)){let s=A(n.root,"managed",r);en(Yb(s),{recursive:!0}),nr(i,s)}let o=A(e,r);kn(o)&&nr(o,i)}}function QM(e,t){for(let i of Xu){let o=A(e,i),s=A(t.root,"managed",i);t.managedDirectories.get(i)?kn(s)&&(En(o,{recursive:!0,force:!0}),nr(s,o)):En(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let s=A(e,i);if(!o){En(s,{force:!0});continue}let a=`${s}.shared-restore-${Ju()}`;ro(A(t.root,"stable",i),a),En(s,{force:!0}),nr(a,s)}let n=A(e,la);En(n,{recursive:!0,force:!0});let r=A(t.root,"sqlite-generations");t.generationStoreExisted&&kn(r)&&nr(r,n)}function cS(e,t){en(t,{recursive:!0});for(let n of HM(e,{withFileTypes:!0})){let r=A(e,n.name),i=A(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?cS(r,i):n.isFile()&&ro(r,i)}}function ZM(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function Wr(e,t,n,r=!0,i=!0){try{let o=xa(e);if(o?.status!=="complete"||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return no("source validation rejected metadata"),!1;let s=ya(e),a=qi(A(e,"index.db"),A(e,"meta.json"));if(r?a.state!=="current":a.state==="invalid"||a.state==="drifted")return no(`source validation rejected SQLite generation state ${a.state}`),!1;let c=new zM(A(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let l=td(t),d=(i?s.files.filter(m=>m.endsWith(".scip")):["index.scip"]).every(m=>{let f=Xb(tt(_t(e,m))).metadata?.projectRoot;return f!==l&&no(`source validation rejected SCIP root for ${m}: ${String(f)}`),f===l});return d||no("source validation rejected SCIP project roots"),d}catch(o){return no(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function no(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function td(e){try{return Ub(UM(e)).href}catch{return Ub(Ct(e)).href}}function e0(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===2&&Array.isArray(t.languages)&&typeof t.pnpmWorkspaces=="boolean"&&(t.typescriptProjectMode==="single"||t.typescriptProjectMode==="workspace")&&Array.isArray(t.typescriptProjects)&&Array.isArray(t.files)&&t.files.every(n=>n!==null&&typeof n=="object"&&typeof n.path=="string"&&typeof n.size=="number"&&typeof n.hash=="string")}function io(e){return zb("sha256").update(e).digest("hex")}function lS(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var nd;function lne(e){nd=e}function uS(e=lS(),t=void 0){if(t===void 0&&nd?.projectRoot===e)return nd;let n=Vy(e),r=Fy(e,n),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:e,config:n,paths:r,dbPath:i,dbPathSource:"env",gitContext:t};if(rd(r.dbPath))return{projectRoot:e,config:n,paths:r,dbPath:r.dbPath,dbPathSource:"configured",gitContext:t};let o=n0(e,"index.db");return{projectRoot:e,config:n,paths:r,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:s0(o,r.dbPath),gitContext:t}}function une(e){return uS(e).dbPath}function dne(e,t,n,r={}){return rd(n.dbPath)&&iS(e,n.cacheDir,void 0,r.gitContext)?{kind:"local-fresh"}:r.gitContext?.clean===!1&&r.watcherGeneration!==void 0&&Xs(n.dbPath)===r.watcherGeneration?Qu(e,t,n,r.gitContext):sb(e,t,n).state==="fresh"?Qu(e,t,n,r.gitContext):rS(e,t,n,r.gitContext)}function mne(e){return!e.startsWith("__")&&!r0.has(e)}var r0=new Set(["bench","config-validate","hook-context","hook-stop","init","setup","setup-agent","setup-ci","setup-hooks","uninstall","work-audit"]);function i0(){try{return o0(lS(),{warnOnRootFallback:!0})}catch(e){console.error(`error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}function o0(e,t={}){let{config:n,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:s,gitContext:a}=uS(e);if(!rd(i))throw new Error("No index.db found. Run: scip-query reindex");t.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:e,sharedEvidenceDbPath:tS(e,n,a),entryRoots:n.entryRoots,semantic:n.semantic,suppressions:n.suppressions,declaredCouplings:n.declaredCouplings,locality:n.locality,architecture:n.architecture,coverageContracts:n.coverageContracts,docs:n.docs},l=Ay(e);return new oa(c,l)}function s0(e,t){let n="unknown time";try{n=t0(e).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${e}, modified ${n}) because the configured index was not found at ${t}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}function tn(e){let t=i0();try{return e(t)}finally{t.close()}}function fne(e,t){return t.concat([e])}function dS(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 pne(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 a0(e)}}function a0(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}function mS(e){return e+1}function c0(e,t){return`${mS(e)}-${mS(t)}`}function hne(e,t,n){return`${e}:${c0(t,n)}`}function yne(e,t=180){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var Ft={empty(e){console.log(e)},list(e,t){for(let n of e)console.log(t(n))},groupedByFile(e,t,n=r=>r.relativePath){let r="";for(let i of e){let o=n(i);o!==r&&(r&&console.log(""),console.log(o),r=o),console.log(t(i))}},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 r of n.rows)console.log(r)}},table(e,t,n){console.log(` ${e.join(" ")}`);let r=n??e.map(i=>i.length);console.log(` ${r.map(i=>"\u2500".repeat(i)).join(" ")}`);for(let i of t)console.log(i)}};import{availableParallelism as GJ}from"os";import{fileURLToPath as Hm}from"url";import{existsSync as Ra,readFileSync as l0,readdirSync as pS}from"fs";import{join as oo}from"path";var u0={files:new Set,pathPrefixes:[]},id=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,d0=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,gS=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],m0=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),f0=4,p0=J("package-surface",{clearGroups:["whole-project"]});function g0(e){return p0.get(e,()=>h0(e.config.projectRoot))}function ir(e,t){let n=g0(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function h0(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of y0(e))for(let o of b0(r))S0(e,i,o,t,n);return t.size===0&&n.length===0?u0:{files:t,pathPrefixes:n}}function y0(e){let t=[],n=yS(e,"");return n&&t.push({manifest:n,packageRoot:""}),hS(e,"",t,0),t}function hS(e,t,n,r){if(r>=f0)return;let i=oo(e,t);if(Ra(i))for(let o of pS(i,{withFileTypes:!0})){if(!o.isDirectory()||m0.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=yS(e,s);a&&n.push({manifest:a,packageRoot:s}),hS(e,s,n,r+1)}}function yS(e,t){try{let n=l0(oo(e,t,"package.json"),"utf-8"),r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function b0(e){let t=[];for(let r of["main","module","types","browser"])typeof e[r]=="string"&&t.push(e[r]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let r of Object.values(n))typeof r=="string"&&t.push(r);return bS(e.exports,t),t}function bS(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))bS(n,t)}function S0(e,t,n,r,i){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 fS(c))l!==""&&i.push(nn(t,l));return}let a=o.replace(d0,"");for(let c of fS(a)){c===a&&c===o&&r.add(nn(t,o));for(let l of gS)C0(e,r,t,c+l)}r.add(nn(t,o))}function fS(e){let t=[e];return id.test(e)&&(t.push(e.replace(id,"src/")),t.push(e.replace(id,""))),t}function C0(e,t,n,r){let i=nn(n,r);if(t.add(i),!r.startsWith("src/")||Ra(oo(e,i)))return;let o=gS.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);x0(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 SS(e,n,c,`${l}${o}`))t.add(u)}function x0(e,t,n,r,i){let o=nn(n,`${r}/index${i}`);Ra(oo(e,o))&&t.add(o)}function SS(e,t,n,r){let i=oo(e,t,n);if(!Ra(i))return[];let o=[];for(let s of pS(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...SS(e,t,a,r)):s.isFile()&&s.name===r&&o.push(nn(t,a))}return o}function nn(e,t){return e?`${e}/${t}`:t}import{existsSync as va,readFileSync as R0,readdirSync as v0}from"fs";import{dirname as I0,join as Ia}from"path";var w0={rootFiles:new Set,sourcePrefixes:[]},D0=new Set([".git",".scipquery","node_modules","target"]),E0=6,k0=J("rust-library-surface",{clearGroups:["whole-project"]});function CS(e,t,n){if(!n.endsWith(".rs")||!_0(P0(e),n))return!1;let r=Q(e,n).find(i=>i.symbol===t);return r?F0(Ce(e,n)[r.startLine]??""):!1}function P0(e){return k0.get(e,()=>T0(e.config.projectRoot))}function T0(e){let t=new Set,n=new Set;for(let r of L0(e)){let i=Ia(e,r,"Cargo.toml"),o=R0(i,"utf8"),s=N0(o),a=nn(r,"src/lib.rs"),c=s?nn(r,s):!A0(o)&&va(Ia(e,a))?a:null;if(!c)continue;t.add(c);let l=I0(c).replaceAll("\\","/");n.add(l==="."?"":`${l}/`)}return t.size===0?w0:{rootFiles:t,sourcePrefixes:[...n].sort()}}function _0(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:M0(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function F0(e){return/^\s*pub\s+(?!\()/.test(e)}function L0(e){if(!va(e))return[];let t=[];return xS(e,"",t,0),t}function xS(e,t,n,r){let i=Ia(e,t);if(va(i)&&(va(Ia(i,"Cargo.toml"))&&n.push(t),!(r>=E0)))for(let o of v0(i,{withFileTypes:!0})){if(!o.isDirectory()||D0.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;xS(e,s,n,r+1)}}function N0(e){let t=!1;for(let n of e.split(`
|
|
376
|
+
`)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="lib";continue}if(!t)continue;let o=/^path\s*=\s*["']([^"']+)["']/.exec(r)?.[1];if(o)return o.replaceAll("\\","/").replace(/^\.\//,"")}return null}function A0(e){let t=!1;for(let n of e.split(`
|
|
377
|
+
`)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="package";continue}if(t&&/^autolib\s*=\s*false\b/.test(r))return!0}return!1}function M0(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function Y(e){let t=te(e);return Z0(t)?"test":eO(t)?"worker":tO(t)?"entry":nO(t)?"barrel":"source"}function Gr(e){return Y(e)==="barrel"}function vS(e){return O0.get(e,()=>{let n=N(e,{includeIgnored:!1}).filter(s=>{let a=Y(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let r=ie(e),i=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!i.has(s)){i.add(s),Y(s)==="barrel"&&o.add(s);for(let a of r.get(s)??[])i.has(a)||n.push(a)}}return o})}var O0=J("live-barrels",{clearGroups:["whole-project"]});function od(e,t){return vS(e).has(te(t))}function IS(e){let t=vS(e);return N(e,{includeIgnored:!1}).filter(n=>Gr(n)&&!t.has(n)&&!j0(e,n))}function j0(e,t){let n=te(t),r=ut(e).forFile(n,{facts:!0}).facts?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
|
|
378
378
|
FROM defn_enclosing_ranges der
|
|
379
379
|
JOIN documents d ON d.id = der.document_id
|
|
380
380
|
WHERE d.relative_path = ?
|
|
381
|
-
AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Ee(e,t){let n=te(t),r=Y(t);return r==="entry"||r==="worker"||
|
|
381
|
+
AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Ee(e,t){let n=te(t),r=Y(t);return r==="entry"||r==="worker"||Y0(n)||od(e,n)}function de(e,t,n){let r=te(n);if(ir(e,r)||$0(e,t,r)||CS(e,t,r)||J0(t,r))return!0;let i=e.config.entryRoots;return i?!!(i.files?.some(o=>te(o)===r)||i.pathPrefixes?.some(o=>r.startsWith(te(o)))||i.qualifiedVars?.some(o=>rO(t,o))||i.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}var B0=J("package-surface-reachability",{clearGroups:["whole-project"]});function $0(e,t,n){let r=H0(e).get(n);return r===void 0?!1:r===null||r.has(T(t))}function H0(e){return B0.get(e,()=>{let t=new Map,n=[];for(let r of N(e,{includeIgnored:!1}))ir(e,r)&&(t.set(r,null),n.push(r));for(;n.length>0;){let r=n.shift(),i=t.get(r);if(i!==void 0)for(let o of Kt(e,r)){if(!o.sourcePath||e.isIgnored(o.sourcePath))continue;let s=U0(i,o);s!==void 0&&W0(t,o.sourcePath,s)&&n.push(o.sourcePath)}}return t})}function U0(e,t){if(e===null)return t.kind==="named"?new Set(t.names):null;if(t.kind==="star")return new Set(e);if(t.kind==="star-as")return;let n=t.names.filter(r=>e.has(r));return n.length>0?new Set(n):void 0}function W0(e,t,n){if(!e.has(t))return e.set(t,n),!0;let r=e.get(t);if(r===void 0)return!1;if(r===null||n===null)return r===null?!1:(e.set(t,null),!0);let i=!1;for(let o of n)r.has(o)||(r.add(o),i=!0);return i}var wS=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),G0=new Set(["default","generateMetadata","generateStaticParams"]),z0=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),V0=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),q0=new Set(["load","actions","entries",...wS]),K0=new Set(["default"]);function J0(e,t){let n=T(e);return n===""?!1:DS(t)?wS.has(n):ES(t)?G0.has(n):kS(t)?z0.has(n):PS(t)?V0.has(n):TS(t)?q0.has(n):Q0(t)?K0.has(n):!1}function Y0(e){return DS(e)||ES(e)||kS(e)||X0(e)||PS(e)||TS(e)}function DS(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function ES(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function kS(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function X0(e){let t="(?:middleware|proxy|instrumentation)\\.(?:ts|js|mts|mjs)";return new RegExp(`^(?:src/)?${t}$`).test(e)||new RegExp(`(?:^|/)src/${t}$`).test(e)||new RegExp(`(?:^|/)(?:apps|services|packages)/[^/]+/(?:src/)?${t}$`).test(e)}function PS(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function TS(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function Q0(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function Z0(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 eO(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function tO(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 nO(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 rO(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let r=t.slice(0,n),i=t.slice(n+1);return e.includes(RS(r)+"/")&&e.includes(RS(i)+".")}function RS(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}import{SymbolInformation_Kind as z}from"@c4312/scip";var wa=new Map(Object.entries(z).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),_S=new Map([...wa.entries()].map(([e,t])=>[t.toLowerCase(),e]));function so(e){return wa.get(e)??"Unknown"}function Lt(){return[z.Function,z.Method,z.Macro,z.Constructor,z.Getter,z.Setter,z.StaticMethod,z.SingletonMethod,z.AbstractMethod,z.ProtocolMethod,z.TraitMethod]}function FS(){return[z.Class,z.Interface,z.Struct,z.Trait,z.Type,z.TypeAlias,z.Enum,z.Union,z.Protocol]}function Hne(){return[z.Constant,z.Variable,z.Value,z.Field,z.Property,z.StaticDataMember,z.StaticField,z.StaticProperty,z.StaticVariable,z.EnumMember]}function ft(e,t,n={}){let r=Da(e,[t],{additive:n.additive,semantic:n.semantic,semanticEvidence:n.semanticEvidence}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>le(o.symbol)||o.source==="ast-callsite"):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function NS(e,t,n){return ad(e,[t],n).get(t.symbolId)??[]}function ad(e,t,n){let r=sO(e)?cO(e,t,{semantic:n.semantic!==!1,semanticEvidence:n.semanticEvidence}):aO(e,n.semanticEvidence);return typeof n.limit!="number"?new Map(t.map(i=>[i.symbolId,r.get(i.symbolId)??[]])):new Map(t.map(i=>[i.symbolId,(r.get(i.symbolId)??[]).slice(0,n.limit)]))}var iO=J("caller-rows",{clearGroups:["whole-project"]}),oO=2e4;function sO(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>oO}function aO(e,t){return iO.get(e,()=>{let n=xe(e),r=Da(e,n,{semanticEvidence:t}),i=new Map;for(let a of n)i.set(a.symbol,a.symbolId);let o=new Map,s=new Map;for(let a of n){let c=r.get(a.symbolId);if(!(!c||c.length===0))for(let l of c){let u=i.get(l.symbol);if(u===void 0||u===a.symbolId)continue;let d=o.get(u);d||(d=[],o.set(u,d),s.set(u,new Set));let m=`${a.symbol}|${a.relativePath}`;s.get(u).has(m)||(s.get(u).add(m),d.push({symbol:a.symbol,file:a.relativePath,source:"caller-map-inversion"}))}}return o})}function cO(e,t,n){let r=n.semantic&&n.semanticEvidence?t.flatMap(a=>{let c=lO(e,a);return c?[c]:[]}):[],i=new Map(r.map(a=>[a.symbolId,a])),o=n.semanticEvidence?.referenceMap(e,r)??new Map,s=new Map;for(let a of t){let c=[],l=new Set,u=m=>{if(m.symbol===a.symbol)return;let f=`${m.symbol}|${m.file}`;l.has(f)||(l.add(f),c.push(m))};for(let m of ki(e,a))m.file!==a.relativePath&&u({symbol:m.enclosingSymbol??m.file,file:m.file,source:"resolved-reference"});let d=i.get(a.symbolId);if(d)for(let m of o.get(d.symbolId)??[]){if(m.file===a.relativePath||e.isIgnored(m.file))continue;let f=Dt(Q(e,m.file),m.line);u({symbol:f?.symbol??m.file,file:m.file,source:"semantic-reference"})}s.set(a.symbolId,c)}return s}function lO(e,t){let n=Lt().join(", "),r=FS().join(", ");return e.get(`SELECT
|
|
382
382
|
d.id AS documentId,
|
|
383
383
|
gs.id AS symbolId,
|
|
384
384
|
gs.symbol,
|
|
@@ -397,7 +397,7 @@ Thumbs.db
|
|
|
397
397
|
LEFT JOIN chunks c ON c.document_id = der.document_id
|
|
398
398
|
JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
|
|
399
399
|
WHERE gs.id = ?
|
|
400
|
-
LIMIT 1`,t.symbolId)??null}function Da(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)M(u.relativePath)&&
|
|
400
|
+
LIMIT 1`,t.symbolId)??null}function Da(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)M(u.relativePath)&&gn(e,u.relativePath)!==null?i.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[d,m]of u){let f=s.get(d);f||(f=[],s.set(d,f));let p=a.get(d);p||(p=new Set,a.set(d,p));for(let g of m){let y=`${g.symbol}|${g.chunkId}`;p.has(y)||(p.add(y),f.push(g))}}};i.length>0&&c(uO(e,i)),n.semantic!==!1&&n.semanticEvidence&&c(hO(n.semanticEvidence.calleeMap(e,t)));let l=r?t:o;return l.length>0&&c(pO(e,l)),s}function uO(e,t){let n=new Map,r=dO(t,n),i=Qt(e);for(let[o,s]of r){let a=gn(e,o);if(!a)continue;let c=vl(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=mO(e,o,i,l);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 dO(e,t){let n=new Map;for(let r of e){let i=n.get(r.relativePath);i?i.push(r):n.set(r.relativePath,[r]),t.set(r.symbolId,[])}for(let r of n.values())r.sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine));return n}function mO(e,t,n,r){let i=ws(t,n.get(r.calleeLeaf)??[]);if(i.length===0)return null;let o=fO(e,t,i,r.calleeQualifier);return o||Ds(e,t,i,r.memberAccess)}function fO(e,t,n,r){if(!r||M(t)!=="clojure")return null;let o=re(e,t).filter(s=>s.kind==="namespace"&&s.localName===r&&s.sourcePath).map(s=>s.sourcePath);for(let s of o){let a=n.find(c=>Ve(s,c.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===r)??null}function pO(e,t){if(t.length===0)return new Map;let r=sd(t.map(f=>f.documentId)).flatMap(f=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
|
|
401
401
|
FROM mentions m
|
|
402
402
|
JOIN chunks c ON m.chunk_id = c.id
|
|
403
403
|
WHERE m.role != 1
|
|
@@ -414,9 +414,9 @@ Thumbs.db
|
|
|
414
414
|
GROUP BY m.symbol_id
|
|
415
415
|
) def_chunk ON def_chunk.symbol_id = gs.id
|
|
416
416
|
WHERE gs.id IN (${f.map(()=>"?").join(",")})`,...f,...f)),a=sd([...t.map(f=>f.documentId),...s.flatMap(f=>f.document_id===null?[]:[f.document_id])]),c=new Map(a.flatMap(f=>e.all(`SELECT id, relative_path FROM documents
|
|
417
|
-
WHERE id IN (${f.map(()=>"?").join(",")})`,...f).map(p=>[p.id,p.relative_path]))),l=new Map;for(let f of s)l.has(f.symbol_id)||l.set(f.symbol_id,{symbol:f.symbol,file:f.document_id!==null?c.get(f.document_id)??"":""});let u=new Map,d=c,m=pO(t);for(let[f,p]of m){let y=[...i.get(f)??[]].sort((S,b)=>S.start_line-b.start_line||S.end_line-b.end_line),h=[...p].sort((S,b)=>S.startLine-b.startLine||S.endLine-b.endLine),C=new Set,x=0;for(let S of h){for(;x<y.length&&y[x].start_line<=S.endLine;)C.add(y[x]),x+=1;for(let D of C)D.end_line<S.startLine&&C.delete(D);let b=new Set,v=[],R=null,E=()=>{if(R)return R;let D=d.get(S.documentId)??"",k=new Set;if(D){let L=sg(e,D),ne=Math.max(0,S.startLine),X=Math.min(L.length-1,S.endLine);for(let F=ne;F<=X;F+=1)for(let ae of L[F])k.add(ae)}return R=k,k};for(let D of C){if(D.symbol_id===S.symbolId)continue;let k=l.get(D.symbol_id);if(!k)continue;if(!(D.start_line>=S.startLine&&D.end_line<=S.endLine)){if(!(D.start_line<=S.endLine&&D.end_line>=S.startLine))continue;let F=T(k.symbol);if(!F||!E().has(F))continue}let ne=`${k.symbol}|${D.chunk_id}`;b.has(ne)||(b.add(ne),v.push({...k,chunkId:D.chunk_id,source:"scip-chunk"}))}u.set(S.symbolId,v)}}return u}var LS=500;function sd(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=LS)n.push(t.slice(r,r+LS));return n}function pO(e){let t=new Map;for(let n of e){let r=t.get(n.documentId);r?r.push(n):t.set(n.documentId,[n])}return t}function gO(e){let t=new Map;for(let[n,r]of e){let i=[];for(let o of r)i.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee"});t.set(n,i)}return t}function AS(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=N(e,{includeIgnored:!1}),o=Xt(e),s=t??xe(e),a=new Set(s.map(l=>l.symbolId)),c=RO(s);return hO(e,r,i,o,a,c),yO(e,r,s,a),xO(e,r,i,o,a,c),n.semantic!==!1&&n.semanticEvidence&&IO(r,n.semanticEvidence.callerMap(e,vO(s))),r}function hO(e,t,n,r,i,o){for(let s of n){if(!M(s))continue;let a=pn(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=ws(s,r.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let u=Ds(e,s,l,c.memberAccess);u&&i.has(u.symbolId)&&u.file!==s&&cd(t,u.symbolId,s)}}}function yO(e,t,n,r){let i=SO(n);for(let o of bO(e,r))e.isIgnored(o.relative_path)||CO(o,i.get(o.symbol_id))||cd(t,o.symbol_id,o.relative_path)}function bO(e,t){return _r(e,t?[...t]:void 0)}function SO(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 CO(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function xO(e,t,n,r,i,o){for(let s of n){if(M(s)!=="rust")continue;let a=Un(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a){if(o&&!o.has(c))continue;let l=r.get(c);if(l)for(let u of l)i.has(u.symbolId)&&u.file!==s&&cd(t,u.symbolId,s)}}}function cd(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function RO(e){let t=new Set;for(let n of e){let r="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?T(n.symbol):"";r&&t.add(r)}return t.size>0?t:null}function vO(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function IO(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let o of r)i.add(o)}}function Ct(e,t,n){return NS(e,t,n)}function MS(e,t,n){return ad(e,t,n)}function ld(e,t,n={}){return AS(e,t,n)}function ao(e,t,n={}){return hg(e,t,n)}function OS(e,t,n={}){let r=ld(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?r:nn(r,ao(e,t))}function nn(e,t){let n=new Map;for(let[r,i]of e)n.set(r,new Set(i));for(let[r,i]of t){let o=n.get(r)??new Set;for(let s of i)o.add(s);n.set(r,o)}return n}function jS(e,t,n){let r=t.identifierResolution==="strict"?Fr:pg,i=t.candidateNames?Di(t.candidateNames):null,o=0,s=0,a=0,c=0,l="";for(let u of t.paths)if(o+=1,l=u,!(!M(u)&&!(t.includeVueSfc&&$t(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(i&&!Es(P(e,u),i))continue;s+=1;let m=(p,g,y,h)=>{if(t.candidateNames&&!t.candidateNames.has(p))return;a+=1;let C=t.resolveTargets?t.resolveTargets({sourceFile:u,name:p,kind:g,defaultTargets:h}):h();for(let x of C)c+=1,n({sourceFile:u,name:p,target:x,occurrences:y,kind:g})},f=Yt(e,u);for(let[p,g]of f)m(p,"identifier",g.length,()=>r(e,u,p));for(let p of Un(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=p.kind==="cross-language-dispatch"?()=>Fr(e,u,p.name):()=>r(e,u,p.name);m(p.name,p.kind,p.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&w("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:l,candidateMatchedPaths:s,visitedNames:a,visitedHits:c}))}}function O(e){return e.endLine-e.startLine+1}function BS(e,t={}){let{scope:n,files:r,minLoc:i=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:l=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:f=!1,sortByLocDesc:p=!1}=t,g=[],y=wO(e,{scope:n,files:r,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),h=new Map,C=new Map,x=b=>{let v=h.get(b);if(v!==void 0)return v;let R=Ee(e,b);return h.set(b,R),R},S=b=>{let v=C.get(b);if(v!==void 0)return v;let R=Y(b);return C.set(b,R),R};for(let b of y){let v=b.relativePath;if(e.isIgnored(v)||a&&x(v)||!DO(b,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&b.symbol===s)continue;let R=O(b);R<i||R>o||c&&EO(v)||l&&de(e,b.symbol,v)||m&&Ie(b.symbol)||S(v)!=="test"&&(hr(b.symbol)||!f&&Ho(e,v,b.startLine)||g.push(b))}return p?g.sort((b,v)=>O(v)-O(b)):g}function wO(e,t){return t.files!==void 0?[...new Set(t.files.map(r=>r.replace(/\\/g,"/")))].sort().filter(r=>!t.scope||r.includes(t.scope)).flatMap(r=>Q(e,r)):t.requireCallableSymbol?Ri(e,{scope:t.scope,symbolMatches:le,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?Ri(e,{scope:t.scope,symbolMatches:ee,sqlPrefilter:"function-like"}):eg(e,t.scope)}function DO(e,t){return t.requireCallableSymbol?le(e.symbol):t.requireFunctionLikeSymbol?ee(e.symbol):e.isFunctionLike}function EO(e){return(e.split("/").pop()??"").includes("types")}var _=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Rl(this.db,t)}definitionsForFile(t){return Q(this.db,t)}productionCallableDefinitions(t={}){return BS(this.db,t)}calleeMap(t,n={}){return Da(this.db,t,{...n,semanticEvidence:H})}crossFileCallerMap(t,n={}){return ld(this.db,t,{...n,semanticEvidence:H})}sourceFallbackCallerFiles(t,n={}){return ao(this.db,t,n)}callerFileMap(t,n={}){return OS(this.db,t,{...n,semanticEvidence:H})}frameworkReferencedSymbolIds(t){let n=new Map;for(let i of t){if(!i.leaf)continue;let o=n.get(i.leaf)??[];o.push(i.symbolId),n.set(i.leaf,o)}let r=new Set;for(let i of N(this.db,{includeIgnored:!1}))if(M(i)==="rust")for(let{name:o}of Un(this.db,i,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])r.add(s);return r}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let r=new Map(t.map(o=>[o.symbolId,o.symbol])),i=this.calleeMap(t,n);return new Set([...i.entries()].filter(([o,s])=>{let a=r.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return ie(this.db,t)}fileKind(t){return Y(t)}hasSuppressionComment(t){return Ho(this.db,t.relativePath,t.startLine)}sourceFiles(){return $e(this.db)}scanSourceReferences(t,n){jS(this.db,t,n)}callableSignature(t){let n=at(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};import{statSync as kO}from"fs";function or(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:r,references:i,...PO(e.config.dbPath)}}function PO(e){try{let t=kO(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function TO(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function _O(e,t){let n=TO(t);return N(e,{like:n,includeIgnored:!1}).filter(r=>FO(t,r)).map(r=>({relativePath:r}))}function FO(e,t){if(!/[*?]/.test(e))return t.includes(e);let n=e.includes("/")?e:`**/${e}`;return Ea(n.split("/"),t.split("/"))}function Ea(e,t){if(e.length===0)return t.length===0;let[n,...r]=e;return n==="**"?Ea(r,t)||t.length>0&&Ea(e,t.slice(1)):t.length===0||!LO(n??"",t[0]??"")?!1:Ea(r,t.slice(1))}function LO(e,t){let n="^";for(let r of e)r==="*"?n+="[^/]*":r==="?"?n+="[^/]":n+=NO(r);return n+="$",new RegExp(n).test(t)}function NO(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}import{basename as AO}from"path";function MO(e,t){let n=B(e,t);if(!n)return[];let r=T(n.symbol),o=new _(e).definitionsForFile(n.relativePath).filter(l=>le(l.symbol)),s=o.filter(l=>l.parentTypeName===r||l.symbol.includes(r)),c=(s.length>0?s:OO(AO(n.relativePath))===r?o.filter(l=>l.symbol.includes("<invalid-global-code>")):[]).map(l=>({startLine:l.startLine,endLine:l.endLine,name:T(l.symbol)}));return M(n.relativePath)!=="clojure"?c:BO(c,jO(e,n))}function OO(e){return e.replace(/\.[^.]+$/,"")}function jO(e,t){let n=T(t.symbol);return n?(G(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({startLine:r.startLine,endLine:r.endLine,name:r.memberName})):[]}function BO(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.name}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}function ud(e,t,n={}){let r=B(e,t);if(!r)return{definitions:[],referencedBy:[]};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=Jt(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:HO(o,i?.display_name??null,r.symbol),source:$O(e,r.relativePath,r.startLine,r.endLine)}],a=Dt(e,r,{semantic:n.semantic,semanticEvidence:H}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?I(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function $O(e,t,n,r){let i=P(e,t);if(!i)return null;let s=i.split(`
|
|
417
|
+
WHERE id IN (${f.map(()=>"?").join(",")})`,...f).map(p=>[p.id,p.relative_path]))),l=new Map;for(let f of s)l.has(f.symbol_id)||l.set(f.symbol_id,{symbol:f.symbol,file:f.document_id!==null?c.get(f.document_id)??"":""});let u=new Map,d=c,m=gO(t);for(let[f,p]of m){let y=[...i.get(f)??[]].sort((S,b)=>S.start_line-b.start_line||S.end_line-b.end_line),h=[...p].sort((S,b)=>S.startLine-b.startLine||S.endLine-b.endLine),C=new Set,x=0;for(let S of h){for(;x<y.length&&y[x].start_line<=S.endLine;)C.add(y[x]),x+=1;for(let D of C)D.end_line<S.startLine&&C.delete(D);let b=new Set,v=[],R=null,E=()=>{if(R)return R;let D=d.get(S.documentId)??"",k=new Set;if(D){let L=sg(e,D),ne=Math.max(0,S.startLine),X=Math.min(L.length-1,S.endLine);for(let F=ne;F<=X;F+=1)for(let ae of L[F])k.add(ae)}return R=k,k};for(let D of C){if(D.symbol_id===S.symbolId)continue;let k=l.get(D.symbol_id);if(!k)continue;if(!(D.start_line>=S.startLine&&D.end_line<=S.endLine)){if(!(D.start_line<=S.endLine&&D.end_line>=S.startLine))continue;let F=T(k.symbol);if(!F||!E().has(F))continue}let ne=`${k.symbol}|${D.chunk_id}`;b.has(ne)||(b.add(ne),v.push({...k,chunkId:D.chunk_id,source:"scip-chunk"}))}u.set(S.symbolId,v)}}return u}var LS=500;function sd(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=LS)n.push(t.slice(r,r+LS));return n}function gO(e){let t=new Map;for(let n of e){let r=t.get(n.documentId);r?r.push(n):t.set(n.documentId,[n])}return t}function hO(e){let t=new Map;for(let[n,r]of e){let i=[];for(let o of r)i.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee"});t.set(n,i)}return t}function AS(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=N(e,{includeIgnored:!1}),o=Qt(e),s=t??xe(e),a=new Set(s.map(l=>l.symbolId)),c=vO(s);return yO(e,r,i,o,a,c),bO(e,r,s,a),RO(e,r,i,o,a,c),n.semantic!==!1&&n.semanticEvidence&&wO(r,n.semanticEvidence.callerMap(e,IO(s))),r}function yO(e,t,n,r,i,o){for(let s of n){if(!M(s))continue;let a=gn(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=ws(s,r.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let u=Ds(e,s,l,c.memberAccess);u&&i.has(u.symbolId)&&u.file!==s&&cd(t,u.symbolId,s)}}}function bO(e,t,n,r){let i=CO(n);for(let o of SO(e,r))e.isIgnored(o.relative_path)||xO(o,i.get(o.symbol_id))||cd(t,o.symbol_id,o.relative_path)}function SO(e,t){return _r(e,t?[...t]:void 0)}function CO(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 xO(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function RO(e,t,n,r,i,o){for(let s of n){if(M(s)!=="rust")continue;let a=Wn(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a){if(o&&!o.has(c))continue;let l=r.get(c);if(l)for(let u of l)i.has(u.symbolId)&&u.file!==s&&cd(t,u.symbolId,s)}}}function cd(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function vO(e){let t=new Set;for(let n of e){let r="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?T(n.symbol):"";r&&t.add(r)}return t.size>0?t:null}function IO(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function wO(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let o of r)i.add(o)}}function xt(e,t,n){return NS(e,t,n)}function MS(e,t,n){return ad(e,t,n)}function ld(e,t,n={}){return AS(e,t,n)}function ao(e,t,n={}){return hg(e,t,n)}function OS(e,t,n={}){let r=ld(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?r:rn(r,ao(e,t))}function rn(e,t){let n=new Map;for(let[r,i]of e)n.set(r,new Set(i));for(let[r,i]of t){let o=n.get(r)??new Set;for(let s of i)o.add(s);n.set(r,o)}return n}function jS(e,t,n){let r=t.identifierResolution==="strict"?Fr:pg,i=t.candidateNames?Di(t.candidateNames):null,o=0,s=0,a=0,c=0,l="";for(let u of t.paths)if(o+=1,l=u,!(!M(u)&&!(t.includeVueSfc&&Ht(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(i&&!Es(P(e,u),i))continue;s+=1;let m=(p,g,y,h)=>{if(t.candidateNames&&!t.candidateNames.has(p))return;a+=1;let C=t.resolveTargets?t.resolveTargets({sourceFile:u,name:p,kind:g,defaultTargets:h}):h();for(let x of C)c+=1,n({sourceFile:u,name:p,target:x,occurrences:y,kind:g})},f=Xt(e,u);for(let[p,g]of f)m(p,"identifier",g.length,()=>r(e,u,p));for(let p of Wn(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=p.kind==="cross-language-dispatch"?()=>Fr(e,u,p.name):()=>r(e,u,p.name);m(p.name,p.kind,p.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&w("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:l,candidateMatchedPaths:s,visitedNames:a,visitedHits:c}))}}function O(e){return e.endLine-e.startLine+1}function BS(e,t={}){let{scope:n,files:r,minLoc:i=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:l=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:f=!1,sortByLocDesc:p=!1}=t,g=[],y=DO(e,{scope:n,files:r,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),h=new Map,C=new Map,x=b=>{let v=h.get(b);if(v!==void 0)return v;let R=Ee(e,b);return h.set(b,R),R},S=b=>{let v=C.get(b);if(v!==void 0)return v;let R=Y(b);return C.set(b,R),R};for(let b of y){let v=b.relativePath;if(e.isIgnored(v)||a&&x(v)||!EO(b,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&b.symbol===s)continue;let R=O(b);R<i||R>o||c&&kO(v)||l&&de(e,b.symbol,v)||m&&Ie(b.symbol)||S(v)!=="test"&&(hr(b.symbol)||!f&&Ho(e,v,b.startLine)||g.push(b))}return p?g.sort((b,v)=>O(v)-O(b)):g}function DO(e,t){return t.files!==void 0?[...new Set(t.files.map(r=>r.replace(/\\/g,"/")))].sort().filter(r=>!t.scope||r.includes(t.scope)).flatMap(r=>Q(e,r)):t.requireCallableSymbol?Ri(e,{scope:t.scope,symbolMatches:le,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?Ri(e,{scope:t.scope,symbolMatches:ee,sqlPrefilter:"function-like"}):eg(e,t.scope)}function EO(e,t){return t.requireCallableSymbol?le(e.symbol):t.requireFunctionLikeSymbol?ee(e.symbol):e.isFunctionLike}function kO(e){return(e.split("/").pop()??"").includes("types")}var _=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Rl(this.db,t)}definitionsForFile(t){return Q(this.db,t)}productionCallableDefinitions(t={}){return BS(this.db,t)}calleeMap(t,n={}){return Da(this.db,t,{...n,semanticEvidence:H})}crossFileCallerMap(t,n={}){return ld(this.db,t,{...n,semanticEvidence:H})}sourceFallbackCallerFiles(t,n={}){return ao(this.db,t,n)}callerFileMap(t,n={}){return OS(this.db,t,{...n,semanticEvidence:H})}frameworkReferencedSymbolIds(t){let n=new Map;for(let i of t){if(!i.leaf)continue;let o=n.get(i.leaf)??[];o.push(i.symbolId),n.set(i.leaf,o)}let r=new Set;for(let i of N(this.db,{includeIgnored:!1}))if(M(i)==="rust")for(let{name:o}of Wn(this.db,i,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])r.add(s);return r}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let r=new Map(t.map(o=>[o.symbolId,o.symbol])),i=this.calleeMap(t,n);return new Set([...i.entries()].filter(([o,s])=>{let a=r.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return ie(this.db,t)}fileKind(t){return Y(t)}hasSuppressionComment(t){return Ho(this.db,t.relativePath,t.startLine)}sourceFiles(){return $e(this.db)}scanSourceReferences(t,n){jS(this.db,t,n)}callableSignature(t){let n=ut(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};import{statSync as PO}from"fs";function or(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:r,references:i,...TO(e.config.dbPath)}}function TO(e){try{let t=PO(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function _O(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function FO(e,t){let n=_O(t);return N(e,{like:n,includeIgnored:!1}).filter(r=>LO(t,r)).map(r=>({relativePath:r}))}function LO(e,t){if(!/[*?]/.test(e))return t.includes(e);let n=e.includes("/")?e:`**/${e}`;return Ea(n.split("/"),t.split("/"))}function Ea(e,t){if(e.length===0)return t.length===0;let[n,...r]=e;return n==="**"?Ea(r,t)||t.length>0&&Ea(e,t.slice(1)):t.length===0||!NO(n??"",t[0]??"")?!1:Ea(r,t.slice(1))}function NO(e,t){let n="^";for(let r of e)r==="*"?n+="[^/]*":r==="?"?n+="[^/]":n+=AO(r);return n+="$",new RegExp(n).test(t)}function AO(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}import{basename as MO}from"path";function OO(e,t){let n=B(e,t);if(!n)return[];let r=T(n.symbol),o=new _(e).definitionsForFile(n.relativePath).filter(l=>le(l.symbol)),s=o.filter(l=>l.parentTypeName===r||l.symbol.includes(r)),c=(s.length>0?s:jO(MO(n.relativePath))===r?o.filter(l=>l.symbol.includes("<invalid-global-code>")):[]).map(l=>({startLine:l.startLine,endLine:l.endLine,name:T(l.symbol)}));return M(n.relativePath)!=="clojure"?c:$O(c,BO(e,n))}function jO(e){return e.replace(/\.[^.]+$/,"")}function BO(e,t){let n=T(t.symbol);return n?(G(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({startLine:r.startLine,endLine:r.endLine,name:r.memberName})):[]}function $O(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.name}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}function ud(e,t,n={}){let r=B(e,t);if(!r)return{definitions:[],referencedBy:[]};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=Yt(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:UO(o,i?.display_name??null,r.symbol),source:HO(e,r.relativePath,r.startLine,r.endLine)}],a=Et(e,r,{semantic:n.semantic,semanticEvidence:H}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?I(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function HO(e,t,n,r){let i=P(e,t);if(!i)return null;let s=i.split(`
|
|
418
418
|
`).slice(n,r+1).join(`
|
|
419
|
-
`).trimEnd();return s.length>0?s:null}function
|
|
419
|
+
`).trimEnd();return s.length>0?s:null}function UO(e,t,n){let r=Jt(e);if(r&&!WO(r))return r;let i=(t??"").trim();return i?ee(n)&&!i.endsWith("()")?`${i}()`:i:I(n)}function WO(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function dd(e,t){let n=Oe(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
|
|
420
420
|
FROM mentions m
|
|
421
421
|
JOIN chunks c ON m.chunk_id = c.id
|
|
422
422
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -480,7 +480,7 @@ Thumbs.db
|
|
|
480
480
|
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
481
481
|
WHERE d2.relative_path IN (${r})
|
|
482
482
|
AND d1.relative_path NOT IN (${r})
|
|
483
|
-
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 pd(e,t){let n=Br(e,t);return n.length===0?[]:
|
|
483
|
+
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 pd(e,t){let n=Br(e,t);return n.length===0?[]:VO([...GO(e,n),...zO(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(qO)}function GO(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
|
|
484
484
|
FROM mentions m
|
|
485
485
|
JOIN chunks c ON m.chunk_id = c.id
|
|
486
486
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -507,8 +507,8 @@ Thumbs.db
|
|
|
507
507
|
AND m.role != 1
|
|
508
508
|
AND ${e.localSymbolPredicate}
|
|
509
509
|
${e.pathExclusionsFor("d1")}
|
|
510
|
-
ORDER BY d1.relative_path`,...t,...t,...t)}function GO(e,t){let n=new _(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>le(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function zO(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 VO(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:I(e.symbol)}}var co=new WeakMap,$S=oe({kind:"definition-exclusions",invalidation:K("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:qO});function US(e,t){let n=M(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let i=P(e,t);if(!i)return[];let o=ce(e,t,i),s=$S.read(e,t,o);if(s)return s;let a=n==="rust"?tj(e,t):XO(e,t);return $S.write(e,t,o,a),a}function qO(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(KO);return n.some(r=>r===null)?null:n}catch{return null}}function KO(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.startLine!="number"||!Number.isFinite(t.startLine)||typeof t.endLine!="number"||!Number.isFinite(t.endLine)||typeof t.reason!="string"||t.containerName!==void 0&&typeof t.containerName!="string")return null;let n=t.disposition===void 0?fj(t.reason):t.disposition;return n!=="exclude"&&n!=="implicit-usage"?null:{startLine:t.startLine,endLine:t.endLine,reason:t.reason,disposition:n,...t.containerName?{containerName:t.containerName}:{}}}var WS=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),JO=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,YO=/\b(?:export\s+)?(?:async\s+)?function\s+use[A-Z][A-Za-z0-9_$]*\b|\b(?:const|let|var)\s+use[A-Z][A-Za-z0-9_$]*\s*(?::[^=;]+)?=\s*(?:async\s*)?(?:function\b|(?:<[^=;{]+>\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>)/;function XO(e,t){let n=P(e,t);if(!n||!QO(n))return[];let r=q(e,t);if(!r)return[];let i=co.get(r);if(i)return i;let o=!1,s=r.rootNode;for(let c of s.namedChildren){if(c.type!=="expression_statement")continue;let l=c.namedChild(0);if(!l||l.type!=="call_expression")continue;let u=l.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&WS.has(d)){o=!0;break}}let a=[];o&&a.push({startLine:0,endLine:s.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)",disposition:"exclude"});for(let c of s.namedChildren){let l=null,u=null;if(c.type==="function_declaration")l=c.namedChild(0)?.text??null,u=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(l=d.namedChild(0)?.text??null,u=d)}else if(c.type==="lexical_declaration"){let d=c.namedChild(0);if(d?.type==="variable_declarator"){let m=d.namedChild(0)?.text,f=d.namedChild(1);m&&(f?.type==="arrow_function"||f?.type==="function_expression")&&(l=m,u=d)}}l&&/^use[A-Z]/.test(l)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return a.push(...GS(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),co.set(r,a),a}function QO(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of WS)if(e.includes(n)){t=!0;break}return t&&JO.test(e)?!0:e.includes("use")&&YO.test(e)}var ZO=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function ej(e){return ZO.test(e)}function GS(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(ej(u.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment",disposition:"exclude"});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 tj(e,t){let n=q(e,t);if(!n)return[];let r=co.get(n);if(r)return r;let i=[],o=nj(n);return o?(co.set(n,o),o):(zS(n.rootNode,i,!1,!1),i.push(...GS(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(...dj(n.rootNode)),co.set(n,i),i)}function nj(e){return pj(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function zS(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)",disposition:"implicit-usage"}),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)",disposition:"implicit-usage"})),e.type==="function_item"||e.type==="function_signature_item"?rj(e,t,n,r):r&&uj(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)",disposition:"implicit-usage"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?ij(e,t,n):e.type==="mod_item"&&gd(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)zS(s,t,i,o)}function rj(e,t,n,r){let i=gd(e),o=null;r?o={reason:"trait impl method (dynamic dispatch)",disposition:"implicit-usage"}:n&&(o={reason:"inside #[cfg(test)] mod",disposition:"exclude"});for(let s of i){if(VS(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=cj(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function ij(e,t,n){let r=gd(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(lj)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:i}),r.some(VS)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",disposition:"exclude",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",disposition:"exclude",containerName:i})}function gd(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 oj=new Set(["test","bench","tokio::test","async_std::test"]),sj=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),aj=new Set(["allow","warn","deny","forbid","cfg","cfg_attr","doc","inline","cold","must_use","deprecated","repr","derive","automatically_derived","non_exhaustive","path","link","link_section","global_allocator","panic_handler"]);function cj(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=mj(e);return t?oj.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:sj.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:aj.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function lj(e){return/#\[\s*derive\s*\(/.test(e)}function VS(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function uj(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function dj(e){let t=gj(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:'attribute `with = "..."` module - body may be invoked via reflection',disposition:"implicit-usage",containerName:i})}return n}function mj(e){let t=/^#!?\[\s*([A-Za-z_][A-Za-z0-9_]*(?:\s*::\s*[A-Za-z_][A-Za-z0-9_]*)*)/.exec(e);return t?t[1].replace(/\s+/g,""):null}function fj(e){return e==="#[tauri::command]"||e==="#[command]"||e==="#[wasm_bindgen]"||e==="#[no_mangle]"||e==="#[napi]"||e==="#[pyfunction]"||e==="#[pymethod]"||e==="#[pyo3]"||e==="#[doc(hidden)]"||e.startsWith("trait ")||e.startsWith("#[derive(<reflective>)]")||e.startsWith("#[derive(...)]")||e.startsWith('serde `with = "')||e.startsWith('attribute `with = "')||e.startsWith("Rust attribute macro #[")||e.startsWith("Rust ABI/export attribute #[")?"implicit-usage":"exclude"}function pj(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 HS=/\bwith\s*=\s*"([^"]+)"/g;function gj(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){HS.lastIndex=0;let r;for(;(r=HS.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function qS(e){let t=hd(e);return(n,r,i,o)=>t(n,r,i,o)?.disposition==="exclude"}function hd(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=US(e,r),s=new Map;for(let a of o){if(!a.containerName)continue;let c=s.get(a.containerName)??[];c.push(a),s.set(a.containerName,c)}return i={ranges:o,containers:s},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r),c=[];for(let u of a.ranges)i>=u.startLine&&i<=u.endLine&&c.push(u);let l=new Set;s&&l.add(s);for(let u of Cs(o))l.add(u);for(let u of l){let d=a.containers.get(u);d&&c.push(...d)}return hj(c)}}function hj(e){if(e.length===0)return null;let n=e.find(r=>r.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}function yd(e,t={}){xc(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function KS(e,t,n={}){xc(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function JS(e,t){if(t.isIgnoredPath(e.relativePath))return je("ignored-file");if(fn(e.symbol))return je("module-like-symbol");if(!ka(e.symbol))return je("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&ka(e.enclosingSymbol))return je("nested-non-callable-value");if(!t.includeTests&&!yj(e.relativePath))return je("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return je("excluded-file-region");let n=T(e.symbol);if(n==="<constructor>")return je("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return je("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return je("python-protocol-member")}return t.isDeclarationOnlyCallable()?je("declaration-only-callable"):t.isFrameworkContractCallable()?je("framework-contract-member"):Ie(e.symbol)?je("rust-trait-impl-member"):hr(e.symbol)?je("rust-test-module"):!t.includeMembers&&!bj(e)?je("member"):e.endLine-e.startLine+1<t.minLoc?je("below-min-loc"):{accepted:!0}}function yj(e){return Y(e)!=="test"}function je(e){return{accepted:!1,rejectionReason:e}}function ka(e){return ee(e)||e.endsWith("().")||e.endsWith(".")}function bj(e){return le(e.symbol)||Cs(e.symbol).length===0}function Pa(e,t){return O(e)-O(t)||e.relativePath.localeCompare(t.relativePath)}function se(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function zr(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 YS(){return new Map}function XS(e,t,n){let r=new Map;for(let i of ag(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||_a(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function QS(e,t,n,r={}){let i=new Set;if(r.conservative||n.size===0){for(let o of lg(e,t))i.add(o.symbol_id);return i}for(let o of cg(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||i.add(o.symbol_id);return i}function bd(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 Ta(e,t,n){let r=e.get(t);if(!r)return!1;for(let[i,o]of r)if(i!==n&&o.occurrences>0)return!0;return!1}function ZS(e){return e?.occurrences??0}function _a(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=tC(e,t,n);o.occurrences+=r,o.sources.add(i)}function eC(e,t,n,r,i){if(r<=0)return;let o=tC(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function tC(e,t,n){let r=e.get(t);r||(r=new Map,e.set(t,r));let i=r.get(n);return i||(i={occurrences:0,sources:new Set},r.set(n,i)),i}var Sj=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function Vr(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=q(e,t.relativePath);if(!n)return!1;let r=n.rootNode.descendantsOfType("method_definition").find(s=>s.startPosition.row<=t.startLine&&s.endPosition.row>=t.endLine);if(!r)return!1;if(/\boverride\b/.test(r.text.slice(0,Math.max(0,r.text.indexOf("{")))))return!0;let i=r.parent;for(;i&&i.type!=="class_declaration"&&i.type!=="class";)i=i.parent;if(!i)return!1;let o=i.text.slice(0,Math.max(0,i.text.indexOf("{")));return/\bimplements\b/.test(o)||/\bextends\b/.test(o)?!0:Sj.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}var Cj=1e3,xj=300;function sr(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=0,d=w("dead.candidates",()=>{let b=se(Rj(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c);return u=b.length,b},()=>({definitions:u})),m=0,f=o?w("dead.inactive-barrels",()=>{let b=new Set(IS(e));return m=b.size,b},()=>({paths:m})):new Set,p=0,g=a?YS():w("dead.mention-reference-counts",()=>{let b=XS(e,f,d.map(v=>v.symbolId));return p=b.size,b},()=>({definitions:d.length,symbolsWithReferences:p})),y=0,h=a?w("dead.mentioned-symbol-ids",()=>{let b=QS(e,d.map(v=>v.symbolId),f,{conservative:f.size===0});return y=b.size,b},()=>({definitions:d.length,referencedSymbols:y})):new Set,C=a?d.filter(b=>!h.has(b.symbolId)):d.filter(b=>!Ta(g,b.symbolId,b.relativePath));a?w("dead.source-fallback.dead-code-only",()=>Pj(e,C,g,{inactiveBarrelPaths:f}),()=>({definitions:C.length,testReferencesIncluded:!0})):w("dead.source-fallback.ast",()=>kj(e,C,g,{inactiveBarrelPaths:f}),()=>({definitions:C.length,testReferencesIncluded:!0}));let x=a?C.filter(b=>!bd(g,b.symbolId)):C.filter(b=>!Ta(g,b.symbolId,b.relativePath));w("dead.caller-map-supplement",()=>Nj(e,x,g,{inactiveBarrelPaths:f,includeSemantic:!a&&l}),()=>({definitions:x.length,semantic:!a&&l}));let S=a?C.filter(b=>!bd(g,b.symbolId)):d;return Ej(e,wj(S,g))}function Rj(e,t){let n=qS(e),r=[];for(let i of Ri(e,{scope:t.scope,symbolMatches:ka,sqlPrefilter:"function-like"}))JS(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>Ij(e,i),isFrameworkContractCallable:()=>Vr(e,i)}).accepted&&r.push(i);return r}var vj=["method_signature","abstract_method_signature","call_signature","construct_signature"];function Ij(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=q(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...vj]).some(i=>i.startPosition.row<=t.startLine&&i.endPosition.row>=t.endLine);let r=Ce(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
|
|
511
|
-
`).trim();return r.endsWith(";")&&!r.includes("=>")&&!r.includes("{")}function
|
|
510
|
+
ORDER BY d1.relative_path`,...t,...t,...t)}function zO(e,t){let n=new _(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>le(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function VO(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 qO(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:I(e.symbol)}}var co=new WeakMap,$S=oe({kind:"definition-exclusions",invalidation:K("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:KO});function US(e,t){let n=M(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let i=P(e,t);if(!i)return[];let o=ce(e,t,i),s=$S.read(e,t,o);if(s)return s;let a=n==="rust"?nj(e,t):QO(e,t);return $S.write(e,t,o,a),a}function KO(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(JO);return n.some(r=>r===null)?null:n}catch{return null}}function JO(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.startLine!="number"||!Number.isFinite(t.startLine)||typeof t.endLine!="number"||!Number.isFinite(t.endLine)||typeof t.reason!="string"||t.containerName!==void 0&&typeof t.containerName!="string")return null;let n=t.disposition===void 0?pj(t.reason):t.disposition;return n!=="exclude"&&n!=="implicit-usage"?null:{startLine:t.startLine,endLine:t.endLine,reason:t.reason,disposition:n,...t.containerName?{containerName:t.containerName}:{}}}var WS=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),YO=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,XO=/\b(?:export\s+)?(?:async\s+)?function\s+use[A-Z][A-Za-z0-9_$]*\b|\b(?:const|let|var)\s+use[A-Z][A-Za-z0-9_$]*\s*(?::[^=;]+)?=\s*(?:async\s*)?(?:function\b|(?:<[^=;{]+>\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>)/;function QO(e,t){let n=P(e,t);if(!n||!ZO(n))return[];let r=q(e,t);if(!r)return[];let i=co.get(r);if(i)return i;let o=!1,s=r.rootNode;for(let c of s.namedChildren){if(c.type!=="expression_statement")continue;let l=c.namedChild(0);if(!l||l.type!=="call_expression")continue;let u=l.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&WS.has(d)){o=!0;break}}let a=[];o&&a.push({startLine:0,endLine:s.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)",disposition:"exclude"});for(let c of s.namedChildren){let l=null,u=null;if(c.type==="function_declaration")l=c.namedChild(0)?.text??null,u=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(l=d.namedChild(0)?.text??null,u=d)}else if(c.type==="lexical_declaration"){let d=c.namedChild(0);if(d?.type==="variable_declarator"){let m=d.namedChild(0)?.text,f=d.namedChild(1);m&&(f?.type==="arrow_function"||f?.type==="function_expression")&&(l=m,u=d)}}l&&/^use[A-Z]/.test(l)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return a.push(...GS(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),co.set(r,a),a}function ZO(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of WS)if(e.includes(n)){t=!0;break}return t&&YO.test(e)?!0:e.includes("use")&&XO.test(e)}var ej=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function tj(e){return ej.test(e)}function GS(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(tj(u.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment",disposition:"exclude"});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 nj(e,t){let n=q(e,t);if(!n)return[];let r=co.get(n);if(r)return r;let i=[],o=rj(n);return o?(co.set(n,o),o):(zS(n.rootNode,i,!1,!1),i.push(...GS(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(...mj(n.rootNode)),co.set(n,i),i)}function rj(e){return gj(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function zS(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)",disposition:"implicit-usage"}),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)",disposition:"implicit-usage"})),e.type==="function_item"||e.type==="function_signature_item"?ij(e,t,n,r):r&&dj(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)",disposition:"implicit-usage"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?oj(e,t,n):e.type==="mod_item"&&gd(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)zS(s,t,i,o)}function ij(e,t,n,r){let i=gd(e),o=null;r?o={reason:"trait impl method (dynamic dispatch)",disposition:"implicit-usage"}:n&&(o={reason:"inside #[cfg(test)] mod",disposition:"exclude"});for(let s of i){if(VS(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=lj(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function oj(e,t,n){let r=gd(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(uj)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:i}),r.some(VS)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",disposition:"exclude",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",disposition:"exclude",containerName:i})}function gd(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 sj=new Set(["test","bench","tokio::test","async_std::test"]),aj=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),cj=new Set(["allow","warn","deny","forbid","cfg","cfg_attr","doc","inline","cold","must_use","deprecated","repr","derive","automatically_derived","non_exhaustive","path","link","link_section","global_allocator","panic_handler"]);function lj(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=fj(e);return t?sj.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:aj.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:cj.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function uj(e){return/#\[\s*derive\s*\(/.test(e)}function VS(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function dj(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function mj(e){let t=hj(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:'attribute `with = "..."` module - body may be invoked via reflection',disposition:"implicit-usage",containerName:i})}return n}function fj(e){let t=/^#!?\[\s*([A-Za-z_][A-Za-z0-9_]*(?:\s*::\s*[A-Za-z_][A-Za-z0-9_]*)*)/.exec(e);return t?t[1].replace(/\s+/g,""):null}function pj(e){return e==="#[tauri::command]"||e==="#[command]"||e==="#[wasm_bindgen]"||e==="#[no_mangle]"||e==="#[napi]"||e==="#[pyfunction]"||e==="#[pymethod]"||e==="#[pyo3]"||e==="#[doc(hidden)]"||e.startsWith("trait ")||e.startsWith("#[derive(<reflective>)]")||e.startsWith("#[derive(...)]")||e.startsWith('serde `with = "')||e.startsWith('attribute `with = "')||e.startsWith("Rust attribute macro #[")||e.startsWith("Rust ABI/export attribute #[")?"implicit-usage":"exclude"}function gj(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 HS=/\bwith\s*=\s*"([^"]+)"/g;function hj(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){HS.lastIndex=0;let r;for(;(r=HS.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function qS(e){let t=hd(e);return(n,r,i,o)=>t(n,r,i,o)?.disposition==="exclude"}function hd(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=US(e,r),s=new Map;for(let a of o){if(!a.containerName)continue;let c=s.get(a.containerName)??[];c.push(a),s.set(a.containerName,c)}return i={ranges:o,containers:s},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r),c=[];for(let u of a.ranges)i>=u.startLine&&i<=u.endLine&&c.push(u);let l=new Set;s&&l.add(s);for(let u of Cs(o))l.add(u);for(let u of l){let d=a.containers.get(u);d&&c.push(...d)}return yj(c)}}function yj(e){if(e.length===0)return null;let n=e.find(r=>r.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}function yd(e,t={}){xc(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function KS(e,t,n={}){xc(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function JS(e,t){if(t.isIgnoredPath(e.relativePath))return je("ignored-file");if(pn(e.symbol))return je("module-like-symbol");if(!ka(e.symbol))return je("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&ka(e.enclosingSymbol))return je("nested-non-callable-value");if(!t.includeTests&&!bj(e.relativePath))return je("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return je("excluded-file-region");let n=T(e.symbol);if(n==="<constructor>")return je("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return je("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return je("python-protocol-member")}return t.isDeclarationOnlyCallable()?je("declaration-only-callable"):t.isFrameworkContractCallable()?je("framework-contract-member"):Ie(e.symbol)?je("rust-trait-impl-member"):hr(e.symbol)?je("rust-test-module"):!t.includeMembers&&!Sj(e)?je("member"):e.endLine-e.startLine+1<t.minLoc?je("below-min-loc"):{accepted:!0}}function bj(e){return Y(e)!=="test"}function je(e){return{accepted:!1,rejectionReason:e}}function ka(e){return ee(e)||e.endsWith("().")||e.endsWith(".")}function Sj(e){return le(e.symbol)||Cs(e.symbol).length===0}function Pa(e,t){return O(e)-O(t)||e.relativePath.localeCompare(t.relativePath)}function se(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function zr(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 YS(){return new Map}function XS(e,t,n){let r=new Map;for(let i of ag(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||_a(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function QS(e,t,n,r={}){let i=new Set;if(r.conservative||n.size===0){for(let o of lg(e,t))i.add(o.symbol_id);return i}for(let o of cg(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||i.add(o.symbol_id);return i}function bd(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 Ta(e,t,n){let r=e.get(t);if(!r)return!1;for(let[i,o]of r)if(i!==n&&o.occurrences>0)return!0;return!1}function ZS(e){return e?.occurrences??0}function _a(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=tC(e,t,n);o.occurrences+=r,o.sources.add(i)}function eC(e,t,n,r,i){if(r<=0)return;let o=tC(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function tC(e,t,n){let r=e.get(t);r||(r=new Map,e.set(t,r));let i=r.get(n);return i||(i={occurrences:0,sources:new Set},r.set(n,i)),i}var Cj=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function Vr(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=q(e,t.relativePath);if(!n)return!1;let r=n.rootNode.descendantsOfType("method_definition").find(s=>s.startPosition.row<=t.startLine&&s.endPosition.row>=t.endLine);if(!r)return!1;if(/\boverride\b/.test(r.text.slice(0,Math.max(0,r.text.indexOf("{")))))return!0;let i=r.parent;for(;i&&i.type!=="class_declaration"&&i.type!=="class";)i=i.parent;if(!i)return!1;let o=i.text.slice(0,Math.max(0,i.text.indexOf("{")));return/\bimplements\b/.test(o)||/\bextends\b/.test(o)?!0:Cj.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}var xj=1e3,Rj=300;function sr(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=0,d=w("dead.candidates",()=>{let b=se(vj(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c);return u=b.length,b},()=>({definitions:u})),m=0,f=o?w("dead.inactive-barrels",()=>{let b=new Set(IS(e));return m=b.size,b},()=>({paths:m})):new Set,p=0,g=a?YS():w("dead.mention-reference-counts",()=>{let b=XS(e,f,d.map(v=>v.symbolId));return p=b.size,b},()=>({definitions:d.length,symbolsWithReferences:p})),y=0,h=a?w("dead.mentioned-symbol-ids",()=>{let b=QS(e,d.map(v=>v.symbolId),f,{conservative:f.size===0});return y=b.size,b},()=>({definitions:d.length,referencedSymbols:y})):new Set,C=a?d.filter(b=>!h.has(b.symbolId)):d.filter(b=>!Ta(g,b.symbolId,b.relativePath));a?w("dead.source-fallback.dead-code-only",()=>Tj(e,C,g,{inactiveBarrelPaths:f}),()=>({definitions:C.length,testReferencesIncluded:!0})):w("dead.source-fallback.ast",()=>Pj(e,C,g,{inactiveBarrelPaths:f}),()=>({definitions:C.length,testReferencesIncluded:!0}));let x=a?C.filter(b=>!bd(g,b.symbolId)):C.filter(b=>!Ta(g,b.symbolId,b.relativePath));w("dead.caller-map-supplement",()=>Aj(e,x,g,{inactiveBarrelPaths:f,includeSemantic:!a&&l}),()=>({definitions:x.length,semantic:!a&&l}));let S=a?C.filter(b=>!bd(g,b.symbolId)):d;return kj(e,Dj(S,g))}function vj(e,t){let n=qS(e),r=[];for(let i of Ri(e,{scope:t.scope,symbolMatches:ka,sqlPrefilter:"function-like"}))JS(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>wj(e,i),isFrameworkContractCallable:()=>Vr(e,i)}).accepted&&r.push(i);return r}var Ij=["method_signature","abstract_method_signature","call_signature","construct_signature"];function wj(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=q(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...Ij]).some(i=>i.startPosition.row<=t.startLine&&i.endPosition.row>=t.endLine);let r=Ce(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
|
|
511
|
+
`).trim();return r.endsWith(";")&&!r.includes("=>")&&!r.includes("{")}function Dj(e,t){return e.map(n=>Ej(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 Ej(e,t){let n=t.get(e.symbolId)??new Map,r=ZS(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,parent_type_name:e.parentTypeName,same_file_refs:r,cross_file_refs:i}}function kj(e,t){let n=hd(e),r=[],i=0,o=0,s=0,a=0,c=0,l=0;for(let u of t){if(e.isIgnored(u.relative_path))continue;if(Ee(e,u.relative_path)){a++;continue}if(de(e,u.symbol,u.relative_path)){c++;continue}let d=n(u.relative_path,u.start_line,u.symbol,u.parent_type_name),m=d?.disposition==="implicit-usage"?d.reason:void 0,f=m?"implicit-usage":u.same_file_refs===0?"dead-code":"file-internal";f==="dead-code"?i++:f==="file-internal"?o++:s++,l+=u.loc,r.push({relativePath:u.relative_path,startLine:u.start_line,endLine:u.end_line,loc:u.loc,symbol:u.symbol,shortName:I(u.symbol),sameFileRefs:u.same_file_refs,kind:f,...m?{implicitUsageReason:m}:{}})}return{symbols:r,counts:{total:r.length,deadCode:i,fileInternal:o,implicitUsage:s,loc:l},applicability:{entrySurfaceExcluded:a,externalRootExcluded:c,implicitUsageSignals:s},totalCount:r.length,deadCodeCount:i,fileInternalCount:o,implicitUsageCount:s,totalLoc:l}}function Pj(e,t,n,r){if(t.length===0)return;let i=new _(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 N(e))a.add(c);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>r.inactiveBarrelPaths.has(c)},c=>{o.has(c.target.symbolId)&&(Lj(e,c)||_a(n,c.target.symbolId,c.sourceFile,Nj(c),"source-fallback"))})}function Tj(e,t,n,r){if(t.length===0)return;let i=new _(e),o=_j(t),s=new Set(i.sourceFiles());for(let u of N(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=ks(e,u),c.set(u,d)),d};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.inactiveBarrelPaths.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let f=o.get(d);return f?Fj(u,d,f,()=>l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),KS(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&nC(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||_a(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function _j(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 Fj(e,t,n,r,i){let o=n.filter(l=>l.relativePath===e);if(o.length>0)return o;if(!i.permissive&&n.length===1)return[...n];let s=r(),a=s.get(t);if(a)for(let l of a){let u=n.filter(d=>Ve(l,d.relativePath));if(u.length>0)return u}let c=new Set;for(let l of s.values())for(let u of l)c.add(u);for(let l of c){let u=n.filter(d=>Ve(l,d.relativePath));if(u.length>0&&u.length===n.length)return u}return i.permissive?[...n]:[]}function Lj(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&nC(e,t)}function Nj(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function nC(e,t){return t.occurrences>1?!1:re(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function Aj(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=xj&&N(e).length>=Rj,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||r.inactiveBarrelPaths.has(d)||eC(n,u.symbolId,d,1,"caller-map")};if(o?w("dead.caller-map.per-symbol-non-semantic",()=>{for(let u of t){let d=xt(e,u,{semantic:!1,semanticEvidence:H});for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:!1})):w("dead.caller-map.per-symbol",()=>{for(let u of t){let d=xt(e,u,{semantic:i,semanticEvidence:H});if(d.length!==0)for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:i})),!o)return;let a=0,c=w("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!Ta(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return;let l=yy(e,c);for(let u of c){let d=l.get(u.symbolId);if(d)for(let m of d)s(u,m)}}function Mj(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[],a=e.all(`SELECT
|
|
512
512
|
gs.symbol,
|
|
513
513
|
COUNT(*) AS ref_count,
|
|
514
514
|
COUNT(DISTINCT ref_d.id) AS file_count,
|
|
@@ -532,14 +532,14 @@ Thumbs.db
|
|
|
532
532
|
${i}
|
|
533
533
|
GROUP BY gs.id
|
|
534
534
|
ORDER BY ref_count DESC
|
|
535
|
-
LIMIT ?`,...o,n).filter(c=>!e.isIgnored(c.defined_in)).map(c=>({symbol:c.symbol,shortName:I(c.symbol),refCount:c.ref_count,fileCount:c.file_count,definedIn:c.defined_in}));return a.length>0?a:
|
|
535
|
+
LIMIT ?`,...o,n).filter(c=>!e.isIgnored(c.defined_in)).map(c=>({symbol:c.symbol,shortName:I(c.symbol),refCount:c.ref_count,fileCount:c.file_count,definedIn:c.defined_in}));return a.length>0?a:Oj(e,r,n)}function Oj(e,t,n){return xe(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>jj(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function jj(e,t){let r=xt(e,t,{limit:500,semanticEvidence:H}).filter(i=>i.file!==t.relativePath);return{symbol:t.symbol,shortName:I(t.symbol),refCount:r.length,fileCount:new Set(r.map(i=>i.file)).size,definedIn:t.relativePath}}function Bj(e,t,n={}){return Jj(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function $j(e,t){let n=B(e,t),r=Wj(e,t);if(r.length>0&&!zj(n))return r;let i=Gj(e,t,n);return Sd(t)&&i.length>0?i:Vj([...r,...i])}function Hj(e,t,n={}){let r=Oe(e,t);if(!r)return[];let i=iC(e,r),o=n.semantic===!1?null:rC(e,r);return(o?Uj(o,i):i).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function Uj(e,t){let n=new Map;for(let i of t){let o=n.get(i.shortName);o?o.push(i):n.set(i.shortName,[i])}let r=e.map(i=>{let o=n.get(i.shortName),s=o?.shift();return o?.length===0&&n.delete(i.shortName),s?{...i,used:i.used||s.used}:i});return r.push(...[...n.values()].flat()),r}function Wj(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
|
|
536
536
|
FROM mentions m
|
|
537
537
|
JOIN chunks c ON m.chunk_id = c.id
|
|
538
538
|
JOIN documents d ON c.document_id = d.id
|
|
539
539
|
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
540
540
|
WHERE gs.symbol LIKE ?
|
|
541
541
|
AND m.role = 2
|
|
542
|
-
ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:I(r.symbol),fromFile:r.importer}))}function
|
|
542
|
+
ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:I(r.symbol),fromFile:r.importer}))}function Gj(e,t,n=B(e,t)){let r=n?.relativePath??null,i=n?T(n.symbol):t.replace(/\(\)$/,""),o=n?pn(n.symbol):!1,s=new Set;for(let c of N(e,{includeIgnored:!1}))for(let l of re(e,c))qj(l,c,{targetFile:r,targetLeaf:i,targetIsModule:o,targetPattern:t})&&s.add(c);let a=Sd(t)?t.trim():null;return[...s].sort().map(c=>({symbol:a??n?.symbol??i,shortName:a??(n?I(n.symbol):i),fromFile:c}))}function zj(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||M(e.relativePath)==="clojure"))}function Vj(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.fromFile}`;t.has(i)||(t.add(i),n.push(r))}return n.sort((r,i)=>r.fromFile.localeCompare(i.fromFile)||r.shortName.localeCompare(i.shortName))}function qj(e,t,n){return!e.sourcePath||n.targetFile&&te(e.sourcePath)!==te(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&Zj(t)||e.kind==="namespace"&&Kj(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function Kj(e,t){let n=t.trim().replace(/\(\)$/,"");return Sd(n)?e.importedName===n||e.localName===n:!1}function Sd(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function Jj(e,t,n={}){let r=Oe(e,t);return r?Yj(e,r,n)??(n.semantic===!1?null:rC(e,r))??iC(e,r):null}function Yj(e,t,n){let i=e.all(`SELECT DISTINCT
|
|
543
543
|
gs.symbol,
|
|
544
544
|
def_d.relative_path AS from_file,
|
|
545
545
|
imp_d.relative_path AS importer,
|
|
@@ -565,7 +565,7 @@ Thumbs.db
|
|
|
565
565
|
LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
566
566
|
WHERE imp_d.relative_path = ?
|
|
567
567
|
AND m.role = 2
|
|
568
|
-
ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:Wi(e,t);return i.map(s=>({symbol:s.symbol,shortName:I(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 rC(e,t){let n=Wi(e,t);return n.length>0?n.map(r=>{let i=oC(r.importedName,r.localName,r.kind);return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:r.kind==="side-effect"?!0:r.isUsed}}):null}function iC(e,t){let n=
|
|
568
|
+
ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:Wi(e,t);return i.map(s=>({symbol:s.symbol,shortName:I(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 rC(e,t){let n=Wi(e,t);return n.length>0?n.map(r=>{let i=oC(r.importedName,r.localName,r.kind);return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:r.kind==="side-effect"?!0:r.isUsed}}):null}function iC(e,t){let n=Xj(t,P(e,t));return re(e,t).map(r=>{let i=oC(r.importedName,r.localName,r.kind),o=r.kind==="side-effect"||Qj(t,r)||n.has(r.localName??r.importedName)?!0:r.used;return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:o}})}function Xj(e,t){let n=new Set;if(M(e)!=="python")return n;let r=/(?:^|\n)\s*__all__\s*(?:\+?=)\s*[[(]([\s\S]*?)[\])]/g;for(let i of t.matchAll(r)){let o=i[1]??"";for(let s of o.matchAll(/(['"])([A-Za-z_]\w*)\1/g))n.add(s[2])}return n}function Qj(e,t){if(M(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function oC(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 Zj(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function eB(e,t){let n=B(e,t);if(!n)return[];let i=new _(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>Rf(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:I(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:ue(o.symbol)??"unknown"}));return M(n.relativePath)!=="clojure"?i:nB(i,tB(e,n))}function tB(e,t){let n=T(t.symbol);if(!n)return[];let r=I(t.symbol);return(G(e,t.relativePath)?.clojureMembers??[]).filter(i=>i.ownerName===n).map(i=>({symbol:`${t.symbol}${i.memberName}().`,shortName:`${r}:${i.memberName}()`,startLine:i.startLine,endLine:i.endLine,kind:i.memberKind}))}function nB(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.shortName}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}function rB(e,t){let n=B(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
|
|
569
569
|
FROM mentions m
|
|
570
570
|
JOIN chunks c ON m.chunk_id = c.id
|
|
571
571
|
JOIN (
|
|
@@ -577,7 +577,7 @@ Thumbs.db
|
|
|
577
577
|
) sym_def ON sym_def.symbol_id = m.symbol_id
|
|
578
578
|
WHERE m.symbol_id = ?
|
|
579
579
|
AND m.role != 1
|
|
580
|
-
AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:I(n.symbol),count:r?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function
|
|
580
|
+
AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:I(n.symbol),count:r?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function iB(e,t){let n=Oe(e,t);if(!n)return[];let i=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
581
581
|
FROM mentions m
|
|
582
582
|
JOIN chunks c ON m.chunk_id = c.id
|
|
583
583
|
JOIN documents d ON c.document_id = d.id
|
|
@@ -594,7 +594,7 @@ Thumbs.db
|
|
|
594
594
|
AND m.role != 1
|
|
595
595
|
AND def_d.id != d.id
|
|
596
596
|
GROUP BY d.id
|
|
597
|
-
ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(i.length>0)return i;let s=ie(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function
|
|
597
|
+
ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(i.length>0)return i;let s=ie(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function oB(e,t={}){return sB(e,t).map(n=>({name:I(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function sB(e,t){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT gs.symbol,
|
|
598
598
|
COUNT(DISTINCT c.document_id) AS file_count,
|
|
599
599
|
def_d.relative_path AS defined_in
|
|
600
600
|
FROM mentions m
|
|
@@ -616,7 +616,7 @@ Thumbs.db
|
|
|
616
616
|
GROUP BY gs.id
|
|
617
617
|
HAVING file_count > 1
|
|
618
618
|
ORDER BY file_count DESC
|
|
619
|
-
LIMIT ?`,...o,n)}function
|
|
619
|
+
LIMIT ?`,...o,n)}function aB(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
620
620
|
FROM mentions m
|
|
621
621
|
JOIN chunks c ON m.chunk_id = c.id
|
|
622
622
|
JOIN documents d ON c.document_id = d.id
|
|
@@ -636,7 +636,7 @@ Thumbs.db
|
|
|
636
636
|
${i}
|
|
637
637
|
GROUP BY d.id
|
|
638
638
|
ORDER BY symbol_count DESC
|
|
639
|
-
LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}function
|
|
639
|
+
LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}function cB(e,t,n){let r=Oe(e,t)??t,i=Oe(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
|
|
640
640
|
FROM global_symbols gs
|
|
641
641
|
WHERE (
|
|
642
642
|
-- Defined in file1, referenced in file2
|
|
@@ -668,7 +668,7 @@ Thumbs.db
|
|
|
668
668
|
JOIN documents d ON c.document_id = d.id
|
|
669
669
|
WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
|
|
670
670
|
)
|
|
671
|
-
)`,r,i,i,r);return{...sC(r,i,o?.shared??0)}}function
|
|
671
|
+
)`,r,i,i,r);return{...sC(r,i,o?.shared??0)}}function lB(e,t={}){let{limit:n=20,scope:r}=t,i=r?"AND def_d.relative_path LIKE ? AND ref_d.relative_path LIKE ?":"",o=r?[`%${r}%`,`%${r}%`]:[];return e.all(`SELECT
|
|
672
672
|
def_d.relative_path AS file1,
|
|
673
673
|
ref_d.relative_path AS file2,
|
|
674
674
|
COUNT(DISTINCT gs.id) AS shared
|
|
@@ -690,7 +690,7 @@ Thumbs.db
|
|
|
690
690
|
${i}
|
|
691
691
|
GROUP BY def_d.id, ref_d.id
|
|
692
692
|
ORDER BY shared DESC
|
|
693
|
-
LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>sC(a.file1,a.file2,a.shared))}function sC(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 lo(e,t={}){return lC(e,t).cycles}function lC(e,t={}){let{scope:n,maxDepth:r=10}=t,i=ie(e,n,{scipEdges:"imports-only"}),o=[],s=new Set,a=new Set,c=[],l=!1;function u(m,f){if(f>r){l=!0;return}if(a.has(m)){let g=c.indexOf(m);if(g!==-1){let y=c.slice(g).concat(m),h=y.indexOf(y.reduce((S,b)=>S<b?S:b)),C=[...y.slice(h,-1),...y.slice(0,h),y[h]],x=C.join(" -> ");d.has(x)||(d.add(x),o.push({path:C,kind:lB(C)}))}return}if(s.has(m))return;s.add(m),a.add(m),c.push(m);let p=i.get(m);if(p)for(let g of p)u(g,f+1);c.pop(),a.delete(m)}let d=new Set;for(let m of i.keys())s.has(m)||u(m,0);return o.sort((m,f)=>m.kind!==f.kind?m.kind==="real"?-1:1:m.path.length-f.path.length),{cycles:o,truncated:l,maxDepth:r}}function lB(e){for(let r of e){let i=Y(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":Gr(t)||Gr(n)||aC(t,n)||aC(n,t)||cC(t,n)||cC(n,t)||Y(t)==="entry"||Y(n)==="entry"?"module-hierarchy":"real"}function aC(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 cC(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),o=t.split("/");if(i.length===o.length&&i.includes("tests")&&o.includes("src")){let s=i[i.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}import{readdirSync as uB}from"fs";import{join as uC}from"path";function ar(e,t){let n=Fa(e),r=Fa(t);if(n.endsWith("/**")){let i=n.slice(0,-3);return r===i||r.startsWith(`${i}/`)}if(n.endsWith("/*")){let i=n.slice(0,-2);if(!r.startsWith(`${i}/`))return!1;let o=r.slice(i.length+1);return o.length>0&&!o.includes("/")}return n==="**"?!0:n==="*"?r.length>0&&!r.includes("/"):n===r}function dB(e){return Fa(e).replace(/\/\*\*?$/,"")}function dC(e,t){let n=Fa(t),r=dB(n),i=n.endsWith("/**"),o=[],s=(a,c)=>{let l;try{l=uB(a,{withFileTypes:!0})}catch{return}for(let u of l){if(u.name.startsWith("."))continue;let d=c?`${c}/${u.name}`:u.name;ar(n,d)&&o.push(d),i&&u.isDirectory()&&s(uC(a,u.name),d)}};return s(uC(e,r),r),o.sort()}function Fa(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function La(e){let t=new Map,n=[],r=new Map,i=new Map,o=new Set,s=[],a=0,c=l=>(e.get(l)??[]).values();for(let l of e.keys()){if(r.has(l))continue;let u=[];for(r.set(l,a),i.set(l,a),a+=1,s.push(l),o.add(l),u.push({node:l,iter:c(l),pendingChild:null});u.length>0;){let d=u[u.length-1];if(d.pendingChild!==null){let p=d.pendingChild;d.pendingChild=null,i.set(d.node,Math.min(i.get(d.node),i.get(p)))}let m=d.iter.next();if(m.done){if(i.get(d.node)===r.get(d.node)){let p=[];for(;;){let g=s.pop();if(o.delete(g),p.push(g),t.set(g,n.length),g===d.node)break}n.push(p)}u.pop();continue}let f=m.value;r.has(f)?o.has(f)&&i.set(d.node,Math.min(i.get(d.node),r.get(f))):(r.set(f,a),i.set(f,a),a+=1,s.push(f),o.add(f),d.pendingChild=f,u.push({node:f,iter:c(f),pendingChild:null}))}}return{components:n,componentOf:t}}var cr="architecture:";function mC(e,t,n){let r=mB(e,t);if(!n||n.boundaries.length===0)return{configured:!1,boundaries:[],edges:[],forbiddenEdges:[],reciprocalPairs:[],cycles:[],coverage:{totalFiles:r.length,mappedFiles:0,unmappedFiles:[],ambiguousFiles:[]},policyCoverage:{declaredRows:0,totalBoundaries:0,missingRows:[],requiresCompletePolicy:!1}};let i=new Map,o=new Map(n.boundaries.map(h=>[h.name,new Set])),s=[],a=[];for(let h of r){let C=n.boundaries.filter(x=>x.paths.some(S=>ar(S,h))).map(x=>x.name).sort();if(C.length===0)s.push(h);else if(C.length>1)a.push({file:h,boundaries:C});else{let x=C[0];i.set(h,x),o.get(x).add(h)}}let c=new Map;for(let[h,C]of e){let x=i.get(h);if(x)for(let S of C){let b=i.get(S);if(!b||x===b)continue;let v=Cd(x,b),R=c.get(v);R||(R={from:x,to:b,fileEdges:[],importers:new Set,importedFiles:new Set},c.set(v,R)),R.fileEdges.push({fromFile:h,toFile:S}),R.importers.add(h),R.importedFiles.add(S)}}let l=[...c.values()].map(h=>fB(h,n)).sort(hB),u=new Map(l.map(h=>[Cd(h.from,h.to),h])),d=new Map(n.boundaries.map(h=>[h.name,new Set]));for(let h of l)d.get(h.from).add(h.to);let m=[];for(let h of l){if(h.from>=h.to)continue;let C=u.get(Cd(h.to,h.from));C&&m.push({boundaries:[h.from,h.to],forward:h,reverse:C})}let{components:f}=La(d),p=f.filter(h=>h.length>1).map(h=>gB(h,l,n.requireAcyclic===!0)).sort((h,C)=>C.boundaries.length-h.boundaries.length||h.boundaries.join("/").localeCompare(C.boundaries.join("/"))),g=n.allowedDependencies??{},y=n.boundaries.map(h=>h.name).filter(h=>!Object.hasOwn(g,h)).sort();return{configured:!0,boundaries:n.boundaries.map(h=>({name:h.name,paths:[...h.paths],fileCount:o.get(h.name).size,dependencyPolicyDeclared:Object.hasOwn(g,h.name)})).sort((h,C)=>h.name.localeCompare(C.name)),edges:l,forbiddenEdges:l.filter(h=>h.policyStatus==="forbidden"),reciprocalPairs:m,cycles:p,coverage:{totalFiles:r.length,mappedFiles:i.size,unmappedFiles:s,ambiguousFiles:a},policyCoverage:{declaredRows:n.boundaries.length-y.length,totalBoundaries:n.boundaries.length,missingRows:y,requiresCompletePolicy:n.requireCompletePolicy===!0}}}function qr(e,t={}){let n=ie(e,t.scope,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),r=N(e,{includeIgnored:!1}).filter(i=>!t.scope||i.includes(t.scope));return mC(n,r,e.config.architecture)}function xd(e){let t=e.forbiddenEdges.map(n=>`${cr}forbidden-edge:${encodeURIComponent(n.from)}:${encodeURIComponent(n.to)}`);if(e.policyCoverage.requiresCompletePolicy)for(let n of e.policyCoverage.missingRows)t.push(`${cr}missing-policy-row:${encodeURIComponent(n)}`);for(let n of e.cycles)n.violatesPolicy&&t.push(`${cr}cycle:${n.boundaries.map(r=>encodeURIComponent(r)).sort().join("|")}`);return[...new Set(t)].sort()}function fC(e){return!!e&&(Object.keys(e.allowedDependencies??{}).length>0||e.requireCompletePolicy===!0||e.requireAcyclic===!0)}function mB(e,t){let n=new Set(t);for(let[r,i]of e){n.add(r);for(let o of i)n.add(o)}return[...n].sort()}function fB(e,t){let n=[...e.fileEdges].sort((r,i)=>r.fromFile.localeCompare(i.fromFile)||r.toFile.localeCompare(i.toFile));return{from:e.from,to:e.to,policyStatus:pB(t,e.from,e.to),fileEdgeCount:n.length,importerCount:e.importers.size,importedFileCount:e.importedFiles.size,examples:n.slice(0,5)}}function pB(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function gB(e,t,n){let r=[...e].sort(),i=new Set(r),o=t.filter(a=>i.has(a.from)&&i.has(a.to)),s=Math.min(...o.map(a=>a.fileEdgeCount));return{boundaries:r,internalEdges:o,narrowestEdges:o.filter(a=>a.fileEdgeCount===s),violatesPolicy:n}}function Cd(e,t){return`${e}\0${t}`}function hB(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function yB(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new _(e);return se(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>bB(e,u,t.semantic!==!1)).filter(u=>u.fanIn>=i&&u.fanOut>=o).sort((u,d)=>d.score-u.score||d.fanIn-u.fanIn).slice(0,n)}function bB(e,t,n){let r=[...new Set(Ct(e,t,{limit:500,semantic:n,semanticEvidence:H}).map(l=>l.file))].sort(),i=new Map;for(let l of dt(e,t,{limit:500,semantic:n,semanticEvidence:H})){if(l.file===t.relativePath)continue;let u=`${l.symbol}|${l.file}`;i.has(u)||i.set(u,{symbol:l.symbol,shortName:I(l.symbol),file:l.file})}let o=[...i.values()].sort((l,u)=>l.file.localeCompare(u.file)||l.symbol.localeCompare(u.symbol)),s=r.length,a=o.length,c=s*a;return{symbol:t.symbol,shortName:I(t.symbol),fanIn:s,fanOut:a,callerFiles:r,externalCallees:o,score:c,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${s} incoming file(s) reference this symbol`,`${a} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${c} (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 uo(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new _(e),s=t.semantic!==!1,a=0,c=w("isolated.candidates",()=>{let v=se(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof i=="number"&&i>0}),i).filter(R=>!Vr(e,R));return a=v.length,v},()=>({definitions:a})),l=0,u=w("isolated.strict-callees",()=>{let b=o.symbolsWithNonSelfCallees(c,{additive:!1,semantic:!1});return l=b.size,b},()=>({definitions:c.length,symbols:l})),d=c.filter(b=>!u.has(b.symbolId)),m=0,f=w("isolated.scip-callers",()=>{let b=o.crossFileCallerMap(d,{semantic:!1});return m=b.size,b},()=>({definitions:d.length,symbols:m})),p=new Set(f.keys());for(let b of o.frameworkReferencedSymbolIds(d))p.add(b);let g=d.filter(b=>!p.has(b.symbolId));if(s&&g.length>0){for(let b of In(e,g).keys())p.add(b);for(let b of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))u.add(b);g=g.filter(b=>!p.has(b.symbolId)).filter(b=>!u.has(b.symbolId))}let y=0,h=w("isolated.source-fallback-callers",()=>{let b=o.sourceFallbackCallerFiles(g,{skipPath:v=>Y(v)==="test"});return y=b.size,b},()=>({definitions:g.length,symbols:y}));for(let b of h.keys())p.add(b);let C=g.filter(b=>!p.has(b.symbolId)),x=0,S=w("isolated.additive-callees",()=>{let b=o.symbolsWithNonSelfCallees(C,{additive:!0,semantic:s});return x=b.size,b},()=>({definitions:C.length,symbols:x}));for(let b of S)u.add(b);return C.filter(b=>!u.has(b.symbolId)).sort((b,v)=>O(v)-O(b)||b.relativePath.localeCompare(v.relativePath)||b.startLine-v.startLine).map(b=>({symbol:b.symbol,shortName:I(b.symbol),relativePath:b.relativePath,startLine:b.startLine,endLine:b.endLine,loc:O(b)}))}import{SymbolInformation_Kind as ke}from"@c4312/scip";var pC=500;function SB(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=_S.get(n);if(r!==void 0)return r;for(let[i,o]of wa)if(o.toLowerCase().includes(n))return i;return null}function CB(e,t,n={}){let{scope:r,limit:i=100}=n,o=SB(t);return o===null?[]:RB(e,r).map(a=>({row:a,resolvedKind:hC(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:I(a.symbol),kind:c,kindName:so(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function xB(e,t={}){let n=vB(e,t.scope);for(let r of IB(e,t.scope)){let i=hC(r);i===null||i===0||n.set(i,(n.get(i)??0)+1)}return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0]-i[0]).map(([r,i])=>({kind:r,kindName:so(r),count:i}))}function RB(e,t){return xe(e,{scope:t}).map(wB)}function vB(e,t){let n=new Map;for(let r of gC(N(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
|
|
693
|
+
LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>sC(a.file1,a.file2,a.shared))}function sC(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 lo(e,t={}){return lC(e,t).cycles}function lC(e,t={}){let{scope:n,maxDepth:r=10}=t,i=ie(e,n,{scipEdges:"imports-only"}),o=[],s=new Set,a=new Set,c=[],l=!1;function u(m,f){if(f>r){l=!0;return}if(a.has(m)){let g=c.indexOf(m);if(g!==-1){let y=c.slice(g).concat(m),h=y.indexOf(y.reduce((S,b)=>S<b?S:b)),C=[...y.slice(h,-1),...y.slice(0,h),y[h]],x=C.join(" -> ");d.has(x)||(d.add(x),o.push({path:C,kind:uB(C)}))}return}if(s.has(m))return;s.add(m),a.add(m),c.push(m);let p=i.get(m);if(p)for(let g of p)u(g,f+1);c.pop(),a.delete(m)}let d=new Set;for(let m of i.keys())s.has(m)||u(m,0);return o.sort((m,f)=>m.kind!==f.kind?m.kind==="real"?-1:1:m.path.length-f.path.length),{cycles:o,truncated:l,maxDepth:r}}function uB(e){for(let r of e){let i=Y(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":Gr(t)||Gr(n)||aC(t,n)||aC(n,t)||cC(t,n)||cC(n,t)||Y(t)==="entry"||Y(n)==="entry"?"module-hierarchy":"real"}function aC(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 cC(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),o=t.split("/");if(i.length===o.length&&i.includes("tests")&&o.includes("src")){let s=i[i.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}import{readdirSync as dB}from"fs";import{join as uC}from"path";function ar(e,t){let n=Fa(e),r=Fa(t);if(n.endsWith("/**")){let i=n.slice(0,-3);return r===i||r.startsWith(`${i}/`)}if(n.endsWith("/*")){let i=n.slice(0,-2);if(!r.startsWith(`${i}/`))return!1;let o=r.slice(i.length+1);return o.length>0&&!o.includes("/")}return n==="**"?!0:n==="*"?r.length>0&&!r.includes("/"):n===r}function mB(e){return Fa(e).replace(/\/\*\*?$/,"")}function dC(e,t){let n=Fa(t),r=mB(n),i=n.endsWith("/**"),o=[],s=(a,c)=>{let l;try{l=dB(a,{withFileTypes:!0})}catch{return}for(let u of l){if(u.name.startsWith("."))continue;let d=c?`${c}/${u.name}`:u.name;ar(n,d)&&o.push(d),i&&u.isDirectory()&&s(uC(a,u.name),d)}};return s(uC(e,r),r),o.sort()}function Fa(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function La(e){let t=new Map,n=[],r=new Map,i=new Map,o=new Set,s=[],a=0,c=l=>(e.get(l)??[]).values();for(let l of e.keys()){if(r.has(l))continue;let u=[];for(r.set(l,a),i.set(l,a),a+=1,s.push(l),o.add(l),u.push({node:l,iter:c(l),pendingChild:null});u.length>0;){let d=u[u.length-1];if(d.pendingChild!==null){let p=d.pendingChild;d.pendingChild=null,i.set(d.node,Math.min(i.get(d.node),i.get(p)))}let m=d.iter.next();if(m.done){if(i.get(d.node)===r.get(d.node)){let p=[];for(;;){let g=s.pop();if(o.delete(g),p.push(g),t.set(g,n.length),g===d.node)break}n.push(p)}u.pop();continue}let f=m.value;r.has(f)?o.has(f)&&i.set(d.node,Math.min(i.get(d.node),r.get(f))):(r.set(f,a),i.set(f,a),a+=1,s.push(f),o.add(f),d.pendingChild=f,u.push({node:f,iter:c(f),pendingChild:null}))}}return{components:n,componentOf:t}}var cr="architecture:";function mC(e,t,n){let r=fB(e,t);if(!n||n.boundaries.length===0)return{configured:!1,boundaries:[],edges:[],forbiddenEdges:[],reciprocalPairs:[],cycles:[],coverage:{totalFiles:r.length,mappedFiles:0,unmappedFiles:[],ambiguousFiles:[]},policyCoverage:{declaredRows:0,totalBoundaries:0,missingRows:[],requiresCompletePolicy:!1}};let i=new Map,o=new Map(n.boundaries.map(h=>[h.name,new Set])),s=[],a=[];for(let h of r){let C=n.boundaries.filter(x=>x.paths.some(S=>ar(S,h))).map(x=>x.name).sort();if(C.length===0)s.push(h);else if(C.length>1)a.push({file:h,boundaries:C});else{let x=C[0];i.set(h,x),o.get(x).add(h)}}let c=new Map;for(let[h,C]of e){let x=i.get(h);if(x)for(let S of C){let b=i.get(S);if(!b||x===b)continue;let v=Cd(x,b),R=c.get(v);R||(R={from:x,to:b,fileEdges:[],importers:new Set,importedFiles:new Set},c.set(v,R)),R.fileEdges.push({fromFile:h,toFile:S}),R.importers.add(h),R.importedFiles.add(S)}}let l=[...c.values()].map(h=>pB(h,n)).sort(yB),u=new Map(l.map(h=>[Cd(h.from,h.to),h])),d=new Map(n.boundaries.map(h=>[h.name,new Set]));for(let h of l)d.get(h.from).add(h.to);let m=[];for(let h of l){if(h.from>=h.to)continue;let C=u.get(Cd(h.to,h.from));C&&m.push({boundaries:[h.from,h.to],forward:h,reverse:C})}let{components:f}=La(d),p=f.filter(h=>h.length>1).map(h=>hB(h,l,n.requireAcyclic===!0)).sort((h,C)=>C.boundaries.length-h.boundaries.length||h.boundaries.join("/").localeCompare(C.boundaries.join("/"))),g=n.allowedDependencies??{},y=n.boundaries.map(h=>h.name).filter(h=>!Object.hasOwn(g,h)).sort();return{configured:!0,boundaries:n.boundaries.map(h=>({name:h.name,paths:[...h.paths],fileCount:o.get(h.name).size,dependencyPolicyDeclared:Object.hasOwn(g,h.name)})).sort((h,C)=>h.name.localeCompare(C.name)),edges:l,forbiddenEdges:l.filter(h=>h.policyStatus==="forbidden"),reciprocalPairs:m,cycles:p,coverage:{totalFiles:r.length,mappedFiles:i.size,unmappedFiles:s,ambiguousFiles:a},policyCoverage:{declaredRows:n.boundaries.length-y.length,totalBoundaries:n.boundaries.length,missingRows:y,requiresCompletePolicy:n.requireCompletePolicy===!0}}}function qr(e,t={}){let n=ie(e,t.scope,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),r=N(e,{includeIgnored:!1}).filter(i=>!t.scope||i.includes(t.scope));return mC(n,r,e.config.architecture)}function xd(e){let t=e.forbiddenEdges.map(n=>`${cr}forbidden-edge:${encodeURIComponent(n.from)}:${encodeURIComponent(n.to)}`);if(e.policyCoverage.requiresCompletePolicy)for(let n of e.policyCoverage.missingRows)t.push(`${cr}missing-policy-row:${encodeURIComponent(n)}`);for(let n of e.cycles)n.violatesPolicy&&t.push(`${cr}cycle:${n.boundaries.map(r=>encodeURIComponent(r)).sort().join("|")}`);return[...new Set(t)].sort()}function fC(e){return!!e&&(Object.keys(e.allowedDependencies??{}).length>0||e.requireCompletePolicy===!0||e.requireAcyclic===!0)}function fB(e,t){let n=new Set(t);for(let[r,i]of e){n.add(r);for(let o of i)n.add(o)}return[...n].sort()}function pB(e,t){let n=[...e.fileEdges].sort((r,i)=>r.fromFile.localeCompare(i.fromFile)||r.toFile.localeCompare(i.toFile));return{from:e.from,to:e.to,policyStatus:gB(t,e.from,e.to),fileEdgeCount:n.length,importerCount:e.importers.size,importedFileCount:e.importedFiles.size,examples:n.slice(0,5)}}function gB(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function hB(e,t,n){let r=[...e].sort(),i=new Set(r),o=t.filter(a=>i.has(a.from)&&i.has(a.to)),s=Math.min(...o.map(a=>a.fileEdgeCount));return{boundaries:r,internalEdges:o,narrowestEdges:o.filter(a=>a.fileEdgeCount===s),violatesPolicy:n}}function Cd(e,t){return`${e}\0${t}`}function yB(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function bB(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new _(e);return se(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>SB(e,u,t.semantic!==!1)).filter(u=>u.fanIn>=i&&u.fanOut>=o).sort((u,d)=>d.score-u.score||d.fanIn-u.fanIn).slice(0,n)}function SB(e,t,n){let r=[...new Set(xt(e,t,{limit:500,semantic:n,semanticEvidence:H}).map(l=>l.file))].sort(),i=new Map;for(let l of ft(e,t,{limit:500,semantic:n,semanticEvidence:H})){if(l.file===t.relativePath)continue;let u=`${l.symbol}|${l.file}`;i.has(u)||i.set(u,{symbol:l.symbol,shortName:I(l.symbol),file:l.file})}let o=[...i.values()].sort((l,u)=>l.file.localeCompare(u.file)||l.symbol.localeCompare(u.symbol)),s=r.length,a=o.length,c=s*a;return{symbol:t.symbol,shortName:I(t.symbol),fanIn:s,fanOut:a,callerFiles:r,externalCallees:o,score:c,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${s} incoming file(s) reference this symbol`,`${a} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${c} (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 uo(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new _(e),s=t.semantic!==!1,a=0,c=w("isolated.candidates",()=>{let v=se(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof i=="number"&&i>0}),i).filter(R=>!Vr(e,R));return a=v.length,v},()=>({definitions:a})),l=0,u=w("isolated.strict-callees",()=>{let b=o.symbolsWithNonSelfCallees(c,{additive:!1,semantic:!1});return l=b.size,b},()=>({definitions:c.length,symbols:l})),d=c.filter(b=>!u.has(b.symbolId)),m=0,f=w("isolated.scip-callers",()=>{let b=o.crossFileCallerMap(d,{semantic:!1});return m=b.size,b},()=>({definitions:d.length,symbols:m})),p=new Set(f.keys());for(let b of o.frameworkReferencedSymbolIds(d))p.add(b);let g=d.filter(b=>!p.has(b.symbolId));if(s&&g.length>0){for(let b of wn(e,g).keys())p.add(b);for(let b of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))u.add(b);g=g.filter(b=>!p.has(b.symbolId)).filter(b=>!u.has(b.symbolId))}let y=0,h=w("isolated.source-fallback-callers",()=>{let b=o.sourceFallbackCallerFiles(g,{skipPath:v=>Y(v)==="test"});return y=b.size,b},()=>({definitions:g.length,symbols:y}));for(let b of h.keys())p.add(b);let C=g.filter(b=>!p.has(b.symbolId)),x=0,S=w("isolated.additive-callees",()=>{let b=o.symbolsWithNonSelfCallees(C,{additive:!0,semantic:s});return x=b.size,b},()=>({definitions:C.length,symbols:x}));for(let b of S)u.add(b);return C.filter(b=>!u.has(b.symbolId)).sort((b,v)=>O(v)-O(b)||b.relativePath.localeCompare(v.relativePath)||b.startLine-v.startLine).map(b=>({symbol:b.symbol,shortName:I(b.symbol),relativePath:b.relativePath,startLine:b.startLine,endLine:b.endLine,loc:O(b)}))}import{SymbolInformation_Kind as ke}from"@c4312/scip";var pC=500;function CB(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=_S.get(n);if(r!==void 0)return r;for(let[i,o]of wa)if(o.toLowerCase().includes(n))return i;return null}function xB(e,t,n={}){let{scope:r,limit:i=100}=n,o=CB(t);return o===null?[]:vB(e,r).map(a=>({row:a,resolvedKind:hC(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:I(a.symbol),kind:c,kindName:so(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function RB(e,t={}){let n=IB(e,t.scope);for(let r of wB(e,t.scope)){let i=hC(r);i===null||i===0||n.set(i,(n.get(i)??0)+1)}return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0]-i[0]).map(([r,i])=>({kind:r,kindName:so(r),count:i}))}function vB(e,t){return xe(e,{scope:t}).map(DB)}function IB(e,t){let n=new Map;for(let r of gC(N(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
|
|
694
694
|
FROM defn_enclosing_ranges der
|
|
695
695
|
JOIN global_symbols gs ON der.symbol_id = gs.id
|
|
696
696
|
JOIN documents d ON der.document_id = d.id
|
|
@@ -698,7 +698,7 @@ Thumbs.db
|
|
|
698
698
|
AND gs.kind != 0
|
|
699
699
|
AND gs.symbol NOT LIKE '%#'
|
|
700
700
|
AND d.relative_path IN (${i})
|
|
701
|
-
GROUP BY gs.kind`,...r);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function
|
|
701
|
+
GROUP BY gs.kind`,...r);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function wB(e,t){let n=[];for(let r of gC(N(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
|
|
702
702
|
gs.kind,
|
|
703
703
|
gs.documentation,
|
|
704
704
|
gs.enclosing_symbol,
|
|
@@ -711,11 +711,11 @@ Thumbs.db
|
|
|
711
711
|
WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
|
|
712
712
|
${e.symbolNoiseFor("gs")}
|
|
713
713
|
AND d.relative_path IN (${i})
|
|
714
|
-
ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...r))}return n}function gC(e){let t=[];for(let n=0;n<e.length;n+=pC)t.push(e.slice(n,n+pC));return t}function
|
|
715
|
-
WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:I(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:I(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=ye(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 p=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:p,shortName:p,depth:m})}return u}function Rd(e,t,n={}){let r=B(e,t);if(!r)return null;let i=n.semantic!==!1,o=Ct(e,r,{semantic:i,semanticEvidence:H}).filter(a=>ee(a.symbol)).slice(0,50),s=zr(dt(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i,semanticEvidence:H}));return{symbol:r.symbol,shortName:I(r.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:I(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:I(a.symbol),file:a.file}))}}function mt(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function Pe(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function kn(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 yC(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 vd(e,t){if(t<=0)return new Map;let n=new Map;for(let[r,i]of e)i>0&&n.set(r,Math.log(t/i));return n}function Kr(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 Jr(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function bC(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??Kr(n),c=[],l=[];for(let m of e){let f=n.get(m)??0;o+=f*f,t.has(m)&&(i+=f*f,f>=a?c.push(m):l.push(m))}if(c.length===0&&l.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let f=n.get(m)??0;s+=f*f}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?i/u:0;return c.sort((m,f)=>(n.get(f)??0)-(n.get(m)??0)),{similarity:d,significantShared:c,trivialShared:l}}function SC(e,t,n,r){let i=0,o=r.medianIdf??Kr(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;i+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let c=r.magnitudeA*r.magnitudeB,l=c>0?i/c:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:l,significantShared:s,trivialShared:a}}function Na(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=HB(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!ee(o.symbol))return[];if(o.callees.size===0)return CC(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=NB(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):CC(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"})}function Ed(e,t,n,r={}){let i=B(e,t),o=B(e,n);if(!i||!o)return null;let s=Na(e,i.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:r.semantic,scanLimit:r.scanLimit}).find(l=>l.symbolB===o.symbol||l.symbolA===o.symbol);if(!s)return null;let a=i.endLine-i.startLine+1,c=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:I(i.symbol),file:i.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:I(o.symbol),file:o.relativePath,loc:c},similarity:s.similarity,similarityBasis:s.similarityBasis??"callees",sharedEvidence:s.sharedCallees,uniqueToA:s.uniqueToA,uniqueToB:s.uniqueToB,evidenceClass:s.evidenceClass,actionTier:s.actionTier,recommendation:s.recommendation,consolidationStrategy:LB(s)}}function LB(e){let t=e.similarityBasis==="source-tokens"?"source-token":"tracked callee";return e.sharedCallees.length===0?`No shared ${t} evidence survived similar's weighting. Inspect the source before attempting consolidation.`:e.uniqueToA.length===0&&e.uniqueToB.length===0?`The functions have identical ${t} evidence under similar's weighting. Verify signatures, guards, and return values before consolidating.`:e.uniqueToA.length===0?`A's ${t} evidence is a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic first.`:e.uniqueToB.length===0?`B's ${t} evidence is a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic first.`:e.uniqueToA.length<=2&&e.uniqueToB.length<=2?`Create a shared helper around the ${e.sharedCallees.length} shared ${t}(s). Pass the ${e.uniqueToA.length+e.uniqueToB.length} divergent point(s) as parameters or callbacks.`:`Extract the ${e.sharedCallees.length} shared ${t}(s) into a common helper. Keep each function's unique logic outside that helper (${e.uniqueToA.length} item(s) in A, ${e.uniqueToB.length} in B).`}function NB(e,t,n,r){let i=Yr(e).calleeIndex({minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=JB(t,i.corpus),s=VB(o,i),a=AB(o,i),c=Kr(a),l=Jr(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let m=Jr(d.callees,a),f=IC(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:l,magnitudeB:m});f&&u.push(f)}return u.sort((d,m)=>m.similarity-d.similarity),u}function AB(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return vd(n,t.corpus.length+1)}function IC(e,t,n,r){let i=OB(e,t,n,r);if(!jB(i,r))return null;let{similarity:o,significantShared:s,trivialShared:a}=i,c=s.length>0?s:a,l=PC(c,"callees");return{symbolA:e.symbol,shortNameA:I(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:I(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(I),uniqueToA:[...Pe(e.callees,t.callees)].map(I),uniqueToB:[...Pe(t.callees,e.callees)].map(I),...l}}function MB(e,t,n,r){let i=r.magnitudeA??Jr(e.callees,n),o=r.magnitudeB??Jr(t.callees,n),s=0,a=0,c=0,l=r.medianIdf??Kr(n);for(let m of e.callees){if(!t.callees.has(m))continue;let f=n.get(m)??0;s+=f*f,c+=1,f>=l&&(a+=1)}if(c===0)return!1;let u=i*o;return(u>0?s/u:0)<r.minSimilarity?!1:a>=r.requireSignificantShared||c>=r.requireSharedCount}function OB(e,t,n,r){return r.magnitudeA===void 0||r.magnitudeB===void 0?bC(e.callees,t.callees,n,{medianIdf:r.medianIdf}):SC(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB})}function jB(e,t){if(e.similarity<t.minSimilarity)return!1;let n=e.significantShared.length+e.trivialShared.length;return e.significantShared.length>=t.requireSignificantShared||n>=t.requireSharedCount}function mo(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=t.semantic!==!1,l=U(),u=0,d=0,m=0,f=0,p=0,g=0,y=0;return w("similar.all",()=>{let C=Yr(e).calleeIndex({minCallees:o,scope:i,scanLimit:a,semantic:c}),x=C.corpus;u=x.length;let S=t.focusFiles,b=[],v=0;return w("similar.all.pair-scan",()=>{for(let R=0;R<x.length;R+=1){let E=x[R],D=S?.has(E.file)??!1,k=C.weightedMagnitudes[R],L=new Set;for(let ne of E.callees){let X=C.candidateIndexesByCallee.get(ne);if(X)for(let F of X)F<=R||S&&!D&&!S.has(x[F].file)||L.add(F)}l&&(m+=L.size,L.size>0&&(d+=1));for(let ne of L){let X=x[ne];if(s&&E.file===X.file){l&&(p+=1);continue}if(wC(E,X)){l&&(g+=1);continue}l&&(f+=1);let F=IC(E,X,C.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:C.medianIdf,magnitudeA:k,magnitudeB:C.weightedMagnitudes[ne]});F&&(BB(b,F,r,v),l&&(y+=1),v+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:y,topResults:b.length})),w("similar.all.sort-project",()=>(b.sort((R,E)=>E.result.similarity-R.result.similarity||R.order-E.order),b.map(R=>R.result)),()=>({topResults:b.length}))},()=>({minSimilarity:n,limit:r,scope:i,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:y}))}function kd(e,t={}){let{minSimilarity:n=.5,scope:r,minCallees:i=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=U(),l=0,u=0,d=0,m=0,f=0,p=0,g=0;return w("similar.all-count",()=>{let h=Yr(e).calleeIndex({minCallees:i,scope:r,scanLimit:s,semantic:a}),C=h.corpus;l=C.length;let x=t.focusFiles;return w("similar.all-count.pair-scan",()=>{for(let S=0;S<C.length;S+=1){let b=C[S],v=x?.has(b.file)??!1,R=h.weightedMagnitudes[S],E=new Set;for(let D of b.callees){let k=h.candidateIndexesByCallee.get(D);if(k)for(let L of k)L<=S||x&&!v&&!x.has(C[L].file)||E.add(L)}c&&(d+=E.size,E.size>0&&(u+=1));for(let D of E){let k=C[D];if(o&&b.file===k.file){c&&(f+=1);continue}if(wC(b,k)){c&&(p+=1);continue}c&&(m+=1),MB(b,k,h.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:h.medianIdf,magnitudeA:R,magnitudeB:h.weightedMagnitudes[D]})&&(g+=1)}}},()=>({corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g})),g},()=>({minSimilarity:n,scope:r,minCallees:i,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g}))}function wC(e,t){if(e.paramCount<0||t.paramCount<0)return!1;let n=Math.abs(e.paramCount-t.paramCount),r=Math.max(2,Math.ceil(Math.max(e.paramCount,t.paramCount)*.5));return n>r}var DC=oe({kind:"source-fingerprints",invalidation:K("source-fingerprints"),serialize:g$,deserialize:p$});function BB(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 $B=["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 HB(e,t,n){let r=B(e,t);if(!r||!ee(r.symbol))return null;let i=new _(e),o=dt(e,r,{semantic:n.semantic,semanticEvidence:H});return{symbol:r.symbol,file:r.relativePath,callees:Aa(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var UB=J("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),WB=J("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function EC(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=UB.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=!0,u=0,d=0;return w("similar.callee-fingerprints.resolve",()=>{let m=a.get(c);if(l=m!==void 0,m||(m=qB(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,m)),u=m.length,i===void 0)return m;let f=m.filter(p=>p.symbol!==i);return d=m.length-f.length,f},()=>({minCallees:n,scope:r,scanLimit:o,semantic:s,cacheHit:l,corpusSize:u,excludeSymbol:i!==void 0,excludedSymbols:d}))}function GB(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=WB.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=!0,l=0,u=0,d=0;return w("similar.callee-index.resolve",()=>{let m=s.get(a);return c=m!==void 0,m||(m=zB(EC(e,{minCallees:n,scope:r,scanLimit:i,semantic:o})),s.set(a,m)),l=m.corpus.length,u=m.docFreq.size,d=m.candidateIndexesByCallee.size,m},()=>({minCallees:n,scope:r,scanLimit:i,semantic:o,cacheHit:c,corpusSize:l,indexedCallees:u,candidateBuckets:d}))}function Yr(e){return{calleeCorpus:t=>EC(e,t),calleeIndex:t=>GB(e,t),sourceCorpus:(t={})=>NC(e,t),sourceIndex:(t={})=>vC(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?s$(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):o$(t,vC(e,{scanLimit:n.scanLimit}))}}function zB(e){let t=U(),n=0,r=w("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let f of e)for(let p of f.callees)m.set(p,(m.get(p)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),i=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=w("similar.callee-index.idf-weights",()=>vd(r,e.length),()=>({corpusSize:e.length,uniqueCallees:r.size})),s=w("similar.callee-index.weighted-magnitudes",()=>e.map(m=>Jr(m.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,u=w("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let f=0;f<e.length;f+=1){let p=e[f];for(let g of p.callees){if((r.get(g)??0)>i){t&&(c+=1);continue}let y=m.get(g);y||(y=[],m.set(g,y)),y.push(f),t&&(a+=1)}}return t&&(l=m.size),m},()=>({corpusSize:e.length,buckets:l,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:i})),d=w("similar.callee-index.median-idf",()=>Kr(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:r,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:i}}function VB(e,t){let n=new Map;for(let r of e.callees)for(let i of t.candidateIndexesByCallee.get(r)??[]){let o=t.corpus[i];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function qB(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=U(),a=new _(e),c=0,l=w("similar.callee-fingerprints.candidates",()=>{let g=se(a.productionCallableDefinitions({scope:r,minLoc:5,sortByLocDesc:typeof i=="number"&&i>0}),i);return c=g.length,g},()=>({scope:r,scanLimit:i,candidateCount:c})),u=0,d=w("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeMap(l,{semantic:o});if(s)for(let y of g.values())u+=y.length;return g},()=>({candidateCount:c,semantic:o,calleeEdges:u})),m=0,f=0,p=0;return w("similar.callee-fingerprints.shape",()=>{let g=l.map(C=>({symbol:C.symbol,file:C.relativePath,callees:Aa((d.get(C.symbolId)??[]).map(x=>x.symbol)),paramCount:a.callableSignature(C)?.paramCount??-1})),y=KB(g);s&&(p=y.filter((C,x)=>C.callees.size!==g[x].callees.size).length);let h=y.filter(C=>C.callees.size>=n);return m=h.length,s&&(f=h.reduce((C,x)=>C+x.callees.size,0)),h},()=>({candidateCount:c,fingerprintCount:m,retainedCalleeCount:f,minCallees:n,siblingSaturatedFingerprints:p}))}var kC=5;function KB(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=new Map,t.set(n.file,r));for(let i of n.callees)r.set(i,(r.get(i)??0)+1)}return e.map(n=>{let r=t.get(n.file);if(!r)return n;let i=[...n.callees].filter(s=>(r.get(s)??0)>=kC);if(i.length===0)return n;let o=new Set(n.callees);for(let s of i)o.delete(s);return{...n,callees:o}})}function JB(e,t){let n=new Map;for(let o of t)if(!(o.file!==e.file||o.symbol===e.symbol))for(let s of o.callees)n.set(s,(n.get(s)??0)+1);let r=[...e.callees].filter(o=>(n.get(o)??0)+1>=kC);if(r.length===0)return e;let i=new Set(e.callees);for(let o of r)i.delete(o);return{...e,callees:i}}function Aa(e){return new Set([...e].filter(t=>!YB(t)))}function YB(e){return $B.some(t=>e.includes(t))}function CC(e,t,n){let r=e$(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,c=0,l=0,u=0;return w("similar.source-shape",()=>{let m=Yr(e).sourceCandidates(r,{minSimilarity:i,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let f of m){if(f.symbol===r.symbol||f.tokens.size<3)continue;c+=1;let p=mt(r.tokens,f.tokens);if(p.size<2){l+=1;continue}let g=new Set([...r.tokens,...f.tokens]),y=g.size>0?p.size/g.size:0;if(y<i){u+=1;continue}o.push({symbolA:r.symbol,shortNameA:I(r.symbol),fileA:r.file,symbolB:f.symbol,shortNameB:I(f.symbol),fileB:f.file,similarity:y,similarityBasis:"source-tokens",sharedCallees:[...p].sort(),uniqueToA:[...Pe(r.tokens,f.tokens)].sort(),uniqueToB:[...Pe(f.tokens,r.tokens)].sort(),...PC([...p],"source-tokens")})}return o.sort((f,p)=>p.similarity-f.similarity||f.shortNameB.localeCompare(p.shortNameB)),o.slice(0,n.limit)},()=>({symbol:r.symbol,file:r.file,targetTokens:r.tokens.size,candidateMode:s,candidates:a,comparedPairs:c,sharedSkips:l,similaritySkips:u,results:o.length}))}function PC(e,t){let n=e.flatMap(wd),r=e.flatMap(y=>xC(y,t)),i=Id(n,TC),o=Id(n,_C),s=Id(r,Dd),a=[...new Set(r.filter(RC))],c=e.filter(y=>{let h=xC(y,t);return h.some(C=>Dd.has(C))&&h.some(RC)}).length,l=[];i.length>0&&l.push(`access/query scaffolding: ${i.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(y=>FC.has(y));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=i.length+o.length>0,f=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,p=f?"domain-behavior":d?m?"mixed":"domain-behavior":i.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";p==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=p==="domain-behavior"&&(e.length>=3||f)?"direct":"signal";return{evidenceClass:p,actionTier:g,evidenceClassReasons:l,recommendation:XB(p,g)}}function XB(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 Id(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function wd(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function xC(e,t){if(t==="source-tokens")return wd(e);let n=T(e);return wd(n.length>0?n:QB(e))}function QB(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(r=>r.trim()).filter(r=>/[A-Za-z]/.test(r)).at(-1)?.replace(/\.$/,"")??e}function RC(e){return e.length>3&&!Dd.has(e)&&!TC.has(e)&&!_C.has(e)&&!FC.has(e)&&!ZB.has(e)}var Dd=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),TC=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),_C=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"]),FC=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),ZB=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 e$(e,t){let n=B(e,t);if(!n||!ee(n.symbol))return null;let r=t$(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function t$(e,t){let n=T(t.symbol),r=d$(e,t.relativePath,t.startLine,t.endLine,n),i=OC(r,n);return i.size>0?i:null}var n$=J("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),r$=J("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function LC(e){return`${e.scanLimit??""}`}function NC(e,t={}){let n=n$.get(e,()=>new Map),r=LC(t),i=n.get(r);return i||(i=u$(e,t),n.set(r,i)),i}function vC(e,t={}){let n=r$.get(e,()=>new Map),r=LC(t),i=n.get(r);return i||(i=i$(NC(e,t)),n.set(r,i)),i}function i$(e){let t=new Map;for(let i of e)for(let o of i.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),r=new Map;for(let i of e)for(let o of i.tokens){if((t.get(o)??0)>n)continue;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}return{corpus:e,candidateByToken:r,docFreq:t,ubiquityThreshold:n}}function o$(e,t){let n=new Map;for(let r of e.tokens)for(let i of t.candidateByToken.get(r)??[])i.symbol!==e.symbol&&n.set(i.symbol,i);return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function s$(e,t,n){let r=U(),i=new _(e),o=a$(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=w("similar.source-shape.target-files",()=>{let p=[...t.tokens],g=[];for(let y of N(e,{includeIgnored:!1})){s+=1;let h=P(e,y);h&&(a+=1,c$(h,p,o)&&g.push(y))}return c=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:c})),u=0,d=w("similar.source-shape.target-definitions",()=>{let p=se(i.productionCallableDefinitions({files:l,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=p.length,p},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:u})),m=0;return w("similar.source-shape.target-fingerprints",()=>{let p=AC(e,d);return r&&(m=p.length),p},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(p=>p.symbol!==t.symbol)}function a$(e,t){return Math.max(2,Math.ceil(e*t))}function c$(e,t,n){if(t.length<n)return!1;let r=e.toLowerCase(),i=0;for(let o of t)if(l$(r,o)&&(i+=1,i>=n))return!0;return!1}function l$(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function u$(e,t={}){let n=new _(e),{scanLimit:r}=t,i=se(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}),r);return AC(e,i)}function AC(e,t){let n=new Map;for(let i of t){let o=n.get(i.relativePath)??[];o.push(i),n.set(i.relativePath,o)}let r=new Map;for(let[i,o]of n){let s=P(e,i);if(!s)continue;let a=ce(e,i,s),c=f$(e,i,a),l=!1,u=null;for(let d of o){let m=m$(d),f=c.get(m),p=f?new Set(f.tokens):null;p||(u??=Ce(e,i),p=OC(MC(u,d.startLine,d.endLine,d.leaf),d.leaf),c.set(m,{key:m,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...p].sort()}),l=!0),p.size>0&&r.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:p})}l&&h$(e,i,a,c)}return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function d$(e,t,n,r,i){let o=Ce(e,t);return o.length===0?"":MC(o,n,r,i)}function MC(e,t,n,r){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
|
|
716
|
-
`);let i=[new RegExp(`\\bdef\\s+${$(r)}\\b`),new RegExp(`\\bfun\\s+${$(r)}\\b`),new RegExp(`\\bfn\\s+${$(r)}\\b`),new RegExp(`\\bfunction\\s+${$(r)}\\b`),new RegExp(`\\b${$(r)}\\s*\\(`)],o=e.findIndex(s=>i.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let c=e[a]??"";if(a>o&&
|
|
714
|
+
ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...r))}return n}function gC(e){let t=[];for(let n=0;n<e.length;n+=pC)t.push(e.slice(n,n+pC));return t}function DB(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 hC(e){return e.kind!==null&&e.kind!==0?EB(e.kind,e.symbol,e.documentation):kB(e.symbol,e.documentation,e.enclosing_symbol)}function EB(e,t,n){let r=(n??"").toLowerCase();if(ue(t)==="type"){if(r.includes("type "))return ke.TypeAlias;if(r.includes("interface "))return ke.Interface;if(r.includes("struct "))return ke.Struct;if(r.includes("trait "))return ke.Trait;if(r.includes("class "))return ke.Class}return e}function kB(e,t,n){let r=ye(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=ue(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?ke.TypeAlias:a.includes("interface ")?ke.Interface:a.includes("struct ")?ke.Struct:a.includes("trait ")?ke.Trait:a.includes("class ")?ke.Class:ke.Class:s==="method"?o?.suffix==="type"?ke.Method:ke.Function:s==="namespace"?ke.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?ke.Function:(n?ue(n):o?.suffix??null)==="type"?ke.Field:ke.Variable}function PB(e,t={}){let{limit:n=10,scope:r,minDepth:i=3}=t,o=ie(e,r),{components:s,componentOf:a}=La(o),c=new Map;for(let g=0;g<s.length;g++)c.set(g,new Set);for(let[g,y]of o){let h=a.get(g);for(let C of y){let x=a.get(C);x!==h&&c.get(h).add(x)}}let l=new Array(s.length),u=new Array(s.length);for(let g=0;g<s.length;g++){let y=[],h=0;for(let C of c.get(g)){let x=u[C];x>h&&(h=x,y=l[C])}l[g]=[g,...y],u[g]=1+h}function d(g){return l[g]}let m=s.map(g=>[...g].sort()),f=new Set,p=[];for(let g=0;g<s.length;g++){let h=d(g).map(S=>m[S]),C=h.map(S=>S[0]);if(h.length<i)continue;let x=C.join(" ");f.has(x)||(f.add(x),p.push(TB(C,h)))}return p.sort((g,y)=>y.depth-g.depth),_B(p).slice(0,n)}function TB(e,t){let n=t.reduce((i,o)=>i+o.length,0),r=t.filter(i=>i.length>1).length;return{chain:e,components:t,depth:t.length,fileCount:n,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${t.length} condensed dependency component(s) form the representative transitive path`,`${n} file(s) are represented; ${r} component(s) contain a dependency cycle`,"cycles count once toward depth and retain their full membership separately"],recommendation:"Review whether the chain crosses ownership or layer boundaries; shorten it only when the dependency direction is accidental."}}function _B(e){let t=[];for(let n of e)t.some(r=>FB(n.chain,r.chain))||t.push(n);return t}function FB(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let r=0;r<e.length;r++)if(e[r]!==t[n+r])return!1;return!0}function LB(e,t){let n=B(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
|
|
715
|
+
WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:I(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:I(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=ye(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 p=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:p,shortName:p,depth:m})}return u}function Rd(e,t,n={}){let r=B(e,t);if(!r)return null;let i=n.semantic!==!1,o=xt(e,r,{semantic:i,semanticEvidence:H}).filter(a=>ee(a.symbol)).slice(0,50),s=zr(ft(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i,semanticEvidence:H}));return{symbol:r.symbol,shortName:I(r.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:I(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:I(a.symbol),file:a.file}))}}function pt(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function Pe(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function Pn(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 yC(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 vd(e,t){if(t<=0)return new Map;let n=new Map;for(let[r,i]of e)i>0&&n.set(r,Math.log(t/i));return n}function Kr(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 Jr(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function bC(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??Kr(n),c=[],l=[];for(let m of e){let f=n.get(m)??0;o+=f*f,t.has(m)&&(i+=f*f,f>=a?c.push(m):l.push(m))}if(c.length===0&&l.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let f=n.get(m)??0;s+=f*f}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?i/u:0;return c.sort((m,f)=>(n.get(f)??0)-(n.get(m)??0)),{similarity:d,significantShared:c,trivialShared:l}}function SC(e,t,n,r){let i=0,o=r.medianIdf??Kr(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;i+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let c=r.magnitudeA*r.magnitudeB,l=c>0?i/c:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:l,significantShared:s,trivialShared:a}}function Na(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=UB(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!ee(o.symbol))return[];if(o.callees.size===0)return CC(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=AB(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):CC(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"})}function Ed(e,t,n,r={}){let i=B(e,t),o=B(e,n);if(!i||!o)return null;let s=Na(e,i.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:r.semantic,scanLimit:r.scanLimit}).find(l=>l.symbolB===o.symbol||l.symbolA===o.symbol);if(!s)return null;let a=i.endLine-i.startLine+1,c=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:I(i.symbol),file:i.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:I(o.symbol),file:o.relativePath,loc:c},similarity:s.similarity,similarityBasis:s.similarityBasis??"callees",sharedEvidence:s.sharedCallees,uniqueToA:s.uniqueToA,uniqueToB:s.uniqueToB,evidenceClass:s.evidenceClass,actionTier:s.actionTier,recommendation:s.recommendation,consolidationStrategy:NB(s)}}function NB(e){let t=e.similarityBasis==="source-tokens"?"source-token":"tracked callee";return e.sharedCallees.length===0?`No shared ${t} evidence survived similar's weighting. Inspect the source before attempting consolidation.`:e.uniqueToA.length===0&&e.uniqueToB.length===0?`The functions have identical ${t} evidence under similar's weighting. Verify signatures, guards, and return values before consolidating.`:e.uniqueToA.length===0?`A's ${t} evidence is a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic first.`:e.uniqueToB.length===0?`B's ${t} evidence is a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic first.`:e.uniqueToA.length<=2&&e.uniqueToB.length<=2?`Create a shared helper around the ${e.sharedCallees.length} shared ${t}(s). Pass the ${e.uniqueToA.length+e.uniqueToB.length} divergent point(s) as parameters or callbacks.`:`Extract the ${e.sharedCallees.length} shared ${t}(s) into a common helper. Keep each function's unique logic outside that helper (${e.uniqueToA.length} item(s) in A, ${e.uniqueToB.length} in B).`}function AB(e,t,n,r){let i=Yr(e).calleeIndex({minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=YB(t,i.corpus),s=qB(o,i),a=MB(o,i),c=Kr(a),l=Jr(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let m=Jr(d.callees,a),f=IC(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:l,magnitudeB:m});f&&u.push(f)}return u.sort((d,m)=>m.similarity-d.similarity),u}function MB(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return vd(n,t.corpus.length+1)}function IC(e,t,n,r){let i=jB(e,t,n,r);if(!BB(i,r))return null;let{similarity:o,significantShared:s,trivialShared:a}=i,c=s.length>0?s:a,l=PC(c,"callees");return{symbolA:e.symbol,shortNameA:I(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:I(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(I),uniqueToA:[...Pe(e.callees,t.callees)].map(I),uniqueToB:[...Pe(t.callees,e.callees)].map(I),...l}}function OB(e,t,n,r){let i=r.magnitudeA??Jr(e.callees,n),o=r.magnitudeB??Jr(t.callees,n),s=0,a=0,c=0,l=r.medianIdf??Kr(n);for(let m of e.callees){if(!t.callees.has(m))continue;let f=n.get(m)??0;s+=f*f,c+=1,f>=l&&(a+=1)}if(c===0)return!1;let u=i*o;return(u>0?s/u:0)<r.minSimilarity?!1:a>=r.requireSignificantShared||c>=r.requireSharedCount}function jB(e,t,n,r){return r.magnitudeA===void 0||r.magnitudeB===void 0?bC(e.callees,t.callees,n,{medianIdf:r.medianIdf}):SC(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB})}function BB(e,t){if(e.similarity<t.minSimilarity)return!1;let n=e.significantShared.length+e.trivialShared.length;return e.significantShared.length>=t.requireSignificantShared||n>=t.requireSharedCount}function mo(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=t.semantic!==!1,l=U(),u=0,d=0,m=0,f=0,p=0,g=0,y=0;return w("similar.all",()=>{let C=Yr(e).calleeIndex({minCallees:o,scope:i,scanLimit:a,semantic:c}),x=C.corpus;u=x.length;let S=t.focusFiles,b=[],v=0;return w("similar.all.pair-scan",()=>{for(let R=0;R<x.length;R+=1){let E=x[R],D=S?.has(E.file)??!1,k=C.weightedMagnitudes[R],L=new Set;for(let ne of E.callees){let X=C.candidateIndexesByCallee.get(ne);if(X)for(let F of X)F<=R||S&&!D&&!S.has(x[F].file)||L.add(F)}l&&(m+=L.size,L.size>0&&(d+=1));for(let ne of L){let X=x[ne];if(s&&E.file===X.file){l&&(p+=1);continue}if(wC(E,X)){l&&(g+=1);continue}l&&(f+=1);let F=IC(E,X,C.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:C.medianIdf,magnitudeA:k,magnitudeB:C.weightedMagnitudes[ne]});F&&($B(b,F,r,v),l&&(y+=1),v+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:y,topResults:b.length})),w("similar.all.sort-project",()=>(b.sort((R,E)=>E.result.similarity-R.result.similarity||R.order-E.order),b.map(R=>R.result)),()=>({topResults:b.length}))},()=>({minSimilarity:n,limit:r,scope:i,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:y}))}function kd(e,t={}){let{minSimilarity:n=.5,scope:r,minCallees:i=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=U(),l=0,u=0,d=0,m=0,f=0,p=0,g=0;return w("similar.all-count",()=>{let h=Yr(e).calleeIndex({minCallees:i,scope:r,scanLimit:s,semantic:a}),C=h.corpus;l=C.length;let x=t.focusFiles;return w("similar.all-count.pair-scan",()=>{for(let S=0;S<C.length;S+=1){let b=C[S],v=x?.has(b.file)??!1,R=h.weightedMagnitudes[S],E=new Set;for(let D of b.callees){let k=h.candidateIndexesByCallee.get(D);if(k)for(let L of k)L<=S||x&&!v&&!x.has(C[L].file)||E.add(L)}c&&(d+=E.size,E.size>0&&(u+=1));for(let D of E){let k=C[D];if(o&&b.file===k.file){c&&(f+=1);continue}if(wC(b,k)){c&&(p+=1);continue}c&&(m+=1),OB(b,k,h.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:h.medianIdf,magnitudeA:R,magnitudeB:h.weightedMagnitudes[D]})&&(g+=1)}}},()=>({corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g})),g},()=>({minSimilarity:n,scope:r,minCallees:i,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g}))}function wC(e,t){if(e.paramCount<0||t.paramCount<0)return!1;let n=Math.abs(e.paramCount-t.paramCount),r=Math.max(2,Math.ceil(Math.max(e.paramCount,t.paramCount)*.5));return n>r}var DC=oe({kind:"source-fingerprints",invalidation:K("source-fingerprints"),serialize:h$,deserialize:g$});function $B(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 HB=["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 UB(e,t,n){let r=B(e,t);if(!r||!ee(r.symbol))return null;let i=new _(e),o=ft(e,r,{semantic:n.semantic,semanticEvidence:H});return{symbol:r.symbol,file:r.relativePath,callees:Aa(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var WB=J("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),GB=J("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function EC(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=WB.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=!0,u=0,d=0;return w("similar.callee-fingerprints.resolve",()=>{let m=a.get(c);if(l=m!==void 0,m||(m=KB(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,m)),u=m.length,i===void 0)return m;let f=m.filter(p=>p.symbol!==i);return d=m.length-f.length,f},()=>({minCallees:n,scope:r,scanLimit:o,semantic:s,cacheHit:l,corpusSize:u,excludeSymbol:i!==void 0,excludedSymbols:d}))}function zB(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=GB.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=!0,l=0,u=0,d=0;return w("similar.callee-index.resolve",()=>{let m=s.get(a);return c=m!==void 0,m||(m=VB(EC(e,{minCallees:n,scope:r,scanLimit:i,semantic:o})),s.set(a,m)),l=m.corpus.length,u=m.docFreq.size,d=m.candidateIndexesByCallee.size,m},()=>({minCallees:n,scope:r,scanLimit:i,semantic:o,cacheHit:c,corpusSize:l,indexedCallees:u,candidateBuckets:d}))}function Yr(e){return{calleeCorpus:t=>EC(e,t),calleeIndex:t=>zB(e,t),sourceCorpus:(t={})=>NC(e,t),sourceIndex:(t={})=>vC(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?a$(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):s$(t,vC(e,{scanLimit:n.scanLimit}))}}function VB(e){let t=U(),n=0,r=w("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let f of e)for(let p of f.callees)m.set(p,(m.get(p)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),i=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=w("similar.callee-index.idf-weights",()=>vd(r,e.length),()=>({corpusSize:e.length,uniqueCallees:r.size})),s=w("similar.callee-index.weighted-magnitudes",()=>e.map(m=>Jr(m.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,u=w("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let f=0;f<e.length;f+=1){let p=e[f];for(let g of p.callees){if((r.get(g)??0)>i){t&&(c+=1);continue}let y=m.get(g);y||(y=[],m.set(g,y)),y.push(f),t&&(a+=1)}}return t&&(l=m.size),m},()=>({corpusSize:e.length,buckets:l,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:i})),d=w("similar.callee-index.median-idf",()=>Kr(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:r,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:i}}function qB(e,t){let n=new Map;for(let r of e.callees)for(let i of t.candidateIndexesByCallee.get(r)??[]){let o=t.corpus[i];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function KB(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=U(),a=new _(e),c=0,l=w("similar.callee-fingerprints.candidates",()=>{let g=se(a.productionCallableDefinitions({scope:r,minLoc:5,sortByLocDesc:typeof i=="number"&&i>0}),i);return c=g.length,g},()=>({scope:r,scanLimit:i,candidateCount:c})),u=0,d=w("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeMap(l,{semantic:o});if(s)for(let y of g.values())u+=y.length;return g},()=>({candidateCount:c,semantic:o,calleeEdges:u})),m=0,f=0,p=0;return w("similar.callee-fingerprints.shape",()=>{let g=l.map(C=>({symbol:C.symbol,file:C.relativePath,callees:Aa((d.get(C.symbolId)??[]).map(x=>x.symbol)),paramCount:a.callableSignature(C)?.paramCount??-1})),y=JB(g);s&&(p=y.filter((C,x)=>C.callees.size!==g[x].callees.size).length);let h=y.filter(C=>C.callees.size>=n);return m=h.length,s&&(f=h.reduce((C,x)=>C+x.callees.size,0)),h},()=>({candidateCount:c,fingerprintCount:m,retainedCalleeCount:f,minCallees:n,siblingSaturatedFingerprints:p}))}var kC=5;function JB(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=new Map,t.set(n.file,r));for(let i of n.callees)r.set(i,(r.get(i)??0)+1)}return e.map(n=>{let r=t.get(n.file);if(!r)return n;let i=[...n.callees].filter(s=>(r.get(s)??0)>=kC);if(i.length===0)return n;let o=new Set(n.callees);for(let s of i)o.delete(s);return{...n,callees:o}})}function YB(e,t){let n=new Map;for(let o of t)if(!(o.file!==e.file||o.symbol===e.symbol))for(let s of o.callees)n.set(s,(n.get(s)??0)+1);let r=[...e.callees].filter(o=>(n.get(o)??0)+1>=kC);if(r.length===0)return e;let i=new Set(e.callees);for(let o of r)i.delete(o);return{...e,callees:i}}function Aa(e){return new Set([...e].filter(t=>!XB(t)))}function XB(e){return HB.some(t=>e.includes(t))}function CC(e,t,n){let r=t$(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,c=0,l=0,u=0;return w("similar.source-shape",()=>{let m=Yr(e).sourceCandidates(r,{minSimilarity:i,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let f of m){if(f.symbol===r.symbol||f.tokens.size<3)continue;c+=1;let p=pt(r.tokens,f.tokens);if(p.size<2){l+=1;continue}let g=new Set([...r.tokens,...f.tokens]),y=g.size>0?p.size/g.size:0;if(y<i){u+=1;continue}o.push({symbolA:r.symbol,shortNameA:I(r.symbol),fileA:r.file,symbolB:f.symbol,shortNameB:I(f.symbol),fileB:f.file,similarity:y,similarityBasis:"source-tokens",sharedCallees:[...p].sort(),uniqueToA:[...Pe(r.tokens,f.tokens)].sort(),uniqueToB:[...Pe(f.tokens,r.tokens)].sort(),...PC([...p],"source-tokens")})}return o.sort((f,p)=>p.similarity-f.similarity||f.shortNameB.localeCompare(p.shortNameB)),o.slice(0,n.limit)},()=>({symbol:r.symbol,file:r.file,targetTokens:r.tokens.size,candidateMode:s,candidates:a,comparedPairs:c,sharedSkips:l,similaritySkips:u,results:o.length}))}function PC(e,t){let n=e.flatMap(wd),r=e.flatMap(y=>xC(y,t)),i=Id(n,TC),o=Id(n,_C),s=Id(r,Dd),a=[...new Set(r.filter(RC))],c=e.filter(y=>{let h=xC(y,t);return h.some(C=>Dd.has(C))&&h.some(RC)}).length,l=[];i.length>0&&l.push(`access/query scaffolding: ${i.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(y=>FC.has(y));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=i.length+o.length>0,f=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,p=f?"domain-behavior":d?m?"mixed":"domain-behavior":i.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";p==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=p==="domain-behavior"&&(e.length>=3||f)?"direct":"signal";return{evidenceClass:p,actionTier:g,evidenceClassReasons:l,recommendation:QB(p,g)}}function QB(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 Id(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function wd(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function xC(e,t){if(t==="source-tokens")return wd(e);let n=T(e);return wd(n.length>0?n:ZB(e))}function ZB(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(r=>r.trim()).filter(r=>/[A-Za-z]/.test(r)).at(-1)?.replace(/\.$/,"")??e}function RC(e){return e.length>3&&!Dd.has(e)&&!TC.has(e)&&!_C.has(e)&&!FC.has(e)&&!e$.has(e)}var Dd=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),TC=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),_C=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"]),FC=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),e$=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 t$(e,t){let n=B(e,t);if(!n||!ee(n.symbol))return null;let r=n$(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function n$(e,t){let n=T(t.symbol),r=m$(e,t.relativePath,t.startLine,t.endLine,n),i=OC(r,n);return i.size>0?i:null}var r$=J("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),i$=J("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function LC(e){return`${e.scanLimit??""}`}function NC(e,t={}){let n=r$.get(e,()=>new Map),r=LC(t),i=n.get(r);return i||(i=d$(e,t),n.set(r,i)),i}function vC(e,t={}){let n=i$.get(e,()=>new Map),r=LC(t),i=n.get(r);return i||(i=o$(NC(e,t)),n.set(r,i)),i}function o$(e){let t=new Map;for(let i of e)for(let o of i.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),r=new Map;for(let i of e)for(let o of i.tokens){if((t.get(o)??0)>n)continue;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}return{corpus:e,candidateByToken:r,docFreq:t,ubiquityThreshold:n}}function s$(e,t){let n=new Map;for(let r of e.tokens)for(let i of t.candidateByToken.get(r)??[])i.symbol!==e.symbol&&n.set(i.symbol,i);return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function a$(e,t,n){let r=U(),i=new _(e),o=c$(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=w("similar.source-shape.target-files",()=>{let p=[...t.tokens],g=[];for(let y of N(e,{includeIgnored:!1})){s+=1;let h=P(e,y);h&&(a+=1,l$(h,p,o)&&g.push(y))}return c=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:c})),u=0,d=w("similar.source-shape.target-definitions",()=>{let p=se(i.productionCallableDefinitions({files:l,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=p.length,p},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:u})),m=0;return w("similar.source-shape.target-fingerprints",()=>{let p=AC(e,d);return r&&(m=p.length),p},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(p=>p.symbol!==t.symbol)}function c$(e,t){return Math.max(2,Math.ceil(e*t))}function l$(e,t,n){if(t.length<n)return!1;let r=e.toLowerCase(),i=0;for(let o of t)if(u$(r,o)&&(i+=1,i>=n))return!0;return!1}function u$(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function d$(e,t={}){let n=new _(e),{scanLimit:r}=t,i=se(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}),r);return AC(e,i)}function AC(e,t){let n=new Map;for(let i of t){let o=n.get(i.relativePath)??[];o.push(i),n.set(i.relativePath,o)}let r=new Map;for(let[i,o]of n){let s=P(e,i);if(!s)continue;let a=ce(e,i,s),c=p$(e,i,a),l=!1,u=null;for(let d of o){let m=f$(d),f=c.get(m),p=f?new Set(f.tokens):null;p||(u??=Ce(e,i),p=OC(MC(u,d.startLine,d.endLine,d.leaf),d.leaf),c.set(m,{key:m,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...p].sort()}),l=!0),p.size>0&&r.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:p})}l&&y$(e,i,a,c)}return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function m$(e,t,n,r,i){let o=Ce(e,t);return o.length===0?"":MC(o,n,r,i)}function MC(e,t,n,r){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
|
|
716
|
+
`);let i=[new RegExp(`\\bdef\\s+${$(r)}\\b`),new RegExp(`\\bfun\\s+${$(r)}\\b`),new RegExp(`\\bfn\\s+${$(r)}\\b`),new RegExp(`\\bfunction\\s+${$(r)}\\b`),new RegExp(`\\b${$(r)}\\s*\\(`)],o=e.findIndex(s=>i.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let c=e[a]??"";if(a>o&&S$(c)||(s=a,c.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
|
|
717
717
|
`)}return e.slice(t,Math.min(e.length,t+8)).join(`
|
|
718
|
-
`)}function m$(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function f$(e,t,n){return DC.read(e,t,n)??new Map}function p$(e){try{let t=JSON.parse(e);if(!Array.isArray(t.entries))return null;let n=new Map;for(let r of t.entries){if(!r||typeof r.key!="string"||typeof r.symbol!="string"||typeof r.startLine!="number"||typeof r.endLine!="number"||typeof r.leaf!="string"||!Array.isArray(r.tokens)||!r.tokens.every(i=>typeof i=="string"))return null;n.set(r.key,r)}return n}catch{return null}}function g$(e){let t={entries:[...e.values()].sort((n,r)=>n.key.localeCompare(r.key))};return JSON.stringify(t)}function h$(e,t,n,r){DC.write(e,t,n,new Map(r))}function OC(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=y$(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 y$(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 b$(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Lt(e,t){let n=new Map;return e.forEach((r,i)=>{let o=new Set;for(let s of t(r)){if(o.has(s))continue;o.add(s);let a=n.get(s);a?a.push(i):n.set(s,[i])}}),{candidatesFor:(r,i)=>{let o=new Set;for(let s of t(r)){let a=n.get(s);if(a)for(let c of a)c!==i&&o.add(c)}return[...o].sort((s,a)=>s-a)}}}function Nt(e){let t=jC(e.profile?.name),n=()=>{let r=[];t=jC(e.profile?.name,e);let i=(s,a)=>{let c=e.profiles[s],l=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let u=e.compare(c,l);u&&r.push(u)};if(e.filePattern){let s=e.profiles.findIndex(a=>a.file.includes(e.filePattern));if(s>=0){let a=e.profiles[s];for(let c of S$(e,s)){let l=e.profiles[c];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(l.file)||i(s,c)}}}else if(e.focusFiles?.size!==0){let s=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let a=0;a<e.profiles.length;a+=1){let c=e.profiles[a],l=e.focusFiles?.has(c.file)??!1;for(let u of C$(e,a))e.focusFiles&&!l&&!e.focusFiles.has(e.profiles[u].file)||i(a,u);if(r.length>s){t.overrunApplied=!0;break}}}r.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=r.length;let o=r.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?w(`pairwise-profile:${e.profile.name}`,n,()=>({...x$(e.profile?.metadata),...t})):n()}function S$(e,t){if(e.candidateIndex)return BC(e,t,-1);let n=[];for(let r=0;r<e.profiles.length;r+=1)r!==t&&n.push(r);return n}function C$(e,t){if(e.candidateIndex)return BC(e,t,t);let n=[];for(let r=t+1;r<e.profiles.length;r+=1)n.push(r);return n}function BC(e,t,n){let r=e.profiles[t],i=new Set;for(let o of e.candidateIndex?.candidatesFor(r,t,e.profiles)??[])o<=n||o!==t&&(o<0||o>=e.profiles.length||i.add(o));return[...i].sort((o,s)=>o-s)}function jC(e,t){return{pipeline:e,profileCount:t?.profiles.length??0,focusedProfileCount:t?.focusFiles?t.profiles.filter(n=>t.focusFiles.has(n.file)).length:0,candidatePairs:0,comparedPairs:0,matchedResults:0,emittedResults:0,candidateIndexApplied:t?.candidateIndex!==void 0,focusApplied:t?.focusFiles!==void 0,filePatternApplied:t?.filePattern!==void 0,overrunApplied:!1}}function x$(e){return typeof e=="function"?e():e??{}}function R$(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=v$(e,{scope:i,minDeps:s}),l=Lt(a,u=>u.deps);return Nt({profiles:a,limit:r,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(u,d)=>w$(u,d,n,c)})}function v$(e,t){let{scope:n,minDeps:r}=t,i=ie(e,n),{universalDeps:o,distinctiveDeps:s}=I$(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 I$(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 w$(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=kn(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 Pn(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&$C(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)D$(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,$C(l.fallbackBucket,n,r));let i=t.length>0,o=n.length>0,s=r.length>0,a=i?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...r,...n].slice(0,6),recommendation:e.recommendation(a)}}function Ma(e,t){if(e.size===0||t.size===0)return 0;let i=mt(e,t).size/Math.min(e.size,t.size)*Math.min(1,Math.min(e.size,t.size)/(.35*Math.max(e.size,t.size)));return Math.max(kn(e,t),i)}function Tn(e,t){let n=Object.fromEntries(e.map(r=>[r.name,r.count]));for(let r of t)if(Object.entries(r.min).every(([o,s])=>(n[o]??0)>=s))return{pass:!0,reason:r.reason,counts:n};return{pass:!1,reason:"shared tokens did not meet calibrated overlap thresholds",counts:n}}function Oa(e,t,n){let r=t.map(c=>{let l=c.value(e),u=c.weightedValue?c.weightedValue(e,l):l;return{axis:c,value:l,weighted:u,qualifies:c.qualifies?c.qualifies(e,l):l>0}}),i=r.filter(c=>c.qualifies&&c.axis.reason).map(c=>c.axis.reason(e,c.value)),o=r.filter(c=>c.qualifies&&c.axis.dominantEligible!==!1).sort((c,l)=>l.weighted-c.weighted)[0],s=o&&o.weighted>0?o.axis.axis:n,a=[...new Set(r.filter(c=>c.qualifies).map(c=>c.axis.axis).concat(i.length>0?[]:[s]))];return{dominantPressure:s,pressureKinds:a,reasons:i}}function V(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function Le(e){return[...e].sort()}function D$(e,t,n,r,i,o){let s=[],a=[];for(let c of e)E$(c,r).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&i.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function E$(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let r of t)n=n.replace(r,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function $C(e,t,n){return e==="generic"?t:n}function fo(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=nt(e).reactProfiles({scope:o,minJsxTokens:r,scanLimit:s}).filter(d=>d.kind==="component").map(d=>({file:d.file,component:d.name,tokens:d.jsxTokens,profile:d})),u=Lt(l,d=>d.tokens);return Nt({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,m)=>k$(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.componentA.localeCompare(m.componentA)||d.fileB.localeCompare(m.fileB)||d.componentB.localeCompare(m.componentB)})}function k$(e,t,n){let r=mt(e.tokens,t.tokens);if(r.size<6||!P$(r))return null;let i=kn(e.tokens,t.tokens);if(i<n)return null;let o=V(r,"component:"),s=V(r,"native:"),a=V(r,"prop:"),c=V(r,"event:"),l=V(r,"binding:"),u=T$({sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Le(r),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:Le(Pe(e.tokens,t.tokens)).slice(0,25),uniqueToB:Le(Pe(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function P$(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 Tn([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function T$(e){return Pn({genericWords:F$,primitiveGroups:[{values:e.sharedNativeTags,reasonPrefix:"shared native tags",bucket:"generic"},{values:e.sharedProps,reasonPrefix:"shared props",bucket:"generic"},{values:e.sharedEvents,reasonPrefix:"shared events",bucket:"generic"}],nameGroups:[{names:e.sharedComponents,label:"shared component",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"}],recommendation:_$})}function _$(e){switch(e){case"domain-behavior":case"mixed":return"Review for a shared component or feature-specific UI primitive around the named domain structure.";case"shared-abstraction":return"Review the existing shared component usage first; extract only if duplicated structure remains outside it.";case"generic-workflow-scaffolding":return"Generic structural overlap \u2014 verify intent before consolidating."}}var F$=new Set(["actions","app","button","card","children","content","container","dialog","field","form","header","input","item","label","layout","list","modal","page","panel","row","section","shell","table","text","toolbar","ui","value","view","wrapper"]);function po(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=nt(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,component:d.name,tokens:d.behaviorTokens,profile:d})),u=Lt(l,d=>d.tokens);return Nt({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,m)=>L$(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.componentA.localeCompare(m.componentA)||d.fileB.localeCompare(m.fileB)||d.componentB.localeCompare(m.componentB)})}function L$(e,t,n,r){let i=mt(e.tokens,t.tokens);if(i.size<r||!M$(i))return null;let o=Ma(e.tokens,t.tokens);if(o<n)return null;let s=V(i,"hook:"),a=V(i,"react-hook:"),c=V(i,"effect:"),l=V(i,"state:"),u=V(i,"request:"),d=V(i,"handler:"),m=V(i,"handler-verb:"),f=N$({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,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Le(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:f.evidenceClass,actionTier:f.actionTier,evidenceClassReasons:f.reasons,recommendation:f.recommendation,uniqueToA:Le(Pe(e.tokens,t.tokens)).slice(0,25),uniqueToB:Le(Pe(t.tokens,e.tokens)).slice(0,25),reason:O$({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function N$(e){return Pn({genericWords:j$,stripPrefixes:B$,primitiveGroups:[{values:e.sharedReactHooks,reasonPrefix:"shared React primitives",bucket:"generic"},{values:e.sharedEffects,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedHooks,label:"shared hook",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedState,label:"shared state",fallbackBucket:"generic"},{names:e.sharedHandlers,label:"shared handler",fallbackBucket:"generic"},{names:e.sharedHandlerVerbs,label:"shared action verb",fallbackBucket:"generic"}],recommendation:A$})}function A$(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 M$(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 Tn([{name:"requests",count:i},{name:"customHooks",count:t},{name:"namedStates",count:s},{name:"handlers",count:o},{name:"effects",count:r},{name:"reactHooks",count:n},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{customHooks:1,requests:1,namedBehavior:5},reason:"shared custom hook and request workflow"},{min:{customHooks:1,namedStates:1,namedBehavior:5},reason:"shared custom hook and state"},{min:{customHooks:1,handlers:2,namedBehavior:5},reason:"shared custom hook and handlers"},{min:{namedStates:1,handlers:2,effects:1,namedBehavior:5},reason:"shared stateful effects"},{min:{namedStates:1,handlers:2,reactHooks:2,namedBehavior:5},reason:"shared stateful React primitives"}]).pass}function O$(e){let t=[];return e.sharedHooks.length&&t.push(`shared hooks: ${e.sharedHooks.join(", ")}`),e.sharedReactHooks.length&&t.push(`shared React hooks: ${e.sharedReactHooks.join(", ")}`),e.sharedEffects.length&&t.push(`shared effects: ${e.sharedEffects.join(", ")}`),e.sharedState.length&&t.push(`shared state: ${e.sharedState.join(", ")}`),e.sharedRequests.length&&t.push(`shared requests: ${e.sharedRequests.join(", ")}`),e.sharedHandlers.length&&t.push(`shared handlers: ${e.sharedHandlers.slice(0,6).join(", ")}`),e.sharedHandlerVerbs.length&&t.push(`shared action verbs: ${e.sharedHandlerVerbs.slice(0,6).join(", ")}`),t.join("; ")||"shared React behavior profile"}var j$=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"]),B$=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function Pd(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 nt(e).reactProfiles({scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>$$(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 $$(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),r=Oa(e,H$({minComponentLines:t.minComponentLines,minFileLines:t.minFileLines,minJsxTokens:t.minJsxTokens,minBehaviorTokens:t.minBehaviorTokens,substantialComponentLines:n}),"component"),{reasons:i}=r;if(i.length===0)return null;let o=r.dominantPressure,s=r.pressureKinds,a=U$(e),c=W$(o,s,a);return{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:o,pressureKinds:s,contextKind:a,recommendationKind:c,recommendation:G$(c,a),reasons:i,loc:e.loc}}function H$(e){return[{axis:"component",value:t=>t.loc,qualifies:(t,n)=>n>=e.minComponentLines,reason:(t,n)=>`${n} component line(s)`},{axis:"file",value:t=>t.fileLines,qualifies:(t,n)=>n>=e.minFileLines&&t.loc>=e.substantialComponentLines,reason:(t,n)=>`${n} file line(s)`},{axis:"jsx-structure",value:t=>t.jsxTokens.size,weightedValue:(t,n)=>n*3,qualifies:(t,n)=>n>=e.minJsxTokens,reason:(t,n)=>`${n} JSX structure token(s)`},{axis:"hook-behavior",value:t=>t.behaviorTokens.size,weightedValue:(t,n)=>n*4,qualifies:(t,n)=>n>=e.minBehaviorTokens,reason:(t,n)=>`${n} behavior token(s)`}]}function U$(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(m=>m.toLowerCase()),r=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),o=n.findIndex(m=>V$.has(m))>=0,s=n.some(m=>z$.has(m));if(HC(r)||HC(e.name))return"component";let c=q$.has(r.toLowerCase()),l=/(?:Page|Route|Screen)$/.test(e.name),u=o&&/View$/.test(e.name),d=!s&&r.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===e.name.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(r);return c||l||u||d?"route-page":"component"}function HC(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&UC.has(t.at(-1))?!0:[...UC].some(n=>e.endsWith(K$(n)))}function W$(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 G$(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 z$=new Set(["component","components","panel","panels","partial","partials"]),UC=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"]),V$=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),q$=new Set(["page","route","screen"]);function K$(e){return e.charAt(0).toUpperCase()+e.slice(1)}function go(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=J$(e,{scope:o,minTokens:r,scanLimit:s}),u=Lt(l,d=>d.tokens);return Nt({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,m)=>X$(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function J$(e,t){return nt(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:Y$(n)}))}function Y$(e){return e.totalLines}function X$(e,t,n){let r=mt(e.tokens,t.tokens);if(r.size<6||!Q$(r))return null;let i=kn(e.tokens,t.tokens);if(i<n)return null;let o=V(r,"component:"),s=V(r,"prop:"),a=V(r,"event:"),c=V(r,"directive:"),l=V(r,"slot:"),u=V(r,"id:"),d=Z$({sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u});return{fileA:e.file,fileB:t.file,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Le(r),sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u,evidenceClass:d.evidenceClass,actionTier:d.actionTier,evidenceClassReasons:d.reasons,recommendation:d.recommendation,uniqueToA:Le(Pe(e.tokens,t.tokens)).slice(0,25),uniqueToB:Le(Pe(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function Q$(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 Tn([{name:"component",count:t},{name:"behavior",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{behavior:3},reason:"shared Vue template structure"}]).pass}function Z$(e){return Pn({genericWords:t1,primitiveGroups:[{values:e.sharedProps,reasonPrefix:"shared props",bucket:"generic"},{values:e.sharedEvents,reasonPrefix:"shared events",bucket:"generic"},{values:e.sharedDirectives,reasonPrefix:"shared directives",bucket:"generic"},{values:e.sharedSlots,reasonPrefix:"shared slots",bucket:"generic"}],nameGroups:[{names:e.sharedComponents,label:"shared component",fallbackBucket:"generic"},{names:e.sharedIdentifiers,label:"shared identifier",fallbackBucket:"generic"}],recommendation:e1})}function e1(e){switch(e){case"domain-behavior":case"mixed":return"Review for a shared component or feature-specific Vue primitive around the named domain structure.";case"shared-abstraction":return"Review the existing shared component usage first; extract only if duplicated structure remains outside it.";case"generic-workflow-scaffolding":return"Generic structural overlap \u2014 verify intent before consolidating."}}var t1=new Set(["actions","app","button","card","content","container","dialog","field","form","header","input","item","label","layout","list","modal","page","panel","row","section","shell","table","text","toolbar","ui","value","view","wrapper"]);function ho(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=nt(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=Lt(l,d=>d.tokens);return Nt({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,m)=>n1(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function n1(e,t,n,r){let i=mt(e.tokens,t.tokens);if(i.size<r||!o1(i))return null;let o=Ma(e.tokens,t.tokens);if(o<n)return null;let s=V(i,"composable:"),a=V(i,"store:"),c=V(i,"reactivity:"),l=V(i,"lifecycle:"),u=V(i,"request:"),d=V(i,"function:"),m=V(i,"function-verb:"),f=V(i,"template-binding:"),p=V(i,"template-event:"),g=r1({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p});return{fileA:e.file,fileB:t.file,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Le(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:Le(Pe(e.tokens,t.tokens)).slice(0,25),uniqueToB:Le(Pe(t.tokens,e.tokens)).slice(0,25),reason:s1({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function r1(e){return Pn({genericWords:a1,primitiveGroups:[{values:e.sharedReactivity,reasonPrefix:"shared reactivity primitive",bucket:"generic"},{values:e.sharedLifecycle,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedComposables,label:"shared composable",fallbackBucket:"shared-abstraction"},{names:e.sharedStores,label:"shared store",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedFunctions,label:"shared function",fallbackBucket:"generic"},{names:e.sharedFunctionVerbs,label:"shared action verb",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"},{names:e.sharedTemplateEvents,label:"shared template event",fallbackBucket:"generic"}],recommendation:i1})}function i1(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 o1(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 Tn([{name:"requests",count:r},{name:"lifecycle",count:i},{name:"functions",count:o},{name:"reusableHooks",count:c},{name:"reactivity",count:s},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{lifecycle:1,functions:2,namedBehavior:4},reason:"shared lifecycle workflow"},{min:{reusableHooks:2,requests:1,namedBehavior:5},reason:"shared reusable Vue hooks and requests"},{min:{reusableHooks:2,functions:2,namedBehavior:5},reason:"shared reusable Vue hooks and functions"},{min:{functions:2,reactivity:1,namedBehavior:4},reason:"shared reactive functions"}]).pass}function s1(e){let t=[];return e.sharedComposables.length&&t.push(`shared composables: ${e.sharedComposables.join(", ")}`),e.sharedStores.length&&t.push(`shared stores: ${e.sharedStores.join(", ")}`),e.sharedRequests.length&&t.push(`shared request helpers: ${e.sharedRequests.join(", ")}`),e.sharedLifecycle.length&&t.push(`shared lifecycle: ${e.sharedLifecycle.join(", ")}`),e.sharedFunctions.length&&t.push(`shared functions: ${e.sharedFunctions.slice(0,6).join(", ")}`),e.sharedFunctionVerbs.length&&t.push(`shared action verbs: ${e.sharedFunctionVerbs.slice(0,6).join(", ")}`),e.sharedBindings.length&&t.push(`shared template bindings: ${e.sharedBindings.slice(0,6).join(", ")}`),t.join("; ")||"shared Vue behavior profile"}var a1=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 Td(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 nt(e).vueProfiles({scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>c1(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 c1(e,t){let n=Oa(e,l1(t),"total"),{reasons:r}=n;if(r.length===0)return null;let i=n.dominantPressure,o=n.pressureKinds.includes("total")?[...new Set([...n.pressureKinds,i])]:n.pressureKinds,s=u1(e.file),a=d1(i,s),c=e.totalLines+e.delegatedComposableLines;return{file:e.file,totalLines:c,sfcLines:e.sfcLines,templateLines:e.templateLines,scriptLines:e.scriptLines,styleLines:e.styleLines,externalScriptLines:e.externalScriptLines,externalScriptPaths:e.externalScriptPaths,customBlockLines:e.customBlockLines,delegatedComposableLines:e.delegatedComposableLines,delegatedComposablePaths:e.delegatedComposablePaths,dominantPressure:i,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:m1(a,s),reasons:r,loc:c}}function l1(e){return[{axis:"total",value:t=>t.totalLines+t.delegatedComposableLines,qualifies:(t,n)=>n>=e.minTotalLines,reason:(t,n)=>t.delegatedComposableLines>0?`${n} total line(s) (${t.totalLines} component + ${t.delegatedComposableLines} delegated composable line(s) across ${t.delegatedComposablePaths.length} file(s))`:`${n} total component line(s)`,dominantEligible:!1},{axis:"template",value:t=>t.templateLines,qualifies:(t,n)=>n>=e.minTemplateLines,reason:(t,n)=>`${n} template line(s)`},{axis:"script",value:t=>t.scriptLines-t.externalScriptLines,qualifies:t=>t.scriptLines>=e.minScriptLines,reason:t=>`${t.scriptLines} script line(s)`},{axis:"style",value:t=>t.styleLines,qualifies:(t,n)=>n>=e.minStyleLines,reason:(t,n)=>`${n} style line(s)`},{axis:"external-script",value:t=>t.externalScriptLines,qualifies:(t,n)=>n>=e.minScriptLines},{axis:"custom-block",value:t=>t.customBlockLines,qualifies:()=>!1}]}function u1(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>f1.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function d1(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 m1(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 f1=new Set(["landing","page","pages","route","routes","view","views"]);function p1(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=ie(e,i),c=R1(a,o,s);if(c.length===0)return[];let l=g1(c);return l.length<2?[]:x1(b1(l,n,r),r)}function g1(e){let t=h1(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 h1(e){let{nodeFreq:t,tailFreq:n}=y1(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 y1(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 b1(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=S1(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 S1(e,t,n){if(!C1(e.filtered,t.filtered))return null;let{distance:r,ops:i}=v1(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:I1(e.original,t.original),commonSuffix:w1(e.original,t.original)}}function C1(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function x1(e,t){let n=[];for(let r of e)if(n.some(o=>WC(r.chainA,o.chainA)&&WC(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function R1(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;GC(e,o,[o],new Set([o]),t,n,r,500)}return r}function GC(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),GC(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 v1(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 I1(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 w1(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 WC(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function ft(e){let t=D1(e.profile?.name),n=()=>{let r=e.candidates(),i=e.filterCandidate?r.filter(e.filterCandidate):r,o=e.orderCandidates?[...i].sort(e.orderCandidates):i,s=se(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:r.length,filteredCandidates:i.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<i.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,c=[];for(let u of s){t.evaluatedCandidates+=1;let d=e.evaluate(u,a);d&&c.push(d)}t.matchedResults=c.length,e.orderResults&&c.sort(e.orderResults);let l=typeof e.limit=="number"?c.slice(0,e.limit):c;return t.emittedResults=l.length,t.resultLimitApplied=l.length<c.length,e.onProfile?.({...t}),l};return e.profile?w(`candidate-pipeline:${e.profile.name}`,n,()=>({...E1(e.profile?.metadata),...t})):n()}function D1(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function E1(e){return typeof e=="function"?e():e??{}}function yo(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new _(e);return ft({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>k1(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function k1(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=L1(r,t),o=N1(r,i);if(o.length<2)return null;let s=A1(o,i);if(s.length===0)return null;let a=I(e.symbol),c=P1(a,r.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:O(e),totalCallees:r.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function P1(e,t,n,r){let i=Math.max(...r.map(c=>c.callees.length)),o=Math.max(...r.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${r.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${i} callees at ${Math.round(o*100)}% isolation`],a=T1(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:i>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function T1(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let r=_1(e);return F1.has(r)?`caller verb suggests orchestration: ${r}`:null}function _1(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 F1=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function L1(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 N1(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 A1(e,t){return e.filter(n=>n.size>=3).map(n=>M1(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function M1(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(I),isolation:s}}import{posix as Xr}from"path";import{spawnSync as O1}from"child_process";import{createHash as j1}from"crypto";import{existsSync as B1}from"fs";import{dirname as zC,join as $1}from"path";import{fileURLToPath as H1}from"url";var KC=j("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),VC=oe({kind:"consumer-file-usage",invalidation:K("consumer-file-usage"),serialize:X1,deserialize:Q1});function rn(e,t){return{forDefinitions(n,r){return U1(e,t,n,r)}}}function on(e){let t=new Map;for(let[n,r]of e)t.set(n,new Set(r.files.map(i=>i.file)));return t}function Ba(e,t,n){return YC(e,t,n).partition}function U1(e,t,n,r){let i=JC(n.length),o=U()?Te(e):null,s=o?W1(n,r,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return w("consumer-evidence.product",()=>{let c=w("consumer-evidence.provenance",()=>G1(e,t,n,r),()=>({...a,definitions:n.length,semantic:r.semantic,sourceFallback:r.sourceFallback!==!1})),l=new Map;i={...i,...c.counters};let u=z1(n,c.sources);return w("consumer-evidence.classify",()=>{let d=V1(e,n,c.sources,u);for(let m of n){let f=d.get(m.symbolId)??K1();i.realFiles+=f.partition.realConsumers.length,i.reexportOnlyFiles+=f.partition.barrelConsumers,i.importOnlyFiles+=f.partition.importOnlyConsumers,l.set(m.symbolId,{definition:m,files:f.files,...f.partition})}},()=>({...a,...u,realFiles:i.realFiles,reexportOnlyFiles:i.reexportOnlyFiles,importOnlyFiles:i.importOnlyFiles})),l},()=>({...a,...i}))}function W1(e,t,n){let r=j1("sha256").update("consumer-evidence-v1\0").update(n).update("\0").update(t.semantic?"semantic\0":"indexed\0").update(t.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let i of e.map(o=>o.symbol).sort())r.update("\0").update(i);return r.digest("hex").slice(0,24)}function JC(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function G1(e,t,n,r){let i=JC(n.length),o=new Map;return _d(o,i,"indexed",t.crossFileCallerMap(n,{semantic:!1})),r.semantic&&_d(o,i,"semantic",In(e,n)),r.sourceFallback!==!1&&_d(o,i,"source-fallback",t.sourceFallbackCallerFiles(n)),i.totalFiles=[...o.values()].reduce((s,a)=>s+a.size,0),{sources:o,counters:i}}function z1(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,r)=>n+r.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function _d(e,t,n,r){let i=0;for(let[o,s]of r){let a=e.get(o);a||(a=new Map,e.set(o,a));for(let c of s){i++;let l=a.get(c)??new Set;l.add(n),a.set(c,l)}}n==="indexed"?t.indexedFiles+=i:n==="semantic"?t.semanticFiles+=i:t.fallbackFiles+=i}function V1(e,t,n,r){let i=oH(e,t,n,r);return i||q1(e,t,n)}function q1(e,t,n){let r=new Map;for(let i of t){let o=n.get(i.symbolId)??new Map;r.set(i.symbolId,YC(e,i,[...o.keys()],o))}return r}function YC(e,t,n,r=new Map){let i=[],o=0,s=0,a=T(t.symbol),c=[];for(let l of n){let u;Z1(e,l,t.relativePath,a)?(o++,u="reexport-only"):Fd(e,l,a)?(s++,u="import-only"):(i.push(l),u="real"),c.push({file:l,sources:[...r.get(l)??[]],classification:u})}return{partition:{realConsumers:i,barrelConsumers:o,importOnlyConsumers:s},files:c}}function K1(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function Fd(e,t,n){if(!n)return!1;let r=M(t);if(!r)return!1;let i=KC.get(e,t,()=>XC(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function XC(e,t,n){let r=at(e).forFile(t,{text:!0,ast:!0}),i=r.text;if(!i)return Y1();let o=ce(e,t,i),s=VC.read(e,t,o);if(s)return s;let a=J1(r.ast,n);return VC.write(e,t,o,a),a}function J1(e,t){let n=new Set,r=new Set;if(!e)return{importedLeaves:n,usedLeaves:r};let i=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=(s,a)=>{let c=a||i.has(s.type);(s.type==="identifier"||s.type==="type_identifier"||s.type==="property_identifier"||s.type==="field_identifier")&&(c?n.add(s.text):r.add(s.text));for(let l of s.children)o(l,c)};return o(e.rootNode,!1),{importedLeaves:n,usedLeaves:r}}function Y1(){return{importedLeaves:new Set,usedLeaves:new Set}}function X1(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function Q1(e){try{let t=JSON.parse(e);return!Array.isArray(t.importedLeaves)||!Array.isArray(t.usedLeaves)?null:{importedLeaves:new Set(t.importedLeaves.filter(n=>typeof n=="string")),usedLeaves:new Set(t.usedLeaves.filter(n=>typeof n=="string"))}}catch{return null}}function Z1(e,t,n,r){if(!r)return!1;let i=at(e).forFile(t,{lines:!0,reexports:!0}),o=i.lines??[];if(o.length===0)return!1;let s=i.reexports??[];return QC(o,s,r)}function QC(e,t,n){if(e.length===0||t.length===0)return!1;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b${r}\\b`),o=0;for(let s=0;s<e.length;s++){if(!i.test(e[s]??""))continue;if(o++,!t.find(c=>c.startLine<=s&&s<=c.endLine))return!1}return o>0}var eH="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY",tH="SCIP_QUERY_NATIVE_KERNELS_BIN",nH="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",qC=1e3,rH=5e3,iH=64*1024*1024,ja;function oH(e,t,n,r){let i=process.env[eH]?.toLowerCase();if(i!=="1"&&i!=="true")return r.nativeReason=i==="0"||i==="false"?"disabled":"opt-in-required",null;if(r.consumerFiles<mH())return r.nativeReason="below-threshold",null;let o=fH();if(!o)return r.nativeReason="binary-missing",null;r.nativeAttempted=!0;let s=sH(e,t,n),a=O1(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:rH,maxBuffer:iH});if(a.status!==0||a.error)return r.nativeReason=a.error?`spawn-error:${a.error.message}`:`exit-${a.status??"null"}`,null;try{let c=JSON.parse(a.stdout),l=cH(c,t);return l?(r.nativeUsed=!0,r.nativeReason="used",l):(r.nativeReason="invalid-response",null)}catch{return r.nativeReason="invalid-json",null}}function sH(e,t,n){let r=new Map,i=[];for(let a of t){let c=T(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,m])=>{let f=r.get(d)??new Set;return c&&f.add(c),r.set(d,f),{file:d,sources:[...m]}});i.push({symbol_id:a.symbolId,leaf:c,consumer_files:u})}let o={},s={};for(let[a,c]of r){let l=M(a);if(l){let d=KC.get(e,a,()=>XC(e,a,l));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=aH(e,a,c);u.length>0&&(s[a]=u)}return{definitions:i,file_usages:o,reexport_only_leaves:s}}function aH(e,t,n){if(n.size===0)return[];let r=at(e).forFile(t,{lines:!0,reexports:!0}),i=r.lines??[],o=r.reexports??[];return i.length===0||o.length===0?[]:[...n].filter(s=>QC(i,o,s))}function cH(e,t){if(!Array.isArray(e.entries)||e.entries.length!==t.length)return null;let n=new Set(t.map(i=>i.symbolId)),r=new Map;for(let i of e.entries){let o=lH(i);if(!o||!n.has(o.symbol_id))return null;r.set(o.symbol_id,{partition:{realConsumers:o.real_consumers,barrelConsumers:o.barrel_consumers,importOnlyConsumers:o.import_only_consumers},files:o.files})}for(let i of n)if(!r.has(i))return null;return r}function lH(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.symbol_id!="number"||!Array.isArray(t.real_consumers)||typeof t.barrel_consumers!="number"||typeof t.import_only_consumers!="number"||!Array.isArray(t.files)||!t.real_consumers.every(r=>typeof r=="string"))return null;let n=[];for(let r of t.files){if(!r||typeof r!="object")return null;let i=r;if(typeof i.file!="string"||!Array.isArray(i.sources)||!i.sources.every(uH)||!dH(i.classification))return null;n.push({file:i.file,sources:i.sources,classification:i.classification})}return{symbol_id:t.symbol_id,real_consumers:t.real_consumers,barrel_consumers:t.barrel_consumers,import_only_consumers:t.import_only_consumers,files:n}}function uH(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function dH(e){return e==="real"||e==="reexport-only"||e==="import-only"}function mH(){let e=process.env[nH];if(!e)return qC;let t=Number(e);return Number.isFinite(t)&&t>=0?t:qC}function fH(){if(ja!==void 0)return ja;let e=process.env[tH],t=process.platform==="win32"?"scip-query-kernels.exe":"scip-query-kernels";return ja=[...e?[e]:[],...pH().map(r=>$1(r,"target","release",t))].find(r=>B1(r))??null,ja}function pH(){let e=new Set,t=zC(H1(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=zC(t);return[...e]}var gH=20,hH=1,yH=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"]]),bH=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),SH=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 CH(e,t={}){let n=Ad(t.limit,gH),r=Ad(t.minConsumers,hH),i=new _(e),o=i.fileDependencyGraph(t.scope),s=$H(N(e,{includeIgnored:!1})),a=WH(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?xH(e,i,t.target):RH(e,t.scope,t.scanLimit)).map(u=>vH(e,i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(BH).slice(0,n)}function xH(e,t,n){let r=DH(e,n);if(r)return[rx(r)];let i=B(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[EH(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:I(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function RH(e,t,n){let r=N(e,{scope:t,includeIgnored:!1}),i=Ad(n,r.length);return r.slice(0,i).map(o=>rx(o))}function vH(e,t,n,r,i,o,s){let a=r.definition?IH(e,t,r.definition,i.semantic):wH(n,r.unit.file),c=r.definition?a.length>0?"exact":"none":a.length>0?"file-level":"none",l=r.unit.file,u=xt(Xr.dirname(l)),d=PH(a),m=kH(u),f=Od([...ZC(u),...d?ZC(d):[]]),p=TH(r.unit,u,d,a),g=_H(p,r.unit,u,d,a,o,s),y=MH(r.unit,c,d,a,u,g.whyNoSuggestedHome),h=OH(r.unit,u,d,a,g.suggestedHome,g.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:r.unit,candidatePath:l,currentDirectory:u,directoryAncestry:m,consumerFiles:a,consumerCoverage:c,nearestCommonOwner:d,boundaryMarkers:f,recommendedTier:p,suggestedHome:g.suggestedHome,destinationConfidence:g.confidence,whyNoSuggestedHome:g.whyNoSuggestedHome,counterevidence:y,reasons:h,recommendation:jH(p,g.suggestedHome,c)}}function IH(e,t,n,r){let i=on(rn(e,t).forDefinitions([n],{semantic:r!==!1,sourceFallback:!0}));return cx(i.get(n.symbolId)??[])}function wH(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return cx(n)}function DH(e,t){let n=gn(t),r=N(e,{includeIgnored:!1}),i=r.find(s=>s===n);if(i)return i;let o=r.find(s=>s.endsWith(`/${n}`));return o||(r.find(s=>s.includes(n))??null)}function EH(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:I(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function rx(e){return{unit:{kind:"file",file:e,shortName:Xr.basename(e)}}}function kH(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let r=0;r<n.length;r+=1){let i=n.slice(0,r+1).join("/");t.push({path:i,depth:r,markers:Md(i)})}return t}function ZC(e){return e==="."?[]:ix(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function Md(e){return Od(ix(e).map(({marker:t})=>t))}function ix(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=yH.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function PH(e){if(e.length===0)return null;let t=e.map(r=>xt(Xr.dirname(r))),n=t[0].split("/").filter(Boolean);for(let r of t.slice(1)){let i=r.split("/").filter(Boolean),o=[],s=Math.min(n.length,i.length);for(let a=0;a<s&&n[a]===i[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function TH(e,t,n,r){return n?e.kind==="symbol"&&r.length===1?r[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":tx(n,"package")?"package-level-shared":tx(n,"app")?"app-level-shared":nx(n,["feature","domain","module"])||nx(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function _H(e,t,n,r,i,o,s){let a=FH(e,r);if(a)return _n(a);let c=HH(t.file),l=LH(e,n,c,i,s);if(l)return l;let u=r;if(xt(n)===xt(u))return _n(`${n} is already the nearest common owner for its consumers.`);let d=NH(u,n,c,s);return d||AH(u,n,c,o,s)}function FH(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 LH(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?Ld(o):_n("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=xt(Xr.dirname(r[0])),s=ax(t,n,o,i);return s?_n(s):Ld(o)}return null}function NH(e,t,n,r){return zH(e)?ox(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function AH(e,t,n,r,i){if(e===".")return _n("The nearest common owner is the repository root.");let o=`${e}/shared`,s=ox(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:_n(`${o} does not exist in the indexed project.`)}function ox(e,t,n,r,i){if(!sx(e,n))return _n(i);let o=ax(t,n,e,r);return o?_n(o):Ld(e)}function Ld(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function _n(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function MH(e,t,n,r,i,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),r.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&i.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function OH(e,t,n,r,i,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${r.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),i?s.push(`Suggested home is ${i}.`):o&&s.push(`No exact suggested home: ${o}`),s}function jH(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 BH(e,t){return ex(t)-ex(e)||e.candidatePath.localeCompare(t.candidatePath)}function ex(e){let t=e.consumerFiles.length*10;return e.consumerCoverage==="exact"&&(t+=5),e.suggestedHome&&(t+=3),e.recommendedTier==="repository-level-review"&&(t*=.1),e.recommendedTier==="no-exact-consumers"&&(t*=.05),t}function $H(e){let t=new Set(["."]);for(let n of e){let r=xt(Xr.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=xt(Xr.dirname(r))}return t}function HH(e){let t=Nd(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function sx(e,t){let n=xt(e),r=xt(t);return r==="."||n===r||n.startsWith(`${r}/`)}function UH(e,t,n){let r=Nd(e),i=Nd(t);return(sx(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function ax(e,t,n,r){return xt(e)===xt(n)||!UH(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function WH(...e){let t=new Set(SH);for(let n of e)for(let r of n??[]){let i=GH(r);i&&t.add(i)}return t}function GH(e){let t=e.trim().toLowerCase();return t===""?null:t}function tx(e,t){return Md(e).includes(t)}function nx(e,t){let n=Md(e);return t.some(r=>n.includes(r))}function zH(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?bH.has(n):!1}function xt(e){let t=gn(e);return t===""?".":t}function Nd(e){let t=gn(e);return t==="."?[]:t.split("/").filter(Boolean)}function Ad(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function cx(e){return Od([...e]).sort((t,n)=>t.localeCompare(n))}function Od(e){return[...new Set(e)]}function jd(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=[],m=MS(e,l,{limit:500,semanticEvidence:H});for(let f of l)for(let p of VH(e,f,i,m.get(f.symbolId)??[])){let g=`${p.file}|${p.shortName}`;if(p.symbolId!==null){if(a.has(p.symbolId))continue;a.add(p.symbolId)}else if(c.has(g))continue;c.add(g),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 VH(e,t,n,r){let i=r.filter(u=>!e.isIgnored(u.file)).filter(u=>!n||u.file.includes(n)),o=new Set(i.map(u=>u.file)),s=[];for(let u of qH(e,t,n)){if(o.has(u))continue;let d=Q(e,u),m=d.length>0?wt(d,d[0].startLine):null;s.push({symbol:m?.symbol??u,file:u})}let a=[...i,...s],c=[],l=new Set;for(let u of a){let d=wi(e,u.symbol);if(!d){let f=`${u.file}|${u.symbol}`;if(l.has(f))continue;l.add(f),c.push({symbolId:null,symbol:u.symbol,shortName:I(u.symbol),file:u.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!KH(d))continue;let m=`${d.symbolId}|${d.relativePath}`;l.has(m)||(l.add(m),c.push({symbolId:d.symbolId,symbol:d.symbol,shortName:I(d.symbol),file:d.relativePath,symbolMatch:d}))}return c}function qH(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
|
|
718
|
+
`)}function f$(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function p$(e,t,n){return DC.read(e,t,n)??new Map}function g$(e){try{let t=JSON.parse(e);if(!Array.isArray(t.entries))return null;let n=new Map;for(let r of t.entries){if(!r||typeof r.key!="string"||typeof r.symbol!="string"||typeof r.startLine!="number"||typeof r.endLine!="number"||typeof r.leaf!="string"||!Array.isArray(r.tokens)||!r.tokens.every(i=>typeof i=="string"))return null;n.set(r.key,r)}return n}catch{return null}}function h$(e){let t={entries:[...e.values()].sort((n,r)=>n.key.localeCompare(r.key))};return JSON.stringify(t)}function y$(e,t,n,r){DC.write(e,t,n,new Map(r))}function OC(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=b$(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 b$(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 S$(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Nt(e,t){let n=new Map;return e.forEach((r,i)=>{let o=new Set;for(let s of t(r)){if(o.has(s))continue;o.add(s);let a=n.get(s);a?a.push(i):n.set(s,[i])}}),{candidatesFor:(r,i)=>{let o=new Set;for(let s of t(r)){let a=n.get(s);if(a)for(let c of a)c!==i&&o.add(c)}return[...o].sort((s,a)=>s-a)}}}function At(e){let t=jC(e.profile?.name),n=()=>{let r=[];t=jC(e.profile?.name,e);let i=(s,a)=>{let c=e.profiles[s],l=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let u=e.compare(c,l);u&&r.push(u)};if(e.filePattern){let s=e.profiles.findIndex(a=>a.file.includes(e.filePattern));if(s>=0){let a=e.profiles[s];for(let c of C$(e,s)){let l=e.profiles[c];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(l.file)||i(s,c)}}}else if(e.focusFiles?.size!==0){let s=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let a=0;a<e.profiles.length;a+=1){let c=e.profiles[a],l=e.focusFiles?.has(c.file)??!1;for(let u of x$(e,a))e.focusFiles&&!l&&!e.focusFiles.has(e.profiles[u].file)||i(a,u);if(r.length>s){t.overrunApplied=!0;break}}}r.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=r.length;let o=r.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?w(`pairwise-profile:${e.profile.name}`,n,()=>({...R$(e.profile?.metadata),...t})):n()}function C$(e,t){if(e.candidateIndex)return BC(e,t,-1);let n=[];for(let r=0;r<e.profiles.length;r+=1)r!==t&&n.push(r);return n}function x$(e,t){if(e.candidateIndex)return BC(e,t,t);let n=[];for(let r=t+1;r<e.profiles.length;r+=1)n.push(r);return n}function BC(e,t,n){let r=e.profiles[t],i=new Set;for(let o of e.candidateIndex?.candidatesFor(r,t,e.profiles)??[])o<=n||o!==t&&(o<0||o>=e.profiles.length||i.add(o));return[...i].sort((o,s)=>o-s)}function jC(e,t){return{pipeline:e,profileCount:t?.profiles.length??0,focusedProfileCount:t?.focusFiles?t.profiles.filter(n=>t.focusFiles.has(n.file)).length:0,candidatePairs:0,comparedPairs:0,matchedResults:0,emittedResults:0,candidateIndexApplied:t?.candidateIndex!==void 0,focusApplied:t?.focusFiles!==void 0,filePatternApplied:t?.filePattern!==void 0,overrunApplied:!1}}function R$(e){return typeof e=="function"?e():e??{}}function v$(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=I$(e,{scope:i,minDeps:s}),l=Nt(a,u=>u.deps);return At({profiles:a,limit:r,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(u,d)=>D$(u,d,n,c)})}function I$(e,t){let{scope:n,minDeps:r}=t,i=ie(e,n),{universalDeps:o,distinctiveDeps:s}=w$(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 w$(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 D$(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=Pn(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 Tn(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&$C(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)E$(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,$C(l.fallbackBucket,n,r));let i=t.length>0,o=n.length>0,s=r.length>0,a=i?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...r,...n].slice(0,6),recommendation:e.recommendation(a)}}function Ma(e,t){if(e.size===0||t.size===0)return 0;let i=pt(e,t).size/Math.min(e.size,t.size)*Math.min(1,Math.min(e.size,t.size)/(.35*Math.max(e.size,t.size)));return Math.max(Pn(e,t),i)}function _n(e,t){let n=Object.fromEntries(e.map(r=>[r.name,r.count]));for(let r of t)if(Object.entries(r.min).every(([o,s])=>(n[o]??0)>=s))return{pass:!0,reason:r.reason,counts:n};return{pass:!1,reason:"shared tokens did not meet calibrated overlap thresholds",counts:n}}function Oa(e,t,n){let r=t.map(c=>{let l=c.value(e),u=c.weightedValue?c.weightedValue(e,l):l;return{axis:c,value:l,weighted:u,qualifies:c.qualifies?c.qualifies(e,l):l>0}}),i=r.filter(c=>c.qualifies&&c.axis.reason).map(c=>c.axis.reason(e,c.value)),o=r.filter(c=>c.qualifies&&c.axis.dominantEligible!==!1).sort((c,l)=>l.weighted-c.weighted)[0],s=o&&o.weighted>0?o.axis.axis:n,a=[...new Set(r.filter(c=>c.qualifies).map(c=>c.axis.axis).concat(i.length>0?[]:[s]))];return{dominantPressure:s,pressureKinds:a,reasons:i}}function V(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function Le(e){return[...e].sort()}function E$(e,t,n,r,i,o){let s=[],a=[];for(let c of e)k$(c,r).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&i.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function k$(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let r of t)n=n.replace(r,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function $C(e,t,n){return e==="generic"?t:n}function fo(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=ot(e).reactProfiles({scope:o,minJsxTokens:r,scanLimit:s}).filter(d=>d.kind==="component").map(d=>({file:d.file,component:d.name,tokens:d.jsxTokens,profile:d})),u=Nt(l,d=>d.tokens);return At({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,m)=>P$(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.componentA.localeCompare(m.componentA)||d.fileB.localeCompare(m.fileB)||d.componentB.localeCompare(m.componentB)})}function P$(e,t,n){let r=pt(e.tokens,t.tokens);if(r.size<6||!T$(r))return null;let i=Pn(e.tokens,t.tokens);if(i<n)return null;let o=V(r,"component:"),s=V(r,"native:"),a=V(r,"prop:"),c=V(r,"event:"),l=V(r,"binding:"),u=_$({sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Le(r),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:Le(Pe(e.tokens,t.tokens)).slice(0,25),uniqueToB:Le(Pe(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function T$(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 _n([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function _$(e){return Tn({genericWords:L$,primitiveGroups:[{values:e.sharedNativeTags,reasonPrefix:"shared native tags",bucket:"generic"},{values:e.sharedProps,reasonPrefix:"shared props",bucket:"generic"},{values:e.sharedEvents,reasonPrefix:"shared events",bucket:"generic"}],nameGroups:[{names:e.sharedComponents,label:"shared component",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"}],recommendation:F$})}function F$(e){switch(e){case"domain-behavior":case"mixed":return"Review for a shared component or feature-specific UI primitive around the named domain structure.";case"shared-abstraction":return"Review the existing shared component usage first; extract only if duplicated structure remains outside it.";case"generic-workflow-scaffolding":return"Generic structural overlap \u2014 verify intent before consolidating."}}var L$=new Set(["actions","app","button","card","children","content","container","dialog","field","form","header","input","item","label","layout","list","modal","page","panel","row","section","shell","table","text","toolbar","ui","value","view","wrapper"]);function po(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=ot(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,component:d.name,tokens:d.behaviorTokens,profile:d})),u=Nt(l,d=>d.tokens);return At({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,m)=>N$(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.componentA.localeCompare(m.componentA)||d.fileB.localeCompare(m.fileB)||d.componentB.localeCompare(m.componentB)})}function N$(e,t,n,r){let i=pt(e.tokens,t.tokens);if(i.size<r||!O$(i))return null;let o=Ma(e.tokens,t.tokens);if(o<n)return null;let s=V(i,"hook:"),a=V(i,"react-hook:"),c=V(i,"effect:"),l=V(i,"state:"),u=V(i,"request:"),d=V(i,"handler:"),m=V(i,"handler-verb:"),f=A$({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,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Le(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:f.evidenceClass,actionTier:f.actionTier,evidenceClassReasons:f.reasons,recommendation:f.recommendation,uniqueToA:Le(Pe(e.tokens,t.tokens)).slice(0,25),uniqueToB:Le(Pe(t.tokens,e.tokens)).slice(0,25),reason:j$({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function A$(e){return Tn({genericWords:B$,stripPrefixes:$$,primitiveGroups:[{values:e.sharedReactHooks,reasonPrefix:"shared React primitives",bucket:"generic"},{values:e.sharedEffects,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedHooks,label:"shared hook",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedState,label:"shared state",fallbackBucket:"generic"},{names:e.sharedHandlers,label:"shared handler",fallbackBucket:"generic"},{names:e.sharedHandlerVerbs,label:"shared action verb",fallbackBucket:"generic"}],recommendation:M$})}function M$(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 O$(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 _n([{name:"requests",count:i},{name:"customHooks",count:t},{name:"namedStates",count:s},{name:"handlers",count:o},{name:"effects",count:r},{name:"reactHooks",count:n},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{customHooks:1,requests:1,namedBehavior:5},reason:"shared custom hook and request workflow"},{min:{customHooks:1,namedStates:1,namedBehavior:5},reason:"shared custom hook and state"},{min:{customHooks:1,handlers:2,namedBehavior:5},reason:"shared custom hook and handlers"},{min:{namedStates:1,handlers:2,effects:1,namedBehavior:5},reason:"shared stateful effects"},{min:{namedStates:1,handlers:2,reactHooks:2,namedBehavior:5},reason:"shared stateful React primitives"}]).pass}function j$(e){let t=[];return e.sharedHooks.length&&t.push(`shared hooks: ${e.sharedHooks.join(", ")}`),e.sharedReactHooks.length&&t.push(`shared React hooks: ${e.sharedReactHooks.join(", ")}`),e.sharedEffects.length&&t.push(`shared effects: ${e.sharedEffects.join(", ")}`),e.sharedState.length&&t.push(`shared state: ${e.sharedState.join(", ")}`),e.sharedRequests.length&&t.push(`shared requests: ${e.sharedRequests.join(", ")}`),e.sharedHandlers.length&&t.push(`shared handlers: ${e.sharedHandlers.slice(0,6).join(", ")}`),e.sharedHandlerVerbs.length&&t.push(`shared action verbs: ${e.sharedHandlerVerbs.slice(0,6).join(", ")}`),t.join("; ")||"shared React behavior profile"}var B$=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"]),$$=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function Pd(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 ot(e).reactProfiles({scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>H$(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 H$(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),r=Oa(e,U$({minComponentLines:t.minComponentLines,minFileLines:t.minFileLines,minJsxTokens:t.minJsxTokens,minBehaviorTokens:t.minBehaviorTokens,substantialComponentLines:n}),"component"),{reasons:i}=r;if(i.length===0)return null;let o=r.dominantPressure,s=r.pressureKinds,a=W$(e),c=G$(o,s,a);return{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:o,pressureKinds:s,contextKind:a,recommendationKind:c,recommendation:z$(c,a),reasons:i,loc:e.loc}}function U$(e){return[{axis:"component",value:t=>t.loc,qualifies:(t,n)=>n>=e.minComponentLines,reason:(t,n)=>`${n} component line(s)`},{axis:"file",value:t=>t.fileLines,qualifies:(t,n)=>n>=e.minFileLines&&t.loc>=e.substantialComponentLines,reason:(t,n)=>`${n} file line(s)`},{axis:"jsx-structure",value:t=>t.jsxTokens.size,weightedValue:(t,n)=>n*3,qualifies:(t,n)=>n>=e.minJsxTokens,reason:(t,n)=>`${n} JSX structure token(s)`},{axis:"hook-behavior",value:t=>t.behaviorTokens.size,weightedValue:(t,n)=>n*4,qualifies:(t,n)=>n>=e.minBehaviorTokens,reason:(t,n)=>`${n} behavior token(s)`}]}function W$(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(m=>m.toLowerCase()),r=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),o=n.findIndex(m=>q$.has(m))>=0,s=n.some(m=>V$.has(m));if(HC(r)||HC(e.name))return"component";let c=K$.has(r.toLowerCase()),l=/(?:Page|Route|Screen)$/.test(e.name),u=o&&/View$/.test(e.name),d=!s&&r.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===e.name.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(r);return c||l||u||d?"route-page":"component"}function HC(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&UC.has(t.at(-1))?!0:[...UC].some(n=>e.endsWith(J$(n)))}function G$(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 z$(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 V$=new Set(["component","components","panel","panels","partial","partials"]),UC=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"]),q$=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),K$=new Set(["page","route","screen"]);function J$(e){return e.charAt(0).toUpperCase()+e.slice(1)}function go(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=Y$(e,{scope:o,minTokens:r,scanLimit:s}),u=Nt(l,d=>d.tokens);return At({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,m)=>Q$(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function Y$(e,t){return ot(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:X$(n)}))}function X$(e){return e.totalLines}function Q$(e,t,n){let r=pt(e.tokens,t.tokens);if(r.size<6||!Z$(r))return null;let i=Pn(e.tokens,t.tokens);if(i<n)return null;let o=V(r,"component:"),s=V(r,"prop:"),a=V(r,"event:"),c=V(r,"directive:"),l=V(r,"slot:"),u=V(r,"id:"),d=e1({sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u});return{fileA:e.file,fileB:t.file,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Le(r),sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u,evidenceClass:d.evidenceClass,actionTier:d.actionTier,evidenceClassReasons:d.reasons,recommendation:d.recommendation,uniqueToA:Le(Pe(e.tokens,t.tokens)).slice(0,25),uniqueToB:Le(Pe(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function Z$(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 _n([{name:"component",count:t},{name:"behavior",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{behavior:3},reason:"shared Vue template structure"}]).pass}function e1(e){return Tn({genericWords:n1,primitiveGroups:[{values:e.sharedProps,reasonPrefix:"shared props",bucket:"generic"},{values:e.sharedEvents,reasonPrefix:"shared events",bucket:"generic"},{values:e.sharedDirectives,reasonPrefix:"shared directives",bucket:"generic"},{values:e.sharedSlots,reasonPrefix:"shared slots",bucket:"generic"}],nameGroups:[{names:e.sharedComponents,label:"shared component",fallbackBucket:"generic"},{names:e.sharedIdentifiers,label:"shared identifier",fallbackBucket:"generic"}],recommendation:t1})}function t1(e){switch(e){case"domain-behavior":case"mixed":return"Review for a shared component or feature-specific Vue primitive around the named domain structure.";case"shared-abstraction":return"Review the existing shared component usage first; extract only if duplicated structure remains outside it.";case"generic-workflow-scaffolding":return"Generic structural overlap \u2014 verify intent before consolidating."}}var n1=new Set(["actions","app","button","card","content","container","dialog","field","form","header","input","item","label","layout","list","modal","page","panel","row","section","shell","table","text","toolbar","ui","value","view","wrapper"]);function ho(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=ot(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=Nt(l,d=>d.tokens);return At({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,m)=>r1(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function r1(e,t,n,r){let i=pt(e.tokens,t.tokens);if(i.size<r||!s1(i))return null;let o=Ma(e.tokens,t.tokens);if(o<n)return null;let s=V(i,"composable:"),a=V(i,"store:"),c=V(i,"reactivity:"),l=V(i,"lifecycle:"),u=V(i,"request:"),d=V(i,"function:"),m=V(i,"function-verb:"),f=V(i,"template-binding:"),p=V(i,"template-event:"),g=i1({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p});return{fileA:e.file,fileB:t.file,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Le(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:Le(Pe(e.tokens,t.tokens)).slice(0,25),uniqueToB:Le(Pe(t.tokens,e.tokens)).slice(0,25),reason:a1({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function i1(e){return Tn({genericWords:c1,primitiveGroups:[{values:e.sharedReactivity,reasonPrefix:"shared reactivity primitive",bucket:"generic"},{values:e.sharedLifecycle,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedComposables,label:"shared composable",fallbackBucket:"shared-abstraction"},{names:e.sharedStores,label:"shared store",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedFunctions,label:"shared function",fallbackBucket:"generic"},{names:e.sharedFunctionVerbs,label:"shared action verb",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"},{names:e.sharedTemplateEvents,label:"shared template event",fallbackBucket:"generic"}],recommendation:o1})}function o1(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 s1(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 _n([{name:"requests",count:r},{name:"lifecycle",count:i},{name:"functions",count:o},{name:"reusableHooks",count:c},{name:"reactivity",count:s},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{lifecycle:1,functions:2,namedBehavior:4},reason:"shared lifecycle workflow"},{min:{reusableHooks:2,requests:1,namedBehavior:5},reason:"shared reusable Vue hooks and requests"},{min:{reusableHooks:2,functions:2,namedBehavior:5},reason:"shared reusable Vue hooks and functions"},{min:{functions:2,reactivity:1,namedBehavior:4},reason:"shared reactive functions"}]).pass}function a1(e){let t=[];return e.sharedComposables.length&&t.push(`shared composables: ${e.sharedComposables.join(", ")}`),e.sharedStores.length&&t.push(`shared stores: ${e.sharedStores.join(", ")}`),e.sharedRequests.length&&t.push(`shared request helpers: ${e.sharedRequests.join(", ")}`),e.sharedLifecycle.length&&t.push(`shared lifecycle: ${e.sharedLifecycle.join(", ")}`),e.sharedFunctions.length&&t.push(`shared functions: ${e.sharedFunctions.slice(0,6).join(", ")}`),e.sharedFunctionVerbs.length&&t.push(`shared action verbs: ${e.sharedFunctionVerbs.slice(0,6).join(", ")}`),e.sharedBindings.length&&t.push(`shared template bindings: ${e.sharedBindings.slice(0,6).join(", ")}`),t.join("; ")||"shared Vue behavior profile"}var c1=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 Td(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 ot(e).vueProfiles({scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>l1(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 l1(e,t){let n=Oa(e,u1(t),"total"),{reasons:r}=n;if(r.length===0)return null;let i=n.dominantPressure,o=n.pressureKinds.includes("total")?[...new Set([...n.pressureKinds,i])]:n.pressureKinds,s=d1(e.file),a=m1(i,s),c=e.totalLines+e.delegatedComposableLines;return{file:e.file,totalLines:c,sfcLines:e.sfcLines,templateLines:e.templateLines,scriptLines:e.scriptLines,styleLines:e.styleLines,externalScriptLines:e.externalScriptLines,externalScriptPaths:e.externalScriptPaths,customBlockLines:e.customBlockLines,delegatedComposableLines:e.delegatedComposableLines,delegatedComposablePaths:e.delegatedComposablePaths,dominantPressure:i,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:f1(a,s),reasons:r,loc:c}}function u1(e){return[{axis:"total",value:t=>t.totalLines+t.delegatedComposableLines,qualifies:(t,n)=>n>=e.minTotalLines,reason:(t,n)=>t.delegatedComposableLines>0?`${n} total line(s) (${t.totalLines} component + ${t.delegatedComposableLines} delegated composable line(s) across ${t.delegatedComposablePaths.length} file(s))`:`${n} total component line(s)`,dominantEligible:!1},{axis:"template",value:t=>t.templateLines,qualifies:(t,n)=>n>=e.minTemplateLines,reason:(t,n)=>`${n} template line(s)`},{axis:"script",value:t=>t.scriptLines-t.externalScriptLines,qualifies:t=>t.scriptLines>=e.minScriptLines,reason:t=>`${t.scriptLines} script line(s)`},{axis:"style",value:t=>t.styleLines,qualifies:(t,n)=>n>=e.minStyleLines,reason:(t,n)=>`${n} style line(s)`},{axis:"external-script",value:t=>t.externalScriptLines,qualifies:(t,n)=>n>=e.minScriptLines},{axis:"custom-block",value:t=>t.customBlockLines,qualifies:()=>!1}]}function d1(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>p1.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function m1(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 f1(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 p1=new Set(["landing","page","pages","route","routes","view","views"]);function g1(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=ie(e,i),c=v1(a,o,s);if(c.length===0)return[];let l=h1(c);return l.length<2?[]:R1(S1(l,n,r),r)}function h1(e){let t=y1(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 y1(e){let{nodeFreq:t,tailFreq:n}=b1(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 b1(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 S1(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=C1(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 C1(e,t,n){if(!x1(e.filtered,t.filtered))return null;let{distance:r,ops:i}=I1(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:w1(e.original,t.original),commonSuffix:D1(e.original,t.original)}}function x1(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function R1(e,t){let n=[];for(let r of e)if(n.some(o=>WC(r.chainA,o.chainA)&&WC(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function v1(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;GC(e,o,[o],new Set([o]),t,n,r,500)}return r}function GC(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),GC(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 I1(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 w1(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 D1(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 WC(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function gt(e){let t=E1(e.profile?.name),n=()=>{let r=e.candidates(),i=e.filterCandidate?r.filter(e.filterCandidate):r,o=e.orderCandidates?[...i].sort(e.orderCandidates):i,s=se(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:r.length,filteredCandidates:i.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<i.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,c=[];for(let u of s){t.evaluatedCandidates+=1;let d=e.evaluate(u,a);d&&c.push(d)}t.matchedResults=c.length,e.orderResults&&c.sort(e.orderResults);let l=typeof e.limit=="number"?c.slice(0,e.limit):c;return t.emittedResults=l.length,t.resultLimitApplied=l.length<c.length,e.onProfile?.({...t}),l};return e.profile?w(`candidate-pipeline:${e.profile.name}`,n,()=>({...k1(e.profile?.metadata),...t})):n()}function E1(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function k1(e){return typeof e=="function"?e():e??{}}function yo(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new _(e);return gt({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>P1(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function P1(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=N1(r,t),o=A1(r,i);if(o.length<2)return null;let s=M1(o,i);if(s.length===0)return null;let a=I(e.symbol),c=T1(a,r.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:O(e),totalCallees:r.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function T1(e,t,n,r){let i=Math.max(...r.map(c=>c.callees.length)),o=Math.max(...r.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${r.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${i} callees at ${Math.round(o*100)}% isolation`],a=_1(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:i>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function _1(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let r=F1(e);return L1.has(r)?`caller verb suggests orchestration: ${r}`:null}function F1(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 L1=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function N1(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 A1(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 M1(e,t){return e.filter(n=>n.size>=3).map(n=>O1(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function O1(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(I),isolation:s}}import{posix as Xr}from"path";import{spawnSync as j1}from"child_process";import{createHash as B1}from"crypto";import{existsSync as $1}from"fs";import{dirname as zC,join as H1}from"path";import{fileURLToPath as U1}from"url";var KC=j("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),VC=oe({kind:"consumer-file-usage",invalidation:K("consumer-file-usage"),serialize:Q1,deserialize:Z1});function on(e,t){return{forDefinitions(n,r){return W1(e,t,n,r)}}}function sn(e){let t=new Map;for(let[n,r]of e)t.set(n,new Set(r.files.map(i=>i.file)));return t}function Ba(e,t,n){return YC(e,t,n).partition}function W1(e,t,n,r){let i=JC(n.length),o=U()?Te(e):null,s=o?G1(n,r,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return w("consumer-evidence.product",()=>{let c=w("consumer-evidence.provenance",()=>z1(e,t,n,r),()=>({...a,definitions:n.length,semantic:r.semantic,sourceFallback:r.sourceFallback!==!1})),l=new Map;i={...i,...c.counters};let u=V1(n,c.sources);return w("consumer-evidence.classify",()=>{let d=q1(e,n,c.sources,u);for(let m of n){let f=d.get(m.symbolId)??J1();i.realFiles+=f.partition.realConsumers.length,i.reexportOnlyFiles+=f.partition.barrelConsumers,i.importOnlyFiles+=f.partition.importOnlyConsumers,l.set(m.symbolId,{definition:m,files:f.files,...f.partition})}},()=>({...a,...u,realFiles:i.realFiles,reexportOnlyFiles:i.reexportOnlyFiles,importOnlyFiles:i.importOnlyFiles})),l},()=>({...a,...i}))}function G1(e,t,n){let r=B1("sha256").update("consumer-evidence-v1\0").update(n).update("\0").update(t.semantic?"semantic\0":"indexed\0").update(t.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let i of e.map(o=>o.symbol).sort())r.update("\0").update(i);return r.digest("hex").slice(0,24)}function JC(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function z1(e,t,n,r){let i=JC(n.length),o=new Map;return _d(o,i,"indexed",t.crossFileCallerMap(n,{semantic:!1})),r.semantic&&_d(o,i,"semantic",wn(e,n)),r.sourceFallback!==!1&&_d(o,i,"source-fallback",t.sourceFallbackCallerFiles(n)),i.totalFiles=[...o.values()].reduce((s,a)=>s+a.size,0),{sources:o,counters:i}}function V1(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,r)=>n+r.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function _d(e,t,n,r){let i=0;for(let[o,s]of r){let a=e.get(o);a||(a=new Map,e.set(o,a));for(let c of s){i++;let l=a.get(c)??new Set;l.add(n),a.set(c,l)}}n==="indexed"?t.indexedFiles+=i:n==="semantic"?t.semanticFiles+=i:t.fallbackFiles+=i}function q1(e,t,n,r){let i=sH(e,t,n,r);return i||K1(e,t,n)}function K1(e,t,n){let r=new Map;for(let i of t){let o=n.get(i.symbolId)??new Map;r.set(i.symbolId,YC(e,i,[...o.keys()],o))}return r}function YC(e,t,n,r=new Map){let i=[],o=0,s=0,a=T(t.symbol),c=[];for(let l of n){let u;eH(e,l,t.relativePath,a)?(o++,u="reexport-only"):Fd(e,l,a)?(s++,u="import-only"):(i.push(l),u="real"),c.push({file:l,sources:[...r.get(l)??[]],classification:u})}return{partition:{realConsumers:i,barrelConsumers:o,importOnlyConsumers:s},files:c}}function J1(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function Fd(e,t,n){if(!n)return!1;let r=M(t);if(!r)return!1;let i=KC.get(e,t,()=>XC(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function XC(e,t,n){let r=ut(e).forFile(t,{text:!0,ast:!0}),i=r.text;if(!i)return X1();let o=ce(e,t,i),s=VC.read(e,t,o);if(s)return s;let a=Y1(r.ast,n);return VC.write(e,t,o,a),a}function Y1(e,t){let n=new Set,r=new Set;if(!e)return{importedLeaves:n,usedLeaves:r};let i=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=(s,a)=>{let c=a||i.has(s.type);(s.type==="identifier"||s.type==="type_identifier"||s.type==="property_identifier"||s.type==="field_identifier")&&(c?n.add(s.text):r.add(s.text));for(let l of s.children)o(l,c)};return o(e.rootNode,!1),{importedLeaves:n,usedLeaves:r}}function X1(){return{importedLeaves:new Set,usedLeaves:new Set}}function Q1(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function Z1(e){try{let t=JSON.parse(e);return!Array.isArray(t.importedLeaves)||!Array.isArray(t.usedLeaves)?null:{importedLeaves:new Set(t.importedLeaves.filter(n=>typeof n=="string")),usedLeaves:new Set(t.usedLeaves.filter(n=>typeof n=="string"))}}catch{return null}}function eH(e,t,n,r){if(!r)return!1;let i=ut(e).forFile(t,{lines:!0,reexports:!0}),o=i.lines??[];if(o.length===0)return!1;let s=i.reexports??[];return QC(o,s,r)}function QC(e,t,n){if(e.length===0||t.length===0)return!1;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b${r}\\b`),o=0;for(let s=0;s<e.length;s++){if(!i.test(e[s]??""))continue;if(o++,!t.find(c=>c.startLine<=s&&s<=c.endLine))return!1}return o>0}var tH="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY",nH="SCIP_QUERY_NATIVE_KERNELS_BIN",rH="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",qC=1e3,iH=5e3,oH=64*1024*1024,ja;function sH(e,t,n,r){let i=process.env[tH]?.toLowerCase();if(i!=="1"&&i!=="true")return r.nativeReason=i==="0"||i==="false"?"disabled":"opt-in-required",null;if(r.consumerFiles<fH())return r.nativeReason="below-threshold",null;let o=pH();if(!o)return r.nativeReason="binary-missing",null;r.nativeAttempted=!0;let s=aH(e,t,n),a=j1(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:iH,maxBuffer:oH});if(a.status!==0||a.error)return r.nativeReason=a.error?`spawn-error:${a.error.message}`:`exit-${a.status??"null"}`,null;try{let c=JSON.parse(a.stdout),l=lH(c,t);return l?(r.nativeUsed=!0,r.nativeReason="used",l):(r.nativeReason="invalid-response",null)}catch{return r.nativeReason="invalid-json",null}}function aH(e,t,n){let r=new Map,i=[];for(let a of t){let c=T(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,m])=>{let f=r.get(d)??new Set;return c&&f.add(c),r.set(d,f),{file:d,sources:[...m]}});i.push({symbol_id:a.symbolId,leaf:c,consumer_files:u})}let o={},s={};for(let[a,c]of r){let l=M(a);if(l){let d=KC.get(e,a,()=>XC(e,a,l));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=cH(e,a,c);u.length>0&&(s[a]=u)}return{definitions:i,file_usages:o,reexport_only_leaves:s}}function cH(e,t,n){if(n.size===0)return[];let r=ut(e).forFile(t,{lines:!0,reexports:!0}),i=r.lines??[],o=r.reexports??[];return i.length===0||o.length===0?[]:[...n].filter(s=>QC(i,o,s))}function lH(e,t){if(!Array.isArray(e.entries)||e.entries.length!==t.length)return null;let n=new Set(t.map(i=>i.symbolId)),r=new Map;for(let i of e.entries){let o=uH(i);if(!o||!n.has(o.symbol_id))return null;r.set(o.symbol_id,{partition:{realConsumers:o.real_consumers,barrelConsumers:o.barrel_consumers,importOnlyConsumers:o.import_only_consumers},files:o.files})}for(let i of n)if(!r.has(i))return null;return r}function uH(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.symbol_id!="number"||!Array.isArray(t.real_consumers)||typeof t.barrel_consumers!="number"||typeof t.import_only_consumers!="number"||!Array.isArray(t.files)||!t.real_consumers.every(r=>typeof r=="string"))return null;let n=[];for(let r of t.files){if(!r||typeof r!="object")return null;let i=r;if(typeof i.file!="string"||!Array.isArray(i.sources)||!i.sources.every(dH)||!mH(i.classification))return null;n.push({file:i.file,sources:i.sources,classification:i.classification})}return{symbol_id:t.symbol_id,real_consumers:t.real_consumers,barrel_consumers:t.barrel_consumers,import_only_consumers:t.import_only_consumers,files:n}}function dH(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function mH(e){return e==="real"||e==="reexport-only"||e==="import-only"}function fH(){let e=process.env[rH];if(!e)return qC;let t=Number(e);return Number.isFinite(t)&&t>=0?t:qC}function pH(){if(ja!==void 0)return ja;let e=process.env[nH],t=process.platform==="win32"?"scip-query-kernels.exe":"scip-query-kernels";return ja=[...e?[e]:[],...gH().map(r=>H1(r,"target","release",t))].find(r=>$1(r))??null,ja}function gH(){let e=new Set,t=zC(U1(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=zC(t);return[...e]}var hH=20,yH=1,bH=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"]]),SH=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),CH=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 xH(e,t={}){let n=Ad(t.limit,hH),r=Ad(t.minConsumers,yH),i=new _(e),o=i.fileDependencyGraph(t.scope),s=HH(N(e,{includeIgnored:!1})),a=GH(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?RH(e,i,t.target):vH(e,t.scope,t.scanLimit)).map(u=>IH(e,i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort($H).slice(0,n)}function RH(e,t,n){let r=EH(e,n);if(r)return[rx(r)];let i=B(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[kH(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:I(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function vH(e,t,n){let r=N(e,{scope:t,includeIgnored:!1}),i=Ad(n,r.length);return r.slice(0,i).map(o=>rx(o))}function IH(e,t,n,r,i,o,s){let a=r.definition?wH(e,t,r.definition,i.semantic):DH(n,r.unit.file),c=r.definition?a.length>0?"exact":"none":a.length>0?"file-level":"none",l=r.unit.file,u=Rt(Xr.dirname(l)),d=TH(a),m=PH(u),f=Od([...ZC(u),...d?ZC(d):[]]),p=_H(r.unit,u,d,a),g=FH(p,r.unit,u,d,a,o,s),y=OH(r.unit,c,d,a,u,g.whyNoSuggestedHome),h=jH(r.unit,u,d,a,g.suggestedHome,g.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:r.unit,candidatePath:l,currentDirectory:u,directoryAncestry:m,consumerFiles:a,consumerCoverage:c,nearestCommonOwner:d,boundaryMarkers:f,recommendedTier:p,suggestedHome:g.suggestedHome,destinationConfidence:g.confidence,whyNoSuggestedHome:g.whyNoSuggestedHome,counterevidence:y,reasons:h,recommendation:BH(p,g.suggestedHome,c)}}function wH(e,t,n,r){let i=sn(on(e,t).forDefinitions([n],{semantic:r!==!1,sourceFallback:!0}));return cx(i.get(n.symbolId)??[])}function DH(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return cx(n)}function EH(e,t){let n=hn(t),r=N(e,{includeIgnored:!1}),i=r.find(s=>s===n);if(i)return i;let o=r.find(s=>s.endsWith(`/${n}`));return o||(r.find(s=>s.includes(n))??null)}function kH(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:I(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function rx(e){return{unit:{kind:"file",file:e,shortName:Xr.basename(e)}}}function PH(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let r=0;r<n.length;r+=1){let i=n.slice(0,r+1).join("/");t.push({path:i,depth:r,markers:Md(i)})}return t}function ZC(e){return e==="."?[]:ix(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function Md(e){return Od(ix(e).map(({marker:t})=>t))}function ix(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=bH.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function TH(e){if(e.length===0)return null;let t=e.map(r=>Rt(Xr.dirname(r))),n=t[0].split("/").filter(Boolean);for(let r of t.slice(1)){let i=r.split("/").filter(Boolean),o=[],s=Math.min(n.length,i.length);for(let a=0;a<s&&n[a]===i[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function _H(e,t,n,r){return n?e.kind==="symbol"&&r.length===1?r[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":tx(n,"package")?"package-level-shared":tx(n,"app")?"app-level-shared":nx(n,["feature","domain","module"])||nx(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function FH(e,t,n,r,i,o,s){let a=LH(e,r);if(a)return Fn(a);let c=UH(t.file),l=NH(e,n,c,i,s);if(l)return l;let u=r;if(Rt(n)===Rt(u))return Fn(`${n} is already the nearest common owner for its consumers.`);let d=AH(u,n,c,s);return d||MH(u,n,c,o,s)}function LH(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 NH(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?Ld(o):Fn("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=Rt(Xr.dirname(r[0])),s=ax(t,n,o,i);return s?Fn(s):Ld(o)}return null}function AH(e,t,n,r){return VH(e)?ox(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function MH(e,t,n,r,i){if(e===".")return Fn("The nearest common owner is the repository root.");let o=`${e}/shared`,s=ox(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:Fn(`${o} does not exist in the indexed project.`)}function ox(e,t,n,r,i){if(!sx(e,n))return Fn(i);let o=ax(t,n,e,r);return o?Fn(o):Ld(e)}function Ld(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function Fn(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function OH(e,t,n,r,i,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),r.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&i.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function jH(e,t,n,r,i,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${r.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),i?s.push(`Suggested home is ${i}.`):o&&s.push(`No exact suggested home: ${o}`),s}function BH(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 $H(e,t){return ex(t)-ex(e)||e.candidatePath.localeCompare(t.candidatePath)}function ex(e){let t=e.consumerFiles.length*10;return e.consumerCoverage==="exact"&&(t+=5),e.suggestedHome&&(t+=3),e.recommendedTier==="repository-level-review"&&(t*=.1),e.recommendedTier==="no-exact-consumers"&&(t*=.05),t}function HH(e){let t=new Set(["."]);for(let n of e){let r=Rt(Xr.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=Rt(Xr.dirname(r))}return t}function UH(e){let t=Nd(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function sx(e,t){let n=Rt(e),r=Rt(t);return r==="."||n===r||n.startsWith(`${r}/`)}function WH(e,t,n){let r=Nd(e),i=Nd(t);return(sx(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function ax(e,t,n,r){return Rt(e)===Rt(n)||!WH(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function GH(...e){let t=new Set(CH);for(let n of e)for(let r of n??[]){let i=zH(r);i&&t.add(i)}return t}function zH(e){let t=e.trim().toLowerCase();return t===""?null:t}function tx(e,t){return Md(e).includes(t)}function nx(e,t){let n=Md(e);return t.some(r=>n.includes(r))}function VH(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?SH.has(n):!1}function Rt(e){let t=hn(e);return t===""?".":t}function Nd(e){let t=hn(e);return t==="."?[]:t.split("/").filter(Boolean)}function Ad(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function cx(e){return Od([...e]).sort((t,n)=>t.localeCompare(n))}function Od(e){return[...new Set(e)]}function jd(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=[],m=MS(e,l,{limit:500,semanticEvidence:H});for(let f of l)for(let p of qH(e,f,i,m.get(f.symbolId)??[])){let g=`${p.file}|${p.shortName}`;if(p.symbolId!==null){if(a.has(p.symbolId))continue;a.add(p.symbolId)}else if(c.has(g))continue;c.add(g),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 qH(e,t,n,r){let i=r.filter(u=>!e.isIgnored(u.file)).filter(u=>!n||u.file.includes(n)),o=new Set(i.map(u=>u.file)),s=[];for(let u of KH(e,t,n)){if(o.has(u))continue;let d=Q(e,u),m=d.length>0?Dt(d,d[0].startLine):null;s.push({symbol:m?.symbol??u,file:u})}let a=[...i,...s],c=[],l=new Set;for(let u of a){let d=wi(e,u.symbol);if(!d){let f=`${u.file}|${u.symbol}`;if(l.has(f))continue;l.add(f),c.push({symbolId:null,symbol:u.symbol,shortName:I(u.symbol),file:u.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!JH(d))continue;let m=`${d.symbolId}|${d.relativePath}`;l.has(m)||(l.add(m),c.push({symbolId:d.symbolId,symbol:d.symbol,shortName:I(d.symbol),file:d.relativePath,symbolMatch:d}))}return c}function KH(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
|
|
719
719
|
FROM mentions m
|
|
720
720
|
JOIN chunks c ON m.chunk_id = c.id
|
|
721
721
|
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
@@ -723,48 +723,48 @@ Thumbs.db
|
|
|
723
723
|
AND m.role != 1
|
|
724
724
|
AND c.document_id != ?
|
|
725
725
|
${e.pathExclusionsFor("consumer_d")}
|
|
726
|
-
${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function
|
|
726
|
+
${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function JH(e){if(e.symbol.startsWith("scip-clojure ")||M(e.relativePath)==="clojure")return!0;let t=ue(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function Bd(e,t,n={}){let r=Oe(e,t);if(!r)return null;let i=YH(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=XH(e,i.relative_path),c=n.semantic===!1?new Map:wn(e,a);for(let l of a){let u=QH(e,i,l,c.get(l.symbolId)??new Set);s+=u,o.push({symbol:l.symbol,shortName:I(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:u,riskLevel:ZH(u)})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s}}function YH(e,t){return e.get(`SELECT id, relative_path FROM documents
|
|
727
727
|
WHERE relative_path = ?
|
|
728
728
|
${e.pathExclusionsFor("documents")}
|
|
729
|
-
LIMIT 1`,t)??null}function
|
|
729
|
+
LIMIT 1`,t)??null}function XH(e,t){return new _(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function QH(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
730
730
|
FROM mentions m
|
|
731
731
|
JOIN chunks c ON m.chunk_id = c.id
|
|
732
732
|
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
733
733
|
WHERE m.symbol_id = ?
|
|
734
734
|
AND m.role != 1
|
|
735
|
-
AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(o=>o.relative_path),...[...r].filter(o=>o!==t.relative_path)]).size}function
|
|
735
|
+
AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(o=>o.relative_path),...[...r].filter(o=>o!==t.relative_path)]).size}function ZH(e){return e>10?"high":e>0?"medium":"low"}function eU(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new _(e),a=tU(e,n,r,o),c=new $d;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(lx(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<=i&&d.length>0;g++){let y=s.calleeMap(d,{semantic:!1}),h=new Set;for(let x of d)for(let S of y.get(x.symbolId)??[])m.has(S.symbol)||h.add(S.symbol);let C=[];for(let x of h){m.add(x);let S=ux(e,x);if(!S||e.isIgnored(S.relativePath)||Ee(e,S.relativePath)||de(e,S.symbol,S.relativePath)||s.fileKind(S.relativePath)==="test"||s.hasSuppressionComment(S))continue;let b=rU(e,S,c);b.removable?C.push(nU(S,"cascade")):b.blockingFiles.length>0&&u.push({shortName:I(S.symbol),file:S.relativePath,blockingFiles:b.blockingFiles.slice(0,3)})}if(C.length===0)break;for(let x of C)c.add(x);l.push(lx(e,g,C,c)),d=C.map(x=>x.definition).filter(x=>x!==null)}let f=l.reduce((g,y)=>g+y.loc,0),p=l.reduce((g,y)=>g+y.entries.length,0);return{batches:l,totalSymbols:p,totalLoc:f,blocked:u}}function tU(e,t,n,r){let i=sr(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(Ee(e,s.relativePath)||de(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:ux(e,s.symbol)}));return o}function nU(e,t){return{symbol:e.symbol,shortName:I(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function ux(e,t){let n=e.get(`SELECT d.relative_path
|
|
736
736
|
FROM global_symbols gs
|
|
737
737
|
JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
738
738
|
JOIN documents d ON d.id = der.document_id
|
|
739
739
|
WHERE gs.symbol = ?
|
|
740
|
-
LIMIT 1`,t);return n?Q(e,n.relative_path).find(r=>r.symbol===t)??null:null}function
|
|
741
|
-
`).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}},t)}var
|
|
740
|
+
LIMIT 1`,t);return n?Q(e,n.relative_path).find(r=>r.symbol===t)??null:null}function rU(e,t,n){let r=ki(e,t);if(r.length===0)return{removable:!1,blockingFiles:[]};let i=new Set;for(let o of r)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||i.add(o.file);return{removable:i.size===0,blockingFiles:[...i]}}function lx(e,t,n,r){let i=[...n].sort((a,c)=>a.file.localeCompare(c.file)||a.startLine-c.startLine),o=new Set(i.map(a=>a.file)),s=[];for(let a of o){let c=Q(e,a);c.length>0&&c.every(l=>r.contains(a,l.startLine))&&s.push(a)}return{depth:t,entries:i.map(({definition:a,...c})=>c),loc:i.reduce((a,c)=>a+c.loc,0),filesEmptied:s.sort()}}var $d=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 r=this.ranges.get(t);return r?r.some(i=>n>=i.start&&n<=i.end):!1}};import{createHash as MV}from"crypto";import{existsSync as rc}from"fs";import{execFileSync as iU}from"child_process";var gx=2e3,$a=50,oU=64,sU=8,aU=3,cU=2160*60*60,lU=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,uU=3,dU=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,mU=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function fU(e){let t=J(e,{clearGroups:["whole-project"]});return(n,r,i)=>{let o=i??Hd(n.config.projectRoot);if(!o)return null;let s=t.has(n)?t.get(n,()=>({head:"",value:null})):null;return s&&s.head===o?s.value:(t.invalidate(n),t.get(n,()=>({head:o,value:r(n.config.projectRoot,o)})).value)}}function Ha(e){let t=J(e,{clearGroups:["whole-project"]});return(n,r,i,o)=>{let s=o??Hd(n.config.projectRoot);if(!s)return null;let a=t.has(n)?t.get(n,()=>({head:"",values:new Map})):null;(!a||a.head!==s)&&t.invalidate(n);let c=t.get(n,()=>({head:s,values:new Map}));if(c.values.has(r))return c.values.get(r)??null;let l=i(n.config.projectRoot,s);return c.values.set(r,l),l}}var pU=Ha("git-commit-history");function ze(e,t={}){let n=t.historyMode??"bounded",r=t.head;return{capability:i=>gU(e,i,r),commitHistory:()=>bo(e,n,r),fileChurn:()=>bU(e,n,r),changeAmplification:()=>SU(e,n,r),trackedFiles:()=>xU(e,r),fileAddRecords:()=>vU(e,n,r),coChangePairs:(i={})=>TU(e,i,n,r),coChangePairsForFiles:(i,o={})=>yx(e,i,o,n,r),directionalCoChangePairsForFiles:(i,o={})=>_U(e,i,o,n,r)}}function bo(e,t="bounded",n){return pU(e,Qr(t),(r,i)=>hU(r,i,t),n)}function gU(e,t,n){let r=n??Hd(e.config.projectRoot);return r?{slot:t,available:!0,head:r}:{slot:t,available:!1,head:null,reason:"git history is unavailable for this project"}}function Hd(e){try{return Mt(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function Mt(e,t){return iU("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"]})}function hU(e,t,n){let r;try{r=Mt(e,["log","--no-merges","--name-only",...Ua(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...zd(r,$a)}}function yU(e){return lU.test(e.subject)}function bU(e,t,n){let r=bo(e,t,n);if(!r)return null;let i=new Map;for(let o of r.commits){let s=yU(o);for(let a of o.files){let c=i.get(a)??{changes:0,fixChanges:0,lastChangedAt:0};c.changes+=1,s&&(c.fixChanges+=1),o.timestamp>c.lastChangedAt&&(c.lastChangedAt=o.timestamp),i.set(a,c)}}return i}function SU(e,t,n){let r=bo(e,t,n);if(!r||r.commits.length===0)return null;let i=r.commits.map(o=>o.files.length).filter(o=>o>0).sort((o,s)=>o-s);return i.length===0?null:{medianFilesPerCommit:dx(i,.5),p90FilesPerCommit:dx(i,.9),commitsAnalyzed:i.length}}function dx(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var CU=fU("git-tracked-files");function xU(e,t){return CU(e,n=>{try{let r=Mt(n,["ls-files"]);return new Set(r.split(`
|
|
741
|
+
`).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}},t)}var RU=Ha("git-file-adds"),mx="__git__/file-adds",fx=oe({kind:"git-file-adds",invalidation:K("git-file-adds"),serialize:wU,deserialize:DU});function Ud(e){return ze(e).fileAddRecords()}function vU(e,t,n){let r=Qr(t);return RU(e,r,(i,o)=>IU(e,i,o,t),n)}function IU(e,t,n,r){let i=fx.read(e,px(r),n);if(i)return i;let o=EU(t,r);return o&&fx.write(e,px(r),n,o),o}function wU(e){return JSON.stringify([...e.entries()])}function DU(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let r of t){if(!Array.isArray(r)||r.length!==2||typeof r[0]!="string")return null;let i=r[1];if(!i||typeof i.commitsAgo!="number"||!Number.isFinite(i.commitsAgo)||typeof i.addedAt!="number"||!Number.isFinite(i.addedAt))return null;n.set(r[0],{commitsAgo:i.commitsAgo,addedAt:i.addedAt})}return n}catch{return null}}function EU(e,t){let n;try{n=Mt(e,["log","--no-merges","--find-renames","--name-status",...Ua(t),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let r=new Map,i=new Map,o=-1;for(let s of n.split("")){if(s.trim()==="")continue;o+=1;let a=s.indexOf(`
|
|
742
742
|
`),c=a>=0?s.slice(0,a):s,[,l]=c.split("\0"),u=Number(l)||0;if(!(a<0))for(let d of s.slice(a+1).split(`
|
|
743
|
-
`)){let m=
|
|
744
|
-
`).map(m=>m.trim()).filter(m=>m!==""&&a.has(m)),l=
|
|
745
|
-
`).map(r=>r.trim()).filter(r=>r!=="").map(r=>{let[i,o]=r.split("\0");return{hash:i??"",timestamp:Number(o)||0}}).filter(r=>r.hash!=="")}function Ua(e){return e==="full"?[]:["-n",String(Sx())]}function Sx(){return
|
|
743
|
+
`)){let m=kU(d);if(!m)continue;if(m.status==="R"&&m.from&&m.to){let p=i.get(m.to)??new Set([m.to]);i.set(m.from,p);continue}if(m.status!=="A"||!m.to)continue;let f={commitsAgo:o,addedAt:u};r.set(m.to,f);for(let p of i.get(m.to)??[])r.set(p,f)}}return r}function kU(e){let t=e.trim().split(" "),n=t[0]??"";if(!n)return null;let r=n[0]??"";if(r==="R"){let o=t[1],s=t[2];return o&&s?{status:r,from:o,to:s}:null}let i=t[1];return i?{status:r,to:i}:null}var hx=Ha("git-co-change-pairs"),PU=Ha("git-directional-co-change-pairs");function TU(e,t,n,r){let i=`all\0${Qr(n)}\0${Wd(t)}`,o=hx(e,i,()=>{let s=bo(e,n,r);return s?Gd(s,t):null},r);return o&&[...o]}function yx(e,t,n,r,i){if(t.size===0)return[];let o=`files\0${Qr(r)}\0${bx(t)}\0${Wd(n)}`,s=hx(e,o,()=>{let a=bo(e,r,i);return a?Gd(a,n,t):null},i);return s&&[...s]}function _U(e,t,n,r,i){if(t.size===0)return[];let o=n.maxFilesPerCommit??$a;if(t.size>oU)return yx(e,t,n,r,i);let s=`directional\0${Qr(r)}\0${bx(t)}\0${Wd({...n,maxFilesPerCommit:o})}`,a=PU(e,s,(c,l)=>{let u=FU(c,l,t,o,r);return u?Gd(u,n,t):null},i);return a&&[...a]}function Wd(e){let t=e.minTogether??4,n=e.minConfidence??.6,r=e.maxFilesPerCommit??$a;return`${t}\0${n}\0${r}`}function bx(e){return[...e].sort().join("\0")}function Gd(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=$a}=t,s=new Map,a=new Map,c=e.newestAnalyzedAt??0;for(let d of e.commits){let m=[...new Set(d.files)].sort();if(m.length>o)continue;e.newestAnalyzedAt===void 0&&d.timestamp>c&&(c=d.timestamp);let f=AU(m),p=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(p)for(let g=0;g<m.length;g++)for(let y=g+1;y<m.length;y++){if(n&&!n.has(m[g])&&!n.has(m[y]))continue;let h=`${m[g]}\0${m[y]}`,C=a.get(h)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};C.together+=1,f?C.broadTogether+=1:C.focusedTogether+=1,d.timestamp>C.lastTogetherAt&&(C.lastTogetherAt=d.timestamp),C.timestamps.push(d.timestamp),C.subjects.push(d.subject),a.set(h,C)}}let l=[],u=c-cU;for(let[d,m]of a){let f=m.together;if(f<r)continue;let[p,g]=d.split("\0"),y=s.get(p)??f,h=s.get(g)??f,C=Math.max(f/y,f/h);if(C<i)continue;let x=m.broadTogether/f,S=m.timestamps.filter(b=>b>=u).length;l.push({fileA:p,fileB:g,together:f,confidence:C,changesA:y,changesB:h,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:x,lastTogetherAt:m.lastTogetherAt,recentTogether:S,commitScope:OU(m.broadTogether,f),recency:S>0?"recent":"stale",subjectContext:jU(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function FU(e,t,n,r,i){let o;try{o=LU(e,i)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=Mt(e,["log","--no-merges","--format=%H",...Ua(i),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(m=>m.hash)),c=s.split(`
|
|
744
|
+
`).map(m=>m.trim()).filter(m=>m!==""&&a.has(m)),l=NU(e,o,r);if(c.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:l};let u;try{u=Mt(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...c])}catch{return null}let d=zd(u,r);return{head:t,...d,newestAnalyzedAt:l}}function LU(e,t){return Mt(e,["log","--no-merges","--format=%H%x00%ct",...Ua(t)]).split(`
|
|
745
|
+
`).map(r=>r.trim()).filter(r=>r!=="").map(r=>{let[i,o]=r.split("\0");return{hash:i??"",timestamp:Number(o)||0}}).filter(r=>r.hash!=="")}function Ua(e){return e==="full"?[]:["-n",String(Sx())]}function Sx(){return Rn(process.env.SCIP_QUERY_GIT_HISTORY_MAX_COMMITS)??gx}function Qr(e){return e==="full"?"full":`bounded:${Sx()}`}function px(e){let t=Qr(e);return t===`bounded:${gx}`?mx:`${mx}:${t}`}function NU(e,t,n){for(let i=0;i<t.length;i+=20){let o=t.slice(i,i+20),s;try{s=Mt(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...o.map(c=>c.hash)])}catch{return t[0]?.timestamp??0}let a=zd(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function zd(e,t){let n=[],r=0;for(let i of e.split("")){if(i.trim()==="")continue;let o=i.indexOf(`
|
|
746
746
|
`),s=o>=0?i.slice(0,o):i,[a,c,l]=s.split("\0");if(!a||!c)continue;let u=o>=0?i.slice(o+1).split(`
|
|
747
|
-
`).map(d=>d.trim()).filter(d=>d!==""):[];if(u.length>t){r+=1;continue}n.push({hash:a,timestamp:Number(c)||0,subject:l??"",files:u})}return{commits:n,skippedBulkCommits:r}}function NU(e){return e.length>=oU?!0:AU(e).size>=sU}function AU(e){let t=new Set;for(let n of e){let r=n.indexOf("/");t.add(r>=0?n.slice(0,r):".")}return t}function MU(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function OU(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<lU&&r.push(i);for(let o of jU(i))t.add(o);for(let o of i.match(uU)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function jU(e){let t=new Set,n=dU.exec(e)?.[1]?.toLowerCase();return n&&t.add(BU(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 BU(e){return e==="feat"?"feature":e}import{existsSync as $U}from"fs";import{join as HU}from"path";function qd(e){return Vd.test(e)}var Vd=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|uv\.lock|poetry\.lock|Pipfile\.lock|bun\.lockb?|\.SRCINFO|CHANGELOG(?:\.[a-z]+)?|.*\.(?:map|tsbuildinfo))$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function So(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=ze(e,{historyMode:n.historyMode,...n.head?{head:n.head}:{}}),c=a.commitHistory(),l=t!==void 0,u=a.coChangePairs({minTogether:l?Math.min(r,2):r,minConfidence:l?0:i,maxFilesPerCommit:s});if(!c||!u)return{available:!1,commitsAnalyzed:0,findings:[]};let d=typeof n.scanLimit=="number"?u.slice(0,n.scanLimit):u,m=ie(e),f=Ix(e),p=Yd(e,m,f),g=n.includeLinked===!0||l,y=[];for(let h of d){if(Vd.test(h.fileA)||Vd.test(h.fileB)||!Cx(e,h.fileA)||!Cx(e,h.fileB)||l&&!h.fileA.includes(t)&&!h.fileB.includes(t)||!l&&(Y(h.fileA)==="test"||Y(h.fileB)==="test"||zU(h.fileA,h.fileB)||WU(h.fileA,h.fileB)))continue;let C=p(h.fileA,h.fileB);if(!g&&C)continue;let x=Kd(h.fileA,h.fileB),S=Jd(h,x,C);if(y.push({...h,structurallyLinked:C,partnerClass:x.partnerClass,partnerClassReasons:x.reasons,...S?{declaredCouplingSuggestion:S}:{}}),y.length>=o)break}return{available:!0,commitsAnalyzed:c.commits.length,findings:y}}function Cx(e,t){return $U(HU(e.config.projectRoot,t))}function Kd(e,t){let n=Rx(e),r=Rx(t),i=[],o=c=>{i.includes(c)||i.push(c)},s=(c,l)=>n.tags.has(c)&&r.tags.has(l)||n.tags.has(l)&&r.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:i};if(n.tags.has("test")||r.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:i};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:i};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:i};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:i};let a=nW(n.tokens,r.tokens).filter(c=>!eW.has(c));return vx(e,t)||a.length>=2?(o(vx(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:i}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:i})}function Jd(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!ZU.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${rW(r)}`,files:r,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function Yd(e,t=ie(e),n=Ix(e)){return(r,i)=>VU(t,n,r,i)}var UU=/(?:^|\/)(?:locales|i18n)\//i;function xx(e){return UU.test(e)}function WU(e,t){return xx(e)&&xx(t)?!0:GU(e,t)}function GU(e,t){if(!e.endsWith(".json")||!t.endsWith(".json"))return!1;let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(n<0||r<0)return!1;let i=e.slice(0,n),o=t.slice(0,r);if(i===o)return!1;let s=e.slice(n+1),a=t.slice(r+1);if(s!==a)return!1;let c=i.lastIndexOf("/"),l=o.lastIndexOf("/"),u=c>=0?i.slice(0,c):"",d=l>=0?o.slice(0,l):"";return u===d}function zU(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 Ix(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function VU(e,t,n,r){return e.get(n)?.has(r)===!0||e.get(r)?.has(n)===!0?!0:t.some(i=>i.has(n)&&i.has(r))}var qU=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,KU=/(?:^|\/)(?:\.[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,JU=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,YU=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,XU=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,QU=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,ZU=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),eW=new Set(["src","lib","app","apps","packages","frontend","backend","examples","python","typescript","javascript","test","tests","spec","index","main","utils","util","types","type","config","docs","doc","package","requirements","ts","tsx","js","jsx","mjs","cjs","vue","py","md","mdx","json","yaml","yml","toml","txt"]);function Rx(e){let t=e.replace(/\\/g,"/"),n=new Set;return qU.test(t)&&n.add("doc"),KU.test(t)&&n.add("config"),JU.test(t)&&n.add("schema"),YU.test(t)&&n.add("script"),XU.test(t)&&n.add("model"),QU.test(t)&&n.add("view"),Y(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:tW(t)}}function vx(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/"),i=n>=0?e.slice(0,n):"",o=r>=0?t.slice(0,r):"";return i!==""&&i===o}function tW(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 nW(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function rW(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as lr}from"child_process";import{existsSync as iW,readFileSync as oW}from"fs";import{basename as wx}from"path";function Wa(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=[],t.set(n.file,r)),r.push(n)}return t}var Co="Unable to compute git diff.";function Zr(e,t={}){let n=t.plan??Fn(e,t);return n.note?sW(n.note,n.changedFileLines):n.changedFiles.length===0?aW(n.changedFileLines):Ga(n.changedFiles,[Px(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function Fn(e,t={}){let{base:n="HEAD"}=t;try{let r=cW(e.config.projectRoot,n),i=r.changedFileLines,o=pW(e,i),s=gW(e,r.changedRanges);return{changedFileLines:i,changedFiles:o,changedRanges:s,renamedFiles:dW(e.config.projectRoot,n,o,r),note:i.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Co}}}function Px(e,t,n,r=[]){let i=new _(e),o=new Set(n),s=Wa(r),a=[],c=new Map,l=t.flatMap(S=>i.definitionsForFile(S)).filter(PW),u=l.filter(S=>yW(S,s)),d=SW(e,l,u,s),m=RW([...u,...d.definitions]).sort((S,b)=>S.relativePath.localeCompare(b.relativePath)||S.startLine-b.startLine),f=m.map(S=>S.symbolId),p=DW(e,f),g=EW(e,f,n),y=m.filter(S=>(p.get(S.symbolId)??0)===0),h=kx(()=>In(e,y)),C=y.filter(S=>(h.get(S.symbolId)?.size??0)===0),x=kx(()=>ao(e,C));for(let S of m)wW(e,S,o,a,c,h.get(S.symbolId)??new Set,x.get(S.symbolId)??new Set,p.get(S.symbolId)??0,g.get(S.symbolId)??new Set);return{changedSymbols:a,consumerEntries:[...c.entries()].map(([S,b])=>({file:S,symbols:[...b].sort()})),attributionNotes:d.notes}}function Ga(e,t){let n=new Map,r=t.flatMap(s=>s.changedSymbols),i=t.flatMap(s=>s.attributionNotes??[]);for(let s of t)for(let a of s.consumerEntries){let c=n.get(a.file);c||(c=new Set,n.set(a.file,c));for(let l of a.symbols)c.add(l)}let o=kW(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:o,attributionNotes:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:o.length}}}function sW(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function aW(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function cW(e,t){let n=lr("git",["diff","--name-status","--find-renames",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=lr("git",["diff","--name-status","--find-renames","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),i=lr("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),o=lr("git",["diff","--unified=0",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),s=lr("git",["diff","--unified=0","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),a=mW([n,r]);return{changedFileLines:[...new Set([...a.changedFiles,...Tx(i)])],changedRanges:Fx([...Ex(o),...Ex(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function Zd(e,t,n){try{return lr("git",["show",`${t}:./${n}`],{encoding:"utf-8",cwd:e,timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return null}}function xo(e,t,n=[]){let r=lW(e,t,n);return i=>(r.has(i)||r.set(i,Zd(e,t,i)),r.get(i)??null)}function Ro(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(r=>[r.to,r.from]));return[...new Set(t.map(r=>n.get(r)??r))]}function lW(e,t,n){let r=[...new Set(n)],i=new Map;if(r.length===0)return i;try{let o=r.map(a=>`${t}:./${a}
|
|
748
|
-
`).join(""),s=lr("git",["cat-file","--batch"],{cwd:e,input:o,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]});return
|
|
749
|
-
`).map(t=>t.trim()).filter(t=>t.length>0)}function
|
|
747
|
+
`).map(d=>d.trim()).filter(d=>d!==""):[];if(u.length>t){r+=1;continue}n.push({hash:a,timestamp:Number(c)||0,subject:l??"",files:u})}return{commits:n,skippedBulkCommits:r}}function AU(e){return e.length>=sU?!0:MU(e).size>=aU}function MU(e){let t=new Set;for(let n of e){let r=n.indexOf("/");t.add(r>=0?n.slice(0,r):".")}return t}function OU(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function jU(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<uU&&r.push(i);for(let o of BU(i))t.add(o);for(let o of i.match(dU)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function BU(e){let t=new Set,n=mU.exec(e)?.[1]?.toLowerCase();return n&&t.add($U(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 $U(e){return e==="feat"?"feature":e}import{existsSync as HU}from"fs";import{join as UU}from"path";function qd(e){return Vd.test(e)}var Vd=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|uv\.lock|poetry\.lock|Pipfile\.lock|bun\.lockb?|\.SRCINFO|CHANGELOG(?:\.[a-z]+)?|.*\.(?:map|tsbuildinfo))$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function So(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=ze(e,{historyMode:n.historyMode,...n.head?{head:n.head}:{}}),c=a.commitHistory(),l=t!==void 0,u=a.coChangePairs({minTogether:l?Math.min(r,2):r,minConfidence:l?0:i,maxFilesPerCommit:s});if(!c||!u)return{available:!1,commitsAnalyzed:0,findings:[]};let d=typeof n.scanLimit=="number"?u.slice(0,n.scanLimit):u,m=ie(e),f=Ix(e),p=Yd(e,m,f),g=n.includeLinked===!0||l,y=[];for(let h of d){if(Vd.test(h.fileA)||Vd.test(h.fileB)||!Cx(e,h.fileA)||!Cx(e,h.fileB)||l&&!h.fileA.includes(t)&&!h.fileB.includes(t)||!l&&(Y(h.fileA)==="test"||Y(h.fileB)==="test"||VU(h.fileA,h.fileB)||GU(h.fileA,h.fileB)))continue;let C=p(h.fileA,h.fileB);if(!g&&C)continue;let x=Kd(h.fileA,h.fileB),S=Jd(h,x,C);if(y.push({...h,structurallyLinked:C,partnerClass:x.partnerClass,partnerClassReasons:x.reasons,...S?{declaredCouplingSuggestion:S}:{}}),y.length>=o)break}return{available:!0,commitsAnalyzed:c.commits.length,findings:y}}function Cx(e,t){return HU(UU(e.config.projectRoot,t))}function Kd(e,t){let n=Rx(e),r=Rx(t),i=[],o=c=>{i.includes(c)||i.push(c)},s=(c,l)=>n.tags.has(c)&&r.tags.has(l)||n.tags.has(l)&&r.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:i};if(n.tags.has("test")||r.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:i};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:i};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:i};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:i};let a=rW(n.tokens,r.tokens).filter(c=>!tW.has(c));return vx(e,t)||a.length>=2?(o(vx(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:i}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:i})}function Jd(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!eW.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${iW(r)}`,files:r,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function Yd(e,t=ie(e),n=Ix(e)){return(r,i)=>qU(t,n,r,i)}var WU=/(?:^|\/)(?:locales|i18n)\//i;function xx(e){return WU.test(e)}function GU(e,t){return xx(e)&&xx(t)?!0:zU(e,t)}function zU(e,t){if(!e.endsWith(".json")||!t.endsWith(".json"))return!1;let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(n<0||r<0)return!1;let i=e.slice(0,n),o=t.slice(0,r);if(i===o)return!1;let s=e.slice(n+1),a=t.slice(r+1);if(s!==a)return!1;let c=i.lastIndexOf("/"),l=o.lastIndexOf("/"),u=c>=0?i.slice(0,c):"",d=l>=0?o.slice(0,l):"";return u===d}function VU(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 Ix(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function qU(e,t,n,r){return e.get(n)?.has(r)===!0||e.get(r)?.has(n)===!0?!0:t.some(i=>i.has(n)&&i.has(r))}var KU=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,JU=/(?:^|\/)(?:\.[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,YU=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,XU=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,QU=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,ZU=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,eW=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),tW=new Set(["src","lib","app","apps","packages","frontend","backend","examples","python","typescript","javascript","test","tests","spec","index","main","utils","util","types","type","config","docs","doc","package","requirements","ts","tsx","js","jsx","mjs","cjs","vue","py","md","mdx","json","yaml","yml","toml","txt"]);function Rx(e){let t=e.replace(/\\/g,"/"),n=new Set;return KU.test(t)&&n.add("doc"),JU.test(t)&&n.add("config"),YU.test(t)&&n.add("schema"),XU.test(t)&&n.add("script"),QU.test(t)&&n.add("model"),ZU.test(t)&&n.add("view"),Y(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:nW(t)}}function vx(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/"),i=n>=0?e.slice(0,n):"",o=r>=0?t.slice(0,r):"";return i!==""&&i===o}function nW(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 rW(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function iW(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as lr}from"child_process";import{existsSync as oW,readFileSync as sW}from"fs";import{basename as wx}from"path";function Wa(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=[],t.set(n.file,r)),r.push(n)}return t}var Co="Unable to compute git diff.";function Zr(e,t={}){let n=t.plan??Ln(e,t);return n.note?aW(n.note,n.changedFileLines):n.changedFiles.length===0?cW(n.changedFileLines):Ga(n.changedFiles,[Px(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function Ln(e,t={}){let{base:n="HEAD"}=t;try{let r=lW(e.config.projectRoot,n),i=r.changedFileLines,o=gW(e,i),s=hW(e,r.changedRanges);return{changedFileLines:i,changedFiles:o,changedRanges:s,renamedFiles:mW(e.config.projectRoot,n,o,r),note:i.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Co}}}function Px(e,t,n,r=[]){let i=new _(e),o=new Set(n),s=Wa(r),a=[],c=new Map,l=t.flatMap(S=>i.definitionsForFile(S)).filter(TW),u=l.filter(S=>bW(S,s)),d=CW(e,l,u,s),m=vW([...u,...d.definitions]).sort((S,b)=>S.relativePath.localeCompare(b.relativePath)||S.startLine-b.startLine),f=m.map(S=>S.symbolId),p=EW(e,f),g=kW(e,f,n),y=m.filter(S=>(p.get(S.symbolId)??0)===0),h=kx(()=>wn(e,y)),C=y.filter(S=>(h.get(S.symbolId)?.size??0)===0),x=kx(()=>ao(e,C));for(let S of m)DW(e,S,o,a,c,h.get(S.symbolId)??new Set,x.get(S.symbolId)??new Set,p.get(S.symbolId)??0,g.get(S.symbolId)??new Set);return{changedSymbols:a,consumerEntries:[...c.entries()].map(([S,b])=>({file:S,symbols:[...b].sort()})),attributionNotes:d.notes}}function Ga(e,t){let n=new Map,r=t.flatMap(s=>s.changedSymbols),i=t.flatMap(s=>s.attributionNotes??[]);for(let s of t)for(let a of s.consumerEntries){let c=n.get(a.file);c||(c=new Set,n.set(a.file,c));for(let l of a.symbols)c.add(l)}let o=PW(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:o,attributionNotes:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:o.length}}}function aW(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function cW(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function lW(e,t){let n=lr("git",["diff","--name-status","--find-renames",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=lr("git",["diff","--name-status","--find-renames","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),i=lr("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),o=lr("git",["diff","--unified=0",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),s=lr("git",["diff","--unified=0","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),a=fW([n,r]);return{changedFileLines:[...new Set([...a.changedFiles,...Tx(i)])],changedRanges:Fx([...Ex(o),...Ex(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function Zd(e,t,n){try{return lr("git",["show",`${t}:./${n}`],{encoding:"utf-8",cwd:e,timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return null}}function xo(e,t,n=[]){let r=uW(e,t,n);return i=>(r.has(i)||r.set(i,Zd(e,t,i)),r.get(i)??null)}function Ro(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(r=>[r.to,r.from]));return[...new Set(t.map(r=>n.get(r)??r))]}function uW(e,t,n){let r=[...new Set(n)],i=new Map;if(r.length===0)return i;try{let o=r.map(a=>`${t}:./${a}
|
|
748
|
+
`).join(""),s=lr("git",["cat-file","--batch"],{cwd:e,input:o,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]});return dW(s,r)}catch{for(let o of r)i.set(o,Zd(e,t,o));return i}}function dW(e,t){let n=new Map,r=0;for(let i of t){let o=e.indexOf(10,r);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(r,o).toString("utf-8");if(r=o+1,s.endsWith(" missing")){n.set(i,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,c,l]=a,u=Number(l);if(!Number.isFinite(u)||u<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(r+u>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(r,r+u);n.set(i,c==="blob"?d.toString("utf-8"):null),r+=u,e[r]===10&&(r+=1)}return n}function mW(e,t,n,r){if(n.length===0)return[];let i=new Map,o=new Set;for(let a of r.renamedFiles)n.includes(a.to)&&(i.set(a.to,a),o.add(a.from));let s=r.deletedFiles;if(s.length===0)return[...i.values()].sort((a,c)=>a.to.localeCompare(c.to));for(let a of n){if(i.has(a)||!oW(`${e}/${a}`))continue;let c=s.filter(d=>!o.has(d)).filter(d=>wx(d)===wx(a));if(c.length===0)continue;let l=sW(`${e}/${a}`,"utf-8"),u=c.map(d=>({from:d,to:a,similarity:pW(Zd(e,t,d)??"",l)})).sort((d,m)=>m.similarity-d.similarity)[0];u&&u.similarity>=.45&&(i.set(a,u),o.add(u.from))}return[...i.values()].sort((a,c)=>a.to.localeCompare(c.to))}function fW(e){let t=new Set,n=new Map,r=new Set;for(let i of e.flatMap(o=>Tx(o))){let[o,s,a]=i.split(" ");if(!(!o||!s)){if(o.startsWith("R")&&a){t.add(a),n.set(a,{from:s,to:a,similarity:Number(o.slice(1))/100});continue}t.add(s),o.startsWith("D")&&r.add(s)}}return{changedFiles:[...t],renamedFiles:[...n.values()],deletedFiles:[...r]}}function pW(e,t){let n=new Set(Dx(e)),r=new Set(Dx(t));if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let o of n)r.has(o)&&(i+=1);return 2*i/(n.size+r.size)}function Dx(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function Tx(e){return e.split(`
|
|
749
|
+
`).map(t=>t.trim()).filter(t=>t.length>0)}function gW(e,t){let n=_x(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function hW(e,t){let n=_x(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return Fx(r)}function _x(e){let t=e.all(`SELECT relative_path FROM documents
|
|
750
750
|
ORDER BY id`).map(r=>r.relative_path),n=new Map(t.map(r=>[r,r]));return r=>{let i=r.replace(/\\/g,"/"),o=n.get(i);return o||(t.find(s=>s.endsWith(i))??null)}}function Ex(e){let t=[],n=null;for(let r of e.split(`
|
|
751
|
-
`)){if(r.startsWith("+++ ")){n=
|
|
751
|
+
`)){if(r.startsWith("+++ ")){n=yW(r.slice(4).trim());continue}if(!n||!r.startsWith("@@ "))continue;let i=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(r);if(!i)continue;let o=Math.max(0,Number(i[1])-1),s=i[2]===void 0?1:Number(i[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function yW(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function Fx(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.startLine}:${r.endLine}`;t.has(i)||(t.add(i),n.push(r))}return n}function bW(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>em(e.startLine,e.endLine,r.startLine,r.endLine))}function SW(e,t,n){let r=new Map,i=[],o=Lx(e),s=IW(n);for(let a of t){let c=o.get(a.file)??[];if(c.some(d=>em(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let l=s.get(a.file)??[],u=wW(l,a);if(u){let d=c.find(m=>m.startLine>=u.startLine&&m.startLine<=u.endLine);if(d){r.set(d.symbolId,d),i.push(Xd(a,"ast-widened"));continue}}if(l.length===0){let d=[...c].filter(m=>m.startLine<=a.startLine).sort((m,f)=>f.startLine-m.startLine||m.endLine-f.endLine)[0];if(d){r.set(d.symbolId,d),i.push(Xd(a,"nearest-preceding"));continue}}i.push(Xd(a,"unattributed"))}return{definitions:[...r.values()],notes:i}}function CW(e,t,n,r){let i=Lx(n),o=[],s=[],a=[...new Set(t.map(c=>c.relativePath))];for(let c of a){let l=r.get(c)??[];if(l.length===0)continue;let u=i.get(c)??[];for(let d of l)u.some(m=>em(m.startLine,m.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===c)&&s.push(...xW(e,c))}return SW(t,o,s)}function xW(e,t){let n=q(e,t);return n?n.rootNode.namedChildren.filter(RW).map(r=>({file:t,startLine:r.startPosition.row,endLine:r.endPosition.row})).filter(r=>r.endLine>=r.startLine):[]}function RW(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function vW(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function Lx(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function IW(e){let t=new Map;for(let n of e){let r=t.get(n.file)??[];r.push(n),t.set(n.file,r)}return t}function wW(e,t){return e.filter(n=>n.startLine<=t.startLine&&n.endLine>=t.endLine).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine))[0]}function Xd(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function em(e,t,n,r){return e<=r&&n<=t}function DW(e,t,n,r,i,o,s,a,c){let l=Math.max(a,o.size,s.size);if(!_W(t,l))return;let u=I(t.symbol);r.push({symbol:t.symbol,shortName:u,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:l});for(let d of c)Qd(e,n,i,d,u);for(let d of o)Qd(e,n,i,d,u);for(let d of s)Qd(e,n,i,d,u)}function kx(e){try{return e()}catch(t){return console.error(`warning: diff-impact enrichment scan failed, continuing without it: ${t instanceof Error?t.message:t}`),new Map}}function EW(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
|
|
752
752
|
FROM mentions m
|
|
753
753
|
JOIN chunks c ON m.chunk_id = c.id
|
|
754
754
|
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
755
755
|
AND m.role != 1
|
|
756
|
-
GROUP BY m.symbol_id`,...t);return new Map(n.map(r=>[r.symbol_id,r.fan_in]))}function
|
|
756
|
+
GROUP BY m.symbol_id`,...t);return new Map(n.map(r=>[r.symbol_id,r.fan_in]))}function kW(e,t,n){if(t.length===0||n.length===0)return new Map;let r=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
|
|
757
757
|
FROM mentions m
|
|
758
758
|
JOIN chunks c ON m.chunk_id = c.id
|
|
759
759
|
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
760
760
|
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
761
761
|
AND m.role != 1
|
|
762
762
|
AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
|
|
763
|
-
${e.pathExclusionsFor("ref_d")}`,...t,...n),i=new Map;for(let o of r){let s=i.get(o.symbol_id);s||(s=new Set,i.set(o.symbol_id,s)),s.add(o.relative_path)}return i}function Qd(e,t,n,r,i){if(e.isIgnored(r)||t.has(r))return;let o=n.get(r);o||(o=new Set,n.set(r,o)),o.add(i)}function
|
|
764
|
-
`).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function ur(e,t){return t.filter(n=>e.includes(n))}var
|
|
765
|
-
`).toLowerCase(),n=[],r=ur(t,[".scipquery","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(r.length>0)return n.push(`configuration/example terms near citation: ${r.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let i=ur(t,["accepted","intentional","intentionally","retained","historical"]);if(i.length>0)return n.push(`intentional-record terms near citation: ${i.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=ur(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
|
|
766
|
-
${n}`.toLowerCase(),i=ur(r,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(i.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${i.join(", ")}`]};let o=ur(r,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function im(e,t,n=[]){let r=e==="co-change"||n.length===0?null:
|
|
767
|
-
`)}function Mt(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t>=0&&n>t)return e.slice(t+1,n);let r=e.indexOf("=>");return r>=0?e.slice(r+2).replace(/;+\s*$/,""):e}function bG(e){return Mt(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function SG(e){return yG("sha256").update(e).digest("hex").slice(0,16)}function Jx(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function Wx(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var CG=new Set(Ft());function xG(e,t={}){let{includeHomonyms:n=!1,limit:r}=t,i=ni(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return r?i.slice(0,r):i}function ni(e,t={}){let{scope:n,minSimilarity:r=.3,scanLimit:i}=t,o=IG(e,{scope:n,scanLimit:i});return Qx(o,{minSimilarity:r,isDelegatePair:VG(e)}).filter(s=>!s.members.some(a=>Uo(e,a.file,a.startLine,"twin")))}function Qx(e,t={}){let n=t.minSimilarity??.3,r=t.isDelegatePair,i=e.filter(l=>!oR(l.leaf)&&!AG(l.leaf)&&Y(l.file)!=="test"&&!Ie(l.symbol)&&!eR(l.symbol)&&!tR(l.symbol,l.leaf)),{recordsByLeaf:o,recordOrder:s}=w("twin-drift.group-by-leaf",()=>RG(i),()=>({records:i.length})),a=w("twin-drift.cluster-leaf-names",()=>Zx([...o.keys()]),()=>({leaves:o.size}));return w("twin-drift.compare-clusters",()=>{let l=[];for(let u of a){let d=vG(u,o,s);if(d.length<2||new Set(d.map(C=>C.file)).size<2)continue;let m=null,f=!1,p=!1,g=new Set;for(let C=0;C<d.length;C+=1)for(let x=C+1;x<d.length;x+=1){let S=d[C],b=d[x];if(S.file===b.file||!BG(S,b)||r?.(S,b,d)||r?.(b,S,d))continue;if(f=!0,g.add(S.symbol),g.add(b.symbol),S.normalizedBody===b.normalizedBody){p=!0;continue}let v=_G(S.tokens,b.tokens);(!m||v>m.similarity)&&(m={a:S,b,similarity:v})}if(!f)continue;let y=d.filter(C=>g.has(C.symbol)).sort((C,x)=>C.file.localeCompare(x.file)||C.startLine-x.startLine).map(TG);if(!m){l.push({leaf:Xx(u),relationship:p?"identical":"homonym",maxDivergence:0,members:y});continue}let h=m.similarity>=n?"divergent":"homonym";l.push({leaf:Xx(u),relationship:h,maxDivergence:Math.round((1-m.similarity)*1e3)/1e3,members:y,...h==="divergent"?{firstDivergentTokens:FG(m.a.tokens,m.b.tokens)}:{}})}return l},()=>({clusters:a.length,records:i.length})).sort((l,u)=>u.members.length-l.members.length||u.maxDivergence-l.maxDivergence||l.leaf.localeCompare(u.leaf))}function RG(e){let t=new Map,n=new Map;for(let[r,i]of e.entries()){let o=t.get(i.leaf)??[];o.push(i),t.set(i.leaf,o),n.set(i,r)}return{recordsByLeaf:t,recordOrder:n}}function vG(e,t,n){let r=[...e].flatMap(i=>t.get(i)??[]);return e.size>1&&r.sort((i,o)=>(n.get(i)??0)-(n.get(o)??0)),r}function IG(e,t){let n=w("twin-drift.load-definitions",()=>xe(e,{scope:t.scope}).filter(o=>wG(o)&&!e.isIgnored(o.relativePath)).filter(o=>!Gr(o.relativePath)));w("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let r=se(n,t.scanLimit),i=w("twin-drift.select-candidates",()=>DG(r),()=>({scanned:r.length}));return w("twin-drift.build-records",()=>{let o=[];for(let s of i){let a=EG(e,s);a&&o.push(a)}return o},()=>({candidates:i.length,scanned:r.length}))}function wG(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&CG.has(e.kind):!0:!1}function DG(e){let t=e.filter(o=>o.leaf&&!oR(o.leaf)&&!Ie(o.symbol)&&!eR(o.symbol)&&!tR(o.symbol,o.leaf)),n=new Map;for(let o of t){let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}let r=Zx([...n.keys()]),i=new Set;for(let o of r){let s=[...o].flatMap(a=>n.get(a)??[]);if(!(s.length<2)&&!(new Set(s.map(a=>a.relativePath)).size<2)&&!s.every(a=>Y(a.relativePath)==="test"))for(let a of s)i.add(a)}return e.filter(o=>i.has(o))}function EG(e,t){if(!t.leaf)return null;let n=an(e,t);if(!n||!le(t.symbol)&&!kG(n,t.leaf))return null;let r=rt(Mt(n)),i=r.replace(/\s+/g,"");if(!i||i.length<8)return null;let o=r.match(PG)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:I(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:O(t),normalizedBody:i,tokens:o,isThinForwarder:rR(r)}}function kG(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b(?:const|let|var)\\s+${n}(?:\\s*:[^=]+)?\\s*=\\s*(?:async\\s*)?(?:\\([^)]*\\)|[A-Za-z_$][\\w$]*)\\s*=>`,"s").test(e)}var PG=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function TG(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function _G(e,t){let n=new Set(e),r=new Set(t);if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let s of n)r.has(s)&&(i+=1);let o=n.size+r.size-i;return o===0?0:i/o}function FG(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;let i=e.slice(r,r+6).join(" "),o=t.slice(r,r+6).join(" ");return!i&&!o?"(bodies differ only in trailing length)":`A: ${i||"(end)"} | B: ${o||"(end)"}`}function Zx(e){let t=new Map;for(let s of e)t.set(s,s);let n=s=>{let a=s;for(;t.get(a)!==a;)a=t.get(a);let c=s;for(;t.get(c)!==a;){let l=t.get(c);t.set(c,a),c=l}return a},r=(s,a)=>{let c=n(s),l=n(a);c!==l&&t.set(c,l)},i=new Map;for(let s of e){let a=s.slice(0,2).toLowerCase(),c=i.get(a)??[];c.push(s),i.set(a,c)}for(let s of i.values())for(let a=0;a<s.length;a+=1)for(let c=a+1;c<s.length;c+=1)LG(s[a],s[c])&&r(s[a],s[c]);let o=new Map;for(let s of e){let a=n(s),c=o.get(a)??new Set;c.add(s),o.set(a,c)}return[...o.values()]}function LG(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||NG(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:$G(e.toLowerCase(),t.toLowerCase(),2)}function NG(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function AG(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||MG.has(e.toLowerCase())}var MG=new Set(["main","row"]),OG=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function eR(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var jG=new Set(["default","new","reset"]);function tR(e,t){return e.startsWith("rust-analyzer ")&&jG.has(t.toLowerCase())}function BG(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=Yx(e);return[...Yx(t)].some(r=>n.has(r))}function Yx(e){let t=e.leaf.toLowerCase();return new Set(`${e.file}/${e.shortName}`.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(n=>n.length>2&&n!==t&&!OG.has(n)))}function $G(e,t,n){if(Math.abs(e.length-t.length)>n)return!1;let r=Array.from({length:t.length+1},(i,o)=>o);for(let i=1;i<=e.length;i+=1){let o=[i],s=o[0];for(let a=1;a<=t.length;a+=1){let c=e[i-1]===t[a-1]?0:1,l=Math.min(r[a]+1,o[a-1]+1,r[a-1]+c);o.push(l),s=Math.min(s,l)}if(s>n)return!1;r=o}return r[t.length]<=n}function nR(e){return rR(rt(Mt(e)))}function rR(e){let t=e.trim();if(!t||HG.test(t))return!1;let n=GG(t);return n.length===0||n.length>2?!1:WG(n[n.length-1])}var HG=/\b(?:if|else|for|while|switch|try|catch|do)\b/,UG=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function WG(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return UG.test(t)}function GG(e){let t=[],n=0,r="";for(let i of e){if(i==="("||i==="["||i==="{"?n+=1:(i===")"||i==="]"||i==="}")&&(n=Math.max(0,n-1)),i===";"&&n===0){t.push(r),r="";continue}r+=i}return r.trim()&&t.push(r),t.map(i=>i.trim()).filter(i=>i.length>0)}var zG=3;function VG(e){let t=new Map;return(n,r,i)=>{if(!n.isThinForwarder)return!1;let o=`${n.symbol}\0${r.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=iR(e,n,r,i,zG,new Set);return t.set(o,a),a}}function iR(e,t,n,r,i,o){if(i<=0||o.has(t.symbol)||(o.add(t.symbol),(pn(e,t.file)??[]).filter(c=>c.line>=t.startLine&&c.line<=t.endLine&&c.calleeLeaf===n.leaf).length===0))return!1;let a=new Set(re(e,t.file).filter(c=>c.sourcePath&&(c.kind!=="namespace"||c.usedMembers.includes(n.leaf))).map(c=>c.sourcePath));if([...a].some(c=>Ve(c,n.file)))return!0;for(let c of r)if(!(c.symbol===t.symbol||c.symbol===n.symbol||!c.isThinForwarder)&&[...a].some(l=>Ve(l,c.file))&&iR(e,c,n,r,i-1,o))return!0;return!1}function oR(e){return e.startsWith("<")&&e.endsWith(">")}function Xx(e){return[...e].sort()[0]}import{readFileSync as qG,readdirSync as KG}from"fs";import{basename as JG,join as cm}from"path";function YG(e,t,n={}){let r=new Set(e),i=new Set(t),o=[...i].filter(a=>!r.has(a)).sort(),s=n.allowExtra?[]:[...r].filter(a=>!i.has(a)).sort();return{missing:o,extra:s}}function lm(e,t){let n=XG(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let r=rz(e.config.projectRoot,t.mustEqual),i=YG(n.keys,r,{allowExtra:t.allowExtra??!1}),o=i.missing.length>0||i.extra.length>0?"violated":"ok";return{name:t.name,file:t.file,status:o,missing:i.missing,extra:i.extra}}function aR(e,t){return t.map(n=>lm(e,n))}function cR(e,t){if(t.has(e.file))return!0;let n=e.mustEqual;switch(n.type){case"top-level-dirs":return[...t].some(r=>r===n.path||r.startsWith(`${n.path}/`));case"file-glob":return[...t].some(r=>ar(n.pattern,r));case"registered-commands":return t.has("docs/COMMAND_REFERENCE.md");case"builtin-skills":return[...t].some(r=>r.startsWith("skills/"))}}function lR(e){if(e.status==="unavailable")return`[coverage-contract] ${e.name}: DISCLOSED \u2014 could not evaluate (${e.unavailableReason})`;let t=[];return e.missing.length>0&&t.push(`missing ${e.missing.join(", ")}`),e.extra.length>0&&t.push(`extra ${e.extra.join(", ")}`),`[coverage-contract] ${e.name}: ${t.join("; ")}`}function XG(e,t,n){return n.type==="markdown-list"?nz(e,t,n.marker):QG(e,t,n)}function QG(e,t,n){if(!P(e,t))return{ok:!1,reason:`file not found: ${t}`};let i=M(t);if(!i)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=q(e,t);if(!o)return{ok:!1,reason:`tree-sitter parser unavailable for ${i} (${t}) \u2014 contract skipped, not silently passed`,disclosedUnavailable:{language:i,reason:"parser-unavailable"}};let s=n.type==="object-literal-keys"?ZG(o,n.identifier):tz(o,n.identifier);return s===null?{ok:!1,reason:`no ${n.type==="object-literal-keys"?"object literal":"string array"} named "${n.identifier}" found in ${t}`}:{ok:!0,keys:s}}function uR(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function ZG(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=uR(n);if(i?.type==="object")return ez(i)}return null}function ez(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let r=n.childForFieldName("key");r&&t.add(dR(r.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function tz(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=uR(n);if(i?.type!=="array")continue;let o=new Set;for(let s of i.namedChildren)s.type==="string"&&o.add(dR(s.text));return[...o].sort()}return null}function dR(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function nz(e,t,n){let r=P(e,t);if(!r)return{ok:!1,reason:`file not found: ${t}`};let i=mR(r,n);return i===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:fR(i)}}function mR(e,t){let n=$(t),i=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return i?i[1]:null}function fR(e){let t=new Set;for(let n of e.matchAll(/`([a-z][a-z0-9-]*)`/g))t.add(n[1]);for(let n of e.matchAll(/\[([a-z][a-z0-9-]*)\]\([^)]*\)/g))t.add(n[1]);return[...t].sort()}function rz(e,t){switch(t.type){case"top-level-dirs":return sR(cm(e,t.path));case"file-glob":return[...new Set(dC(e,t.pattern).map(n=>JG(n)))].sort();case"registered-commands":return iz(e);case"builtin-skills":return sR(cm(e,"skills"))}}function sR(e){let t;try{t=KG(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function iz(e){let t;try{t=qG(cm(e,"docs/COMMAND_REFERENCE.md"),"utf-8")}catch{return[]}let n=mR(t,"COMMAND REFERENCE");return n?fR(n):[]}import{existsSync as RR,readFileSync as vR,writeFileSync as cV}from"fs";import{isAbsolute as lV,join as uV}from"path";var me={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0},isolated:{minLoc:3},similar:{minSimilarity:.6,limit:50,minCallees:4},duplicateBodies:{maxLoc:15,limit:50},extract:{minLoc:15,minCallees:5,limit:50},wrappers:{maxLoc:15,limit:50},passthroughs:{maxLoc:15,limit:50},stale:{minLoc:3,limit:50},drift:{},twinDrift:{minSimilarity:.3}};import wo from"path";function Eo(e,t){let{scope:n,minDeviation:r=5,limit:i=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,c=new _(e).fileDependencyGraph(n),l=qr(e,{scope:n}),u=lz([...oz(e,c,{scope:n,semantic:o}),...az(l.forbiddenEdges),...s?cz(c,r):[]]);return t?.includeArchitecture===!0&&(u.architecture=l),i<=0||u.results.length<=i?u:{...u,results:u.results.slice(0,i),totalResults:u.results.length}}function oz(e,t,n){let r=mz(e,n.scope),i=[],o=new Set;for(let[a,c]of t){if(Do(a))continue;let l=r.get(a)??new Set;for(let u of c)Do(u)||l.has(u)||sz(e,a,u,n)||(i.push({file:a,dep:u}),o.add(a))}o.size>0&&gz(e,r,{paths:[...o]});let s=[];for(let{file:a,dep:c}of i)(r.get(a)??new Set).has(c)||s.push({file:a,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."});return s}function sz(e,t,n,r){return bz(e,t,n)||Sz(e,t,n)||hz(n)||xz(e,t,n)||Cz(n)?!0:r.semantic&&yz(e,t,n)}function az(e){return e.flatMap(t=>{let n=t.examples[0];return n?[{file:n.fromFile,kind:"architecture-violation",description:`${t.from} depends on forbidden boundary ${t.to} through ${t.fileEdgeCount} file edge(s)`,dep:n.toFile,detail:`${t.from} may not depend on ${t.to}`,actionTier:"direct",policyBasis:"explicit",architecture:{fromBoundary:t.from,toBoundary:t.to,fileEdgeCount:t.fileEdgeCount,importerCount:t.importerCount,importedFileCount:t.importedFileCount,examples:t.examples},evidenceReasons:[`configured dependency row for ${t.from} does not allow ${t.to}`,`${t.fileEdgeCount} file edge(s) connect ${t.importerCount} importer(s) to ${t.importedFileCount} imported file(s)`,...t.examples.map(r=>`${r.fromFile} imports ${r.toFile}`)],recommendation:"Move the dependency behind an allowed boundary, reverse the dependency through an owned interface, or deliberately update the project architecture rule."}]:[]})}function cz(e,t){let n=[];for(let[r,i]of uz(e)){let o=i.filter(a=>!Do(a));if(o.length<t)continue;let s=dz(e,o);for(let a of o)for(let c of e.get(a)??[])Do(c)||(s.get(c)??0)===1&&wo.dirname(c)!==r&&wo.dirname(c)!==wo.dirname(r)&&n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${r}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."})}return n}function lz(e){let t=e.filter(n=>n.kind==="architecture-violation").length;return{results:e,unusedImports:e.filter(n=>n.kind==="unused-import").length,architectureViolations:t,layerViolations:t,patternDeviations:e.filter(n=>n.kind==="pattern-deviation").length}}function uz(e){let t=new Map;for(let n of e.keys()){let r=wo.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function dz(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Do(i)||n.set(i,(n.get(i)??0)+1);return n}function mz(e,t){let n=new Map;return fz(e,n,t),n}function fz(e,t,n){for(let r of pz(e,n))pR(e,t,r.from_file,r.to_file)}function pz(e,t){let n=t?"AND d1.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
|
|
763
|
+
${e.pathExclusionsFor("ref_d")}`,...t,...n),i=new Map;for(let o of r){let s=i.get(o.symbol_id);s||(s=new Set,i.set(o.symbol_id,s)),s.add(o.relative_path)}return i}function Qd(e,t,n,r,i){if(e.isIgnored(r)||t.has(r))return;let o=n.get(r);o||(o=new Set,n.set(r,o)),o.add(i)}function PW(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function TW(e){return!(pn(e.symbol)||e.parentTypeName!==null&&!le(e.symbol))}function _W(e,t){return le(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}function tm(e){let[t,n]=ei(e,":"),r=t||"unknown",i=(o={})=>{let s=o.actionTier??FW(r);return{sourceAnalyzer:r,actionTier:s,rootCauseKey:o.rootCauseKey??(n||e),label:o.label??`${r} finding`,relatedFiles:o.relatedFiles??[],why:o.why??[],remediation:o.remediation??LW(s,r),file:o.file}};if(!n)return i({rootCauseKey:e,why:["Baseline identity did not include analyzer payload."]});if(["dead","isolated","extract","wrapper","passthrough","stale"].includes(r)){let[o,s]=ei(n,":");return i({file:o,relatedFiles:o?[o]:[],rootCauseKey:s?`${o}:${s}`:n,label:`${r} finding`,why:s?[`Baseline subject: ${s}.`]:[]})}if(r==="cycle"){let o=n.split(">").filter(Boolean);return i({relatedFiles:o,rootCauseKey:n,label:"cycle finding",why:o.length>0?[`Cycle path: ${o.join(" > ")}.`]:[]})}if(r==="similar"){let o=n.split("|").filter(Boolean);return i({relatedFiles:[],rootCauseKey:n,label:"similarity finding",why:o.length>0?[`Similar symbols: ${o.join(" | ")}.`]:[]})}if(r==="architecture"){let[o,s]=ei(n,":");if(o==="forbidden-edge"){let[a,c]=ei(s,":"),l=za(a),u=za(c);return i({actionTier:"direct",rootCauseKey:n,label:"architecture boundary violation",why:[`Declared boundary rule rejects ${l} -> ${u}.`],remediation:`Move the dependency behind an allowed boundary, or deliberately update the ${l} dependency rule and baseline.`})}if(o==="cycle"){let a=s.split("|").filter(Boolean).map(za);return i({actionTier:"direct",rootCauseKey:n,label:"forbidden architecture cycle",why:[`requireAcyclic rejects the connected boundary group: ${a.join(", ")}.`],remediation:"Break the boundary cycle, or deliberately revise the acyclicity rule and baseline."})}if(o==="missing-policy-row"){let a=za(s);return i({actionTier:"direct",rootCauseKey:n,label:"incomplete architecture policy",why:[`requireCompletePolicy rejects the missing outgoing dependency row for ${a}.`],remediation:`Declare the allowed outgoing dependencies for ${a}, including an empty row when it must depend on nothing.`})}}if(r==="drift"){let[o,s]=ei(n,":"),[a,c]=ei(s,":");return i({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 i({why:["Baseline analyzer prefix is not recognized by this diff-gate version."]})}function FW(e){switch(e){case"dead":case"isolated":case"cycle":case"passthrough":case"architecture":return"direct";case"similar":case"extract":case"wrapper":case"stale":return"signal";default:return"signal"}}function LW(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 ei(e,t){let n=e.indexOf(t);return n<0?[e,""]:[e.slice(0,n),e.slice(n+t.length)]}function za(e){try{return decodeURIComponent(e)}catch{return e}}import{existsSync as BW,readFileSync as Mx}from"fs";function Ka(e,t){let n=NW(e,t)??AW(e,t)??MW(e,t)??OW(e,t);return jW(e,n,t)}function NW(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=nm(e[i]??"");o&&(r===null?(r=o,n=i):o===r&&(r=null,n=-1))}if(r===null||n<0)return null;for(let i=t+1;i<e.length;i+=1)if(nm(e[i]??"")===r)return{start:n,end:i+1};return{start:n,end:e.length}}function nm(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function AW(e,t){if(!Va(e[t]??""))return null;let n=t;for(;n>0&&Va(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&Va(e[r]??"");)r+=1;return{start:n,end:r}}function Va(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function MW(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(qa(o)!==null)break;if(rm(o)!==null)return null;n-=1}if(n<0)return null;let r=qa(e[n]??"");if(r===null)return null;let i=n+1;for(;i<e.length;){let o=e[i]??"",s=qa(o);if(s!==null){if(s<=r)break;i+=1;continue}if(rm(o)!==null)break;i+=1}return{start:n,end:i}}function qa(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function OW(e,t){let n=e[t]??"";if(Ax(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&Nx(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&Nx(e[i]??"");)i+=1;return{start:r,end:i}}function Nx(e){return rm(e)===null}function rm(e){return e.trim().length===0?"blank":Ax(e)?"heading":nm(e)?"fence":Va(e)?"table":qa(e)!==null?"list":null}function Ax(e){return/^#{1,6}\s+/.test(e.trim())}function jW(e,t,n){let{start:r,end:i}=t;if(i-r>40){let s=Math.floor(20);r=Math.max(r,n-s),i=Math.min(i,r+40),r=Math.max(t.start,i-40)}let o=e.slice(r,i).join(`
|
|
764
|
+
`).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function ur(e,t){return t.filter(n=>e.includes(n))}var $W=/<!--\s*scip-query:\s*snapshot\s*-->/i;function Ja(e,t){if((e.config.docs?.snapshotPaths??[]).some(i=>ar(i,t)))return!0;let r=P(e,t);return r.length>0&&$W.test(r)}var an={classifyCitation:UW,citationContexts:WW,citationKindLabel:zW,citationRemediation:VW,referenceTargets:qW,hasLineAnchoredCitation:HW};function HW(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function UW(e){let t=e.join(`
|
|
765
|
+
`).toLowerCase(),n=[],r=ur(t,[".scipquery","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(r.length>0)return n.push(`configuration/example terms near citation: ${r.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let i=ur(t,["accepted","intentional","intentionally","retained","historical"]);if(i.length>0)return n.push(`intentional-record terms near citation: ${i.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=ur(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 WW(e,t,n){let r;try{r=Mx(`${e.config.projectRoot}/${t}`,"utf-8").split(/\r?\n/)}catch{return[]}let i=n.flatMap(GW),o=[];for(let s=0;s<r.length;s+=1){let a=r[s]??"";i.some(c=>a.includes(c))&&o.push(Ka(r,s))}return o}function GW(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,r,i)=>n.length>0&&i.indexOf(n)===r)}function zW(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 VW(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 qW(e,t,n){let r=Wa(n),i=new Set;for(let o of t)KW(e,o,r.get(o)??[])&&i.add(o);return i}function KW(e,t,n){if(!JW.test(t))return!0;let r=`${e.config.projectRoot}/${t}`;if(!BW(r))return!0;if(n.length===0)return!1;let i=Mx(r,"utf-8").split(/\r?\n/),o=YW(i);for(let s of n)for(let a=s.startLine;a<=s.endLine;a+=1)if((i[a]??"").trim()!==""&&!o.has(a))return!0;return!1}var JW=/\.(?:[cm]?[jt]sx?)$/i;function YW(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&XW(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function XW(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}import{existsSync as jx,readFileSync as om,statSync as QW}from"fs";import{join as ti}from"path";var Ox=oe({kind:"doc-path-evidence",invalidation:K("doc-path-evidence"),serialize:fG,deserialize:pG}),vo=/\.(?:md|mdx|rst|txt)$/i;function ZW(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var eG=3,tG=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function nG(e,t={}){let{doc:n,limit:r=20,minCoupling:i=eG,includeSnapshotExcluded:o=!1}=t,s=sG(e,t.historyMode??"bounded");if(!s)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let a=[];for(let c of s.docFiles){if(n!==void 0&&!c.includes(n)||n===void 0&&!$x(e,c)||n!==void 0&&!jx(ti(e.config.projectRoot,c)))continue;let l=Ja(e,c);if(l&&!o)continue;let{value:u,estimated:d}=rG(e,c,s.changeTimes.get(c)),m=iG(e,c),f=new Map,{resolved:p,broken:g,citations:y}=lG(e,c,s.tracked,s.trackedBySuffix,s.everSeenInHistory),h=new Map(y.map(x=>[x.file,x]));for(let x of p){if(x===c||vo.test(x))continue;let S=(s.changeTimes.get(x)??[]).filter(v=>v>u).length;if(S===0)continue;let b=h.get(x);f.set(x,{file:x,evidence:"reference",coChanges:0,changesSinceDocUpdate:S,...im("reference",m,b?.contexts),citationContexts:b?.contexts,citedLines:b?.lineReferences})}for(let[x,S]of s.coupling.get(c)??[]){if(S<i||!s.tracked.has(x))continue;let b=(s.changeTimes.get(x)??[]).filter(R=>R>u).length;if(b===0)continue;let v=f.get(x);v?(v.evidence="both",v.coChanges=S,Object.assign(v,im("both",m,v.citationContexts))):f.set(x,{file:x,evidence:"co-change",coChanges:S,changesSinceDocUpdate:b,...im("co-change",m)})}if(f.size===0&&g.length===0)continue;let C=[...f.values()].sort((x,S)=>S.changesSinceDocUpdate-x.changesSinceDocUpdate);a.push({doc:c,docLastChangedAt:u,staleness:C.reduce((x,S)=>x+S.changesSinceDocUpdate,0)+g.length*10,subjects:C.slice(0,8),brokenReferences:g,...l?{snapshotExcluded:!0}:{},...d?{docLastChangedAtEstimated:!0}:{}})}return a.sort((c,l)=>l.staleness-c.staleness),{available:!0,commitsAnalyzed:s.historyCommitCount,docsScanned:s.docFiles.length,findings:a.slice(0,r)}}function rG(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(QW(ti(e.config.projectRoot,t)).mtimeMs/1e3),estimated:!0}}catch{return{value:0,estimated:!1}}}function iG(e,t){let n;try{n=om(ti(e.config.projectRoot,t),"utf8").slice(0,6e3)}catch{return{docIntent:"unknown",reasons:["doc text unavailable"]}}let r=`${t}
|
|
766
|
+
${n}`.toLowerCase(),i=ur(r,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(i.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${i.join(", ")}`]};let o=ur(r,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function im(e,t,n=[]){let r=e==="co-change"||n.length===0?null:an.classifyCitation(n);return{actionTier:oG(e,t.docIntent,r?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...r?{citationKind:r.citationKind,citationKindReasons:r.reasons}:{}}}function oG(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function sG(e,t){let n=ze(e,{historyMode:t}),r=n.commitHistory();if(!r)return null;let i=n.trackedFiles()??new Set,o=new Map,s=new Map,a=new Set;for(let c of r.commits){let l=[...new Set(c.files)],u=l.filter(m=>vo.test(m)),d=l.filter(m=>!vo.test(m));for(let m of l){a.add(m);let f=o.get(m)??[];f.push(c.timestamp),o.set(m,f)}for(let m of u){let f=s.get(m);f||(f=new Map,s.set(m,f));for(let p of d)f.set(p,(f.get(p)??0)+1)}}return{changeTimes:o,coupling:s,docFiles:[...i].filter(c=>vo.test(c)),everSeenInHistory:a,historyCommitCount:r.commits.length,tracked:i,trackedBySuffix:Hx(i)}}function Bx(e,t){if(t.size===0)return[];let n=U(),r=0,i=0,o=0,s=0,a=0,c=0;return w("doc-reference.docs-citing-files",()=>{let l=ze(e).trackedFiles()??new Set;r=l.size;let u=Hx(l),d=aG(t,u),m=[];for(let f of l){if(!$x(e,f))continue;n&&(i+=1);let p;try{p=om(ti(e.config.projectRoot,f),"utf-8")}catch{n&&(o+=1);continue}if(!dG(p,d)){n&&(s+=1);continue}let g=Ux(e,f,p);if(!g)continue;n&&(a+=1);let y=cG(g.candidates,t,d,l,u);if(y.size===0)continue;let h=[...new Set([...y.values()].flatMap(b=>[...b]))],C=uG(g.contextsByCandidate,h),x=[...y].map(([b,v])=>({file:b,contexts:Ya([...v].flatMap(R=>C.get(R)??[])).slice(0,3),lineReferences:Xa([...v].flatMap(R=>g.lineReferencesByCandidate.get(R)??[]))})).filter(b=>b.contexts.length>0),S=[...y.keys()];if(S.length>0){n&&(c+=1);let b=S.sort();m.push({doc:f,cited:b,citations:x,citedClaims:Ya(x.flatMap(v=>v.contexts)).slice(0,3)})}}return m},()=>({targets:t.size,trackedFiles:r,livingDocs:i,unreadableDocs:o,candidateMisses:s,evidenceDocs:a,citedDocs:c}))}function $x(e,t){return vo.test(t)&&!ZW(t)&&jx(ti(e.config.projectRoot,t))}function Hx(e){let t=new Map;for(let n of e){let r=n.split("/");for(let i of[2,3]){if(r.length<i)continue;let o=r.slice(-i).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function aG(e,t){let n=new Set(e);for(let r of e){let i=r.split("/");for(let o of[2,3]){if(i.length<o)continue;let s=i.slice(-o).join("/"),a=t.get(s);a?.length===1&&a[0]===r&&n.add(s)}}return n}function cG(e,t,n,r,i){let o=new Map;for(let s of e){if(!n.has(s))continue;let a;if(t.has(s))a=s;else if(r.has(s))a=s;else{let l=i.get(s);l?.length===1&&(a=l[0])}if(!a||!t.has(a))continue;let c=o.get(a)??new Set;c.add(s),o.set(a,c)}return o}function lG(e,t,n,r,i){let o=new Set,s=new Set,a=Ux(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=a.candidates,l=a.contextsByCandidate,u=a.lineReferencesByCandidate,d=new Map,m=new Map,f=(p,g)=>{let y=l.get(g);if(y&&y.length>0){let C=d.get(p)??[];C.push(...y),d.set(p,Ya(C).slice(0,3))}let h=u.get(g);h&&h.length>0&&m.set(p,Xa([...m.get(p)??[],...h]))};for(let p of c){if(n.has(p)){o.add(p),f(p,p);continue}let g=r.get(p);if(g&&g.length===1){o.add(g[0]),f(g[0],p);continue}g&&g.length>1||i.has(p)&&s.add(p)}return{resolved:o,broken:[...s],citations:[...d].map(([p,g])=>({file:p,contexts:g,lineReferences:m.get(p)}))}}function uG(e,t){let n=new Map;for(let r of t){let i=e.get(r);i&&i.length>0&&n.set(r,[...i])}return n}function Ux(e,t,n){let r=n;if(r===void 0)try{r=om(ti(e.config.projectRoot,t),"utf-8")}catch{return null}let i=ce(e,t,r),o=Ox.read(e,t,i);if(o)return o;let s=mG(r);return Ox.write(e,t,i,s),s}function dG(e,t){for(let n of t)if(e.includes(n))return!0;return!1}function mG(e){let t=e.split(/\r?\n/),n=new Set,r=new Map,i=new Map;for(let o=0;o<t.length;o+=1){let s=t[o]??"";for(let a of s.matchAll(tG)){let c=(a[1]??"").replace(/^\.?\//,"");if(c.length===0)continue;n.add(c);let l=a[2]?Number(a[2]):null;l!==null&&Number.isSafeInteger(l)&&i.set(c,Xa([...i.get(c)??[],l]));let u=Ka(t,o);if(u.length===0)continue;let d=r.get(c)??[];d.push(u),r.set(c,Ya(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:r,lineReferencesByCandidate:i}}function fG(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function pG(e){try{let t=JSON.parse(e);if(!wt(t))return null;let n=Me(t.candidates),r=hG(t.contextsByCandidate),i=gG(t.lineReferencesByCandidate);return!n||!r?null:{candidates:n,contextsByCandidate:new Map(r),lineReferencesByCandidate:new Map(i??[])}}catch{return null}}function gG(e){if(e===void 0)return[];if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||!Array.isArray(n[1]))return null;let r=[];for(let i of n[1]){if(typeof i!="number"||!Number.isSafeInteger(i))return null;r.push(i)}t.push([n[0],Xa(r)])}return t}function hG(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string")return null;let r=Me(n[1]);if(!r)return null;t.push([n[0],r])}return t}function Ya(e){let t=[];for(let n of new Set(e))t.some(r=>yG(r,n))||t.push(n);return t}function Xa(e){return[...new Set(e)].sort((t,n)=>t-n)}function yG(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=Math.min(n.length,r.length);if(i===0)return!1;if(i<3)return e.includes(t)||t.includes(e);let o=new Set(r),s=n.filter(a=>o.has(a)).length;return s>=3&&s/i>=.6}import{createHash as bG}from"crypto";var Gx=3;function Io(e,t={}){let{scope:n,maxLoc:r=15,minLoc:i=Gx,limit:o,scanLimit:s}=t,a=Ud(e),c=qx(e,{scope:n,maxLoc:r,scanLimit:s}).map(u=>Kx(e,u,a,i)).filter(u=>u!==null),l=Vx(c);return o?l.slice(0,o):l}function sm(e,t,n={}){let{scope:r,maxLoc:i=15,minLoc:o=Gx,scanLimit:s}=n,a=Ud(e),c=qx(e,{scope:r,maxLoc:i,scanLimit:s}).map(u=>Kx(e,u,a,o)).filter(u=>u!==null),l=c.find(u=>u.symbol===t);return l?c.filter(u=>u.symbol!==l.symbol&&u.normalizedBody===l.normalizedBody&&u.file!==l.file).sort(Jx).map(({normalizedBody:u,...d})=>d):[]}function zx(e){let t=Ot(e);return st(t).replace(/\s+/g,"")}function Vx(e){let t=new Map;for(let r of e){if(r.normalizedBody.length<8)continue;let i=CG(r.normalizedBody),o=t.get(i)??[];o.push(r),t.set(i,o)}let n=[];for(let[r,i]of t){let o=new Set(i.map(a=>a.file));if(i.length<2||o.size<2)continue;let s=[...i].sort(Jx).map(({normalizedBody:a,...c})=>c);n.push({hash:r,canonical:s[0],functions:s})}return n.sort((r,i)=>{let o=i.functions.length-r.functions.length;if(o!==0)return o;let s=Wx(i)-Wx(r);return s!==0?s:r.canonical.file.localeCompare(i.canonical.file)}),n}function qx(e,t){let n=xe(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>!Uo(e,r.relativePath,r.startLine,"similar")).filter(r=>O(r)<=t.maxLoc);return n.sort((r,i)=>O(i)-O(r)||r.relativePath.localeCompare(i.relativePath)),se(n,t.scanLimit)}function Kx(e,t,n,r){let i=cn(e,t);if(!i||SG(i)<r)return null;let o=am(e,t);return o?{symbol:t.symbol,shortName:I(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:O(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function am(e,t){let n=cn(e,t);return n&&zx(n)||null}function cn(e,t){let n=Ce(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
|
|
767
|
+
`)}function Ot(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t>=0&&n>t)return e.slice(t+1,n);let r=e.indexOf("=>");return r>=0?e.slice(r+2).replace(/;+\s*$/,""):e}function SG(e){return Ot(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function CG(e){return bG("sha256").update(e).digest("hex").slice(0,16)}function Jx(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function Wx(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var xG=new Set(Lt());function RG(e,t={}){let{includeHomonyms:n=!1,limit:r}=t,i=ni(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return r?i.slice(0,r):i}function ni(e,t={}){let{scope:n,minSimilarity:r=.3,scanLimit:i}=t,o=wG(e,{scope:n,scanLimit:i});return Qx(o,{minSimilarity:r,isDelegatePair:qG(e)}).filter(s=>!s.members.some(a=>Uo(e,a.file,a.startLine,"twin")))}function Qx(e,t={}){let n=t.minSimilarity??.3,r=t.isDelegatePair,i=e.filter(l=>!oR(l.leaf)&&!MG(l.leaf)&&Y(l.file)!=="test"&&!Ie(l.symbol)&&!eR(l.symbol)&&!tR(l.symbol,l.leaf)),{recordsByLeaf:o,recordOrder:s}=w("twin-drift.group-by-leaf",()=>vG(i),()=>({records:i.length})),a=w("twin-drift.cluster-leaf-names",()=>Zx([...o.keys()]),()=>({leaves:o.size}));return w("twin-drift.compare-clusters",()=>{let l=[];for(let u of a){let d=IG(u,o,s);if(d.length<2||new Set(d.map(C=>C.file)).size<2)continue;let m=null,f=!1,p=!1,g=new Set;for(let C=0;C<d.length;C+=1)for(let x=C+1;x<d.length;x+=1){let S=d[C],b=d[x];if(S.file===b.file||!$G(S,b)||r?.(S,b,d)||r?.(b,S,d))continue;if(f=!0,g.add(S.symbol),g.add(b.symbol),S.normalizedBody===b.normalizedBody){p=!0;continue}let v=FG(S.tokens,b.tokens);(!m||v>m.similarity)&&(m={a:S,b,similarity:v})}if(!f)continue;let y=d.filter(C=>g.has(C.symbol)).sort((C,x)=>C.file.localeCompare(x.file)||C.startLine-x.startLine).map(_G);if(!m){l.push({leaf:Xx(u),relationship:p?"identical":"homonym",maxDivergence:0,members:y});continue}let h=m.similarity>=n?"divergent":"homonym";l.push({leaf:Xx(u),relationship:h,maxDivergence:Math.round((1-m.similarity)*1e3)/1e3,members:y,...h==="divergent"?{firstDivergentTokens:LG(m.a.tokens,m.b.tokens)}:{}})}return l},()=>({clusters:a.length,records:i.length})).sort((l,u)=>u.members.length-l.members.length||u.maxDivergence-l.maxDivergence||l.leaf.localeCompare(u.leaf))}function vG(e){let t=new Map,n=new Map;for(let[r,i]of e.entries()){let o=t.get(i.leaf)??[];o.push(i),t.set(i.leaf,o),n.set(i,r)}return{recordsByLeaf:t,recordOrder:n}}function IG(e,t,n){let r=[...e].flatMap(i=>t.get(i)??[]);return e.size>1&&r.sort((i,o)=>(n.get(i)??0)-(n.get(o)??0)),r}function wG(e,t){let n=w("twin-drift.load-definitions",()=>xe(e,{scope:t.scope}).filter(o=>DG(o)&&!e.isIgnored(o.relativePath)).filter(o=>!Gr(o.relativePath)));w("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let r=se(n,t.scanLimit),i=w("twin-drift.select-candidates",()=>EG(r),()=>({scanned:r.length}));return w("twin-drift.build-records",()=>{let o=[];for(let s of i){let a=kG(e,s);a&&o.push(a)}return o},()=>({candidates:i.length,scanned:r.length}))}function DG(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&xG.has(e.kind):!0:!1}function EG(e){let t=e.filter(o=>o.leaf&&!oR(o.leaf)&&!Ie(o.symbol)&&!eR(o.symbol)&&!tR(o.symbol,o.leaf)),n=new Map;for(let o of t){let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}let r=Zx([...n.keys()]),i=new Set;for(let o of r){let s=[...o].flatMap(a=>n.get(a)??[]);if(!(s.length<2)&&!(new Set(s.map(a=>a.relativePath)).size<2)&&!s.every(a=>Y(a.relativePath)==="test"))for(let a of s)i.add(a)}return e.filter(o=>i.has(o))}function kG(e,t){if(!t.leaf)return null;let n=cn(e,t);if(!n||!le(t.symbol)&&!PG(n,t.leaf))return null;let r=st(Ot(n)),i=r.replace(/\s+/g,"");if(!i||i.length<8)return null;let o=r.match(TG)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:I(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:O(t),normalizedBody:i,tokens:o,isThinForwarder:rR(r)}}function PG(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b(?:const|let|var)\\s+${n}(?:\\s*:[^=]+)?\\s*=\\s*(?:async\\s*)?(?:\\([^)]*\\)|[A-Za-z_$][\\w$]*)\\s*=>`,"s").test(e)}var TG=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function _G(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function FG(e,t){let n=new Set(e),r=new Set(t);if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let s of n)r.has(s)&&(i+=1);let o=n.size+r.size-i;return o===0?0:i/o}function LG(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;let i=e.slice(r,r+6).join(" "),o=t.slice(r,r+6).join(" ");return!i&&!o?"(bodies differ only in trailing length)":`A: ${i||"(end)"} | B: ${o||"(end)"}`}function Zx(e){let t=new Map;for(let s of e)t.set(s,s);let n=s=>{let a=s;for(;t.get(a)!==a;)a=t.get(a);let c=s;for(;t.get(c)!==a;){let l=t.get(c);t.set(c,a),c=l}return a},r=(s,a)=>{let c=n(s),l=n(a);c!==l&&t.set(c,l)},i=new Map;for(let s of e){let a=s.slice(0,2).toLowerCase(),c=i.get(a)??[];c.push(s),i.set(a,c)}for(let s of i.values())for(let a=0;a<s.length;a+=1)for(let c=a+1;c<s.length;c+=1)NG(s[a],s[c])&&r(s[a],s[c]);let o=new Map;for(let s of e){let a=n(s),c=o.get(a)??new Set;c.add(s),o.set(a,c)}return[...o.values()]}function NG(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||AG(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:HG(e.toLowerCase(),t.toLowerCase(),2)}function AG(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function MG(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||OG.has(e.toLowerCase())}var OG=new Set(["main","row"]),jG=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function eR(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var BG=new Set(["default","new","reset"]);function tR(e,t){return e.startsWith("rust-analyzer ")&&BG.has(t.toLowerCase())}function $G(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=Yx(e);return[...Yx(t)].some(r=>n.has(r))}function Yx(e){let t=e.leaf.toLowerCase();return new Set(`${e.file}/${e.shortName}`.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(n=>n.length>2&&n!==t&&!jG.has(n)))}function HG(e,t,n){if(Math.abs(e.length-t.length)>n)return!1;let r=Array.from({length:t.length+1},(i,o)=>o);for(let i=1;i<=e.length;i+=1){let o=[i],s=o[0];for(let a=1;a<=t.length;a+=1){let c=e[i-1]===t[a-1]?0:1,l=Math.min(r[a]+1,o[a-1]+1,r[a-1]+c);o.push(l),s=Math.min(s,l)}if(s>n)return!1;r=o}return r[t.length]<=n}function nR(e){return rR(st(Ot(e)))}function rR(e){let t=e.trim();if(!t||UG.test(t))return!1;let n=zG(t);return n.length===0||n.length>2?!1:GG(n[n.length-1])}var UG=/\b(?:if|else|for|while|switch|try|catch|do)\b/,WG=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function GG(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return WG.test(t)}function zG(e){let t=[],n=0,r="";for(let i of e){if(i==="("||i==="["||i==="{"?n+=1:(i===")"||i==="]"||i==="}")&&(n=Math.max(0,n-1)),i===";"&&n===0){t.push(r),r="";continue}r+=i}return r.trim()&&t.push(r),t.map(i=>i.trim()).filter(i=>i.length>0)}var VG=3;function qG(e){let t=new Map;return(n,r,i)=>{if(!n.isThinForwarder)return!1;let o=`${n.symbol}\0${r.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=iR(e,n,r,i,VG,new Set);return t.set(o,a),a}}function iR(e,t,n,r,i,o){if(i<=0||o.has(t.symbol)||(o.add(t.symbol),(gn(e,t.file)??[]).filter(c=>c.line>=t.startLine&&c.line<=t.endLine&&c.calleeLeaf===n.leaf).length===0))return!1;let a=new Set(re(e,t.file).filter(c=>c.sourcePath&&(c.kind!=="namespace"||c.usedMembers.includes(n.leaf))).map(c=>c.sourcePath));if([...a].some(c=>Ve(c,n.file)))return!0;for(let c of r)if(!(c.symbol===t.symbol||c.symbol===n.symbol||!c.isThinForwarder)&&[...a].some(l=>Ve(l,c.file))&&iR(e,c,n,r,i-1,o))return!0;return!1}function oR(e){return e.startsWith("<")&&e.endsWith(">")}function Xx(e){return[...e].sort()[0]}import{readFileSync as KG,readdirSync as JG}from"fs";import{basename as YG,join as cm}from"path";function XG(e,t,n={}){let r=new Set(e),i=new Set(t),o=[...i].filter(a=>!r.has(a)).sort(),s=n.allowExtra?[]:[...r].filter(a=>!i.has(a)).sort();return{missing:o,extra:s}}function lm(e,t){let n=QG(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let r=iz(e.config.projectRoot,t.mustEqual),i=XG(n.keys,r,{allowExtra:t.allowExtra??!1}),o=i.missing.length>0||i.extra.length>0?"violated":"ok";return{name:t.name,file:t.file,status:o,missing:i.missing,extra:i.extra}}function aR(e,t){return t.map(n=>lm(e,n))}function cR(e,t){if(t.has(e.file))return!0;let n=e.mustEqual;switch(n.type){case"top-level-dirs":return[...t].some(r=>r===n.path||r.startsWith(`${n.path}/`));case"file-glob":return[...t].some(r=>ar(n.pattern,r));case"registered-commands":return t.has("docs/COMMAND_REFERENCE.md");case"builtin-skills":return[...t].some(r=>r.startsWith("skills/"))}}function lR(e){if(e.status==="unavailable")return`[coverage-contract] ${e.name}: DISCLOSED \u2014 could not evaluate (${e.unavailableReason})`;let t=[];return e.missing.length>0&&t.push(`missing ${e.missing.join(", ")}`),e.extra.length>0&&t.push(`extra ${e.extra.join(", ")}`),`[coverage-contract] ${e.name}: ${t.join("; ")}`}function QG(e,t,n){return n.type==="markdown-list"?rz(e,t,n.marker):ZG(e,t,n)}function ZG(e,t,n){if(!P(e,t))return{ok:!1,reason:`file not found: ${t}`};let i=M(t);if(!i)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=q(e,t);if(!o)return{ok:!1,reason:`tree-sitter parser unavailable for ${i} (${t}) \u2014 contract skipped, not silently passed`,disclosedUnavailable:{language:i,reason:"parser-unavailable"}};let s=n.type==="object-literal-keys"?ez(o,n.identifier):nz(o,n.identifier);return s===null?{ok:!1,reason:`no ${n.type==="object-literal-keys"?"object literal":"string array"} named "${n.identifier}" found in ${t}`}:{ok:!0,keys:s}}function uR(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function ez(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=uR(n);if(i?.type==="object")return tz(i)}return null}function tz(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let r=n.childForFieldName("key");r&&t.add(dR(r.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function nz(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=uR(n);if(i?.type!=="array")continue;let o=new Set;for(let s of i.namedChildren)s.type==="string"&&o.add(dR(s.text));return[...o].sort()}return null}function dR(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function rz(e,t,n){let r=P(e,t);if(!r)return{ok:!1,reason:`file not found: ${t}`};let i=mR(r,n);return i===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:fR(i)}}function mR(e,t){let n=$(t),i=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return i?i[1]:null}function fR(e){let t=new Set;for(let n of e.matchAll(/`([a-z][a-z0-9-]*)`/g))t.add(n[1]);for(let n of e.matchAll(/\[([a-z][a-z0-9-]*)\]\([^)]*\)/g))t.add(n[1]);return[...t].sort()}function iz(e,t){switch(t.type){case"top-level-dirs":return sR(cm(e,t.path));case"file-glob":return[...new Set(dC(e,t.pattern).map(n=>YG(n)))].sort();case"registered-commands":return oz(e);case"builtin-skills":return sR(cm(e,"skills"))}}function sR(e){let t;try{t=JG(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function oz(e){let t;try{t=KG(cm(e,"docs/COMMAND_REFERENCE.md"),"utf-8")}catch{return[]}let n=mR(t,"COMMAND REFERENCE");return n?fR(n):[]}import{existsSync as RR,readFileSync as vR,writeFileSync as lV}from"fs";import{isAbsolute as uV,join as dV}from"path";var me={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0},isolated:{minLoc:3},similar:{minSimilarity:.6,limit:50,minCallees:4},duplicateBodies:{maxLoc:15,limit:50},extract:{minLoc:15,minCallees:5,limit:50},wrappers:{maxLoc:15,limit:50},passthroughs:{maxLoc:15,limit:50},stale:{minLoc:3,limit:50},drift:{},twinDrift:{minSimilarity:.3}};import wo from"path";function Eo(e,t){let{scope:n,minDeviation:r=5,limit:i=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,c=new _(e).fileDependencyGraph(n),l=qr(e,{scope:n}),u=uz([...sz(e,c,{scope:n,semantic:o}),...cz(l.forbiddenEdges),...s?lz(c,r):[]]);return t?.includeArchitecture===!0&&(u.architecture=l),i<=0||u.results.length<=i?u:{...u,results:u.results.slice(0,i),totalResults:u.results.length}}function sz(e,t,n){let r=fz(e,n.scope),i=[],o=new Set;for(let[a,c]of t){if(Do(a))continue;let l=r.get(a)??new Set;for(let u of c)Do(u)||l.has(u)||az(e,a,u,n)||(i.push({file:a,dep:u}),o.add(a))}o.size>0&&hz(e,r,{paths:[...o]});let s=[];for(let{file:a,dep:c}of i)(r.get(a)??new Set).has(c)||s.push({file:a,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."});return s}function az(e,t,n,r){return Sz(e,t,n)||Cz(e,t,n)||yz(n)||Rz(e,t,n)||xz(n)?!0:r.semantic&&bz(e,t,n)}function cz(e){return e.flatMap(t=>{let n=t.examples[0];return n?[{file:n.fromFile,kind:"architecture-violation",description:`${t.from} depends on forbidden boundary ${t.to} through ${t.fileEdgeCount} file edge(s)`,dep:n.toFile,detail:`${t.from} may not depend on ${t.to}`,actionTier:"direct",policyBasis:"explicit",architecture:{fromBoundary:t.from,toBoundary:t.to,fileEdgeCount:t.fileEdgeCount,importerCount:t.importerCount,importedFileCount:t.importedFileCount,examples:t.examples},evidenceReasons:[`configured dependency row for ${t.from} does not allow ${t.to}`,`${t.fileEdgeCount} file edge(s) connect ${t.importerCount} importer(s) to ${t.importedFileCount} imported file(s)`,...t.examples.map(r=>`${r.fromFile} imports ${r.toFile}`)],recommendation:"Move the dependency behind an allowed boundary, reverse the dependency through an owned interface, or deliberately update the project architecture rule."}]:[]})}function lz(e,t){let n=[];for(let[r,i]of dz(e)){let o=i.filter(a=>!Do(a));if(o.length<t)continue;let s=mz(e,o);for(let a of o)for(let c of e.get(a)??[])Do(c)||(s.get(c)??0)===1&&wo.dirname(c)!==r&&wo.dirname(c)!==wo.dirname(r)&&n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${r}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."})}return n}function uz(e){let t=e.filter(n=>n.kind==="architecture-violation").length;return{results:e,unusedImports:e.filter(n=>n.kind==="unused-import").length,architectureViolations:t,layerViolations:t,patternDeviations:e.filter(n=>n.kind==="pattern-deviation").length}}function dz(e){let t=new Map;for(let n of e.keys()){let r=wo.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function mz(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Do(i)||n.set(i,(n.get(i)??0)+1);return n}function fz(e,t){let n=new Map;return pz(e,n,t),n}function pz(e,t,n){for(let r of gz(e,n))pR(e,t,r.from_file,r.to_file)}function gz(e,t){let n=t?"AND d1.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
|
|
768
768
|
FROM mentions m
|
|
769
769
|
JOIN chunks c ON m.chunk_id = c.id
|
|
770
770
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -780,23 +780,23 @@ ${n}`.toLowerCase(),i=ur(r,["historical note","historical record","history note"
|
|
|
780
780
|
WHERE d1.id != d2.id
|
|
781
781
|
AND m.role != 1
|
|
782
782
|
${e.pathExclusionsFor("d1","d2")}
|
|
783
|
-
${n}`,...r)}function
|
|
784
|
-
`),o=$(r);return new RegExp(`^\\s*export\\s+(?:default\\s+)?(?:(?:async\\s+)?function\\s+${o}\\b|(?:const|let|var)\\s+${o}\\b)`,"m").test(i)?!0:
|
|
785
|
-
`),o=Math.max(0,n-2),s=Math.min(i.length-1,n+2);for(let a=o;a<=s;a++){let l=(i[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
|
|
786
|
-
`);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function
|
|
783
|
+
${n}`,...r)}function hz(e,t,n={}){new _(e).scanSourceReferences({paths:n.paths??N(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||pR(e,t,i.sourceFile,i.target.relativePath))})}function pR(e,t,n,r){if(e.isIgnored(n)||e.isIgnored(r))return;let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(r)}function yz(e){return e.includes("types")||e.endsWith(".d.ts")}function bz(e,t,n){let r=Wi(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function Sz(e,t,n){let r=re(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function Cz(e,t,n){let r=re(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function xz(e){return e.endsWith(".vue")}function Rz(e,t,n){let r=re(e,t).filter(i=>i.sourcePath===n);return r.length===0?!1:r.every(i=>i.kind==="side-effect"||i.kind==="namespace"&&i.usedMembers.length===0&&!i.used)}function Do(e){let t=Y(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||vz(wo.basename(e)))}function vz(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 gR,extname as hR}from"path";function Qa(e,t,n,r,i,o){let s=new Set;wz(e,t,n,r)&&s.add(i);for(let a of o)a.value&&Iz(s,a.label,a.value);return[...s].slice(0,6)}function Iz(e,t,n){let r=Dz(n);t.endsWith("name")&&Ez(r)&&e.add(`${t} has type-guard boundary shape`);for(let i of r){let o=kz.get(i);o&&e.add(`${t} has ${o} term: ${i}`)}}function wz(e,t,n,r){if(n<=0)return!1;let i=Ce(e,t);if(i.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(i[o]??"").trim();if(s!==""){if(di(s)===r)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function Dz(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 Ez(e){return e.some(t=>Pz.has(t))&&e.some(t=>Tz.has(t))}var kz=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"]]),Pz=new Set(["can","has","is","should"]),Tz=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function ko(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new _(e);return gt({candidates:()=>jz(e,s,n,r),orderCandidates:Pa,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>_z(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function _z(e,t,n){let r=Oz(n);if(r.size!==1||!Wc(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=Fz(e,t,i),s=Nz(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:I(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:O(t),forwardsTo:i.symbol,forwardsToShort:I(i.symbol),forwardsToFile:i.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:Lz(a,o,s)}}function Fz(e,t,n){return Qa(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:I(t.symbol)},{label:"callee name",value:I(n.symbol)},{label:"passthrough module",value:gR(t.relativePath,hR(t.relativePath))},{label:"callee module",value:gR(n.file,hR(n.file))}])}function Lz(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 r=t.filter(Mz);return r.length>0?`Review the public API before inlining; public-surface evidence: ${r.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 Nz(e,t){return Po(e,t)?ir(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:de(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function Po(e,t){let n=Ce(e,t.relativePath);if(n.length===0)return!1;let r=T(t.symbol);if(!r)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
|
|
784
|
+
`),o=$(r);return new RegExp(`^\\s*export\\s+(?:default\\s+)?(?:(?:async\\s+)?function\\s+${o}\\b|(?:const|let|var)\\s+${o}\\b)`,"m").test(i)?!0:Az(n,r)}function Az(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${$(t)}\\b`);return e.some(r=>n.test(r))}function Mz(e){return e.includes("public surface")}function Oz(e){let t=e.some(r=>ee(r.symbol))?e.filter(r=>ee(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function jz(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(i=>!gi(e,i))}function To(e,t){let{scope:n,minLoc:r=3,maxLoc:i=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new _(e),u=l.scopedDefinitions(n),d=Yz(l,n),m={high:0,medium:1,low:2};return gt({candidates:()=>Bz(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(f,p)=>O(p)-O(f)||f.relativePath.localeCompare(p.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:f=>{let p=Hz(f),g=$z(e,l,f,p,{semantic:c}),y=f.filter(h=>{let C=Za(e,h,g,p);return C.realConsumers.length<=1&&!C.transitivelyReachable&&yR(h,C.realConsumers.length,d)});return{consumerFileMap:g,singletonBackedClassIds:Gz(e,l,u,y,{semantic:c}),candidateIndex:p}},evaluate:(f,p)=>{if(p.singletonBackedClassIds.has(f.symbolId))return null;let g=Za(e,f,p.consumerFileMap,p.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!yR(g.definition,g.realConsumers.length,d))return null;let y=Uz(e,g);return!s&&y.confidence==="low"?null:y},orderResults:(f,p)=>m[f.confidence]-m[p.confidence]||p.loc-f.loc||f.file.localeCompare(p.file)||f.startLine-p.startLine,limit:o})}function Bz(e,t,n,r){return n.filter(i=>i.isTypeLike&&O(i)>=r.minLoc).filter(i=>O(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>!i.relativePath.endsWith(".d.ts")).filter(i=>Y(i.relativePath)!=="test").filter(i=>!de(e,i.symbol,i.relativePath)).filter(i=>!Xz(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function um(e,t,n,r){return sn(on(e,t).forDefinitions(n,{semantic:r.semantic,sourceFallback:r.sourceFallback}))}function $z(e,t,n,r,i){let o=um(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(l=>{let u=Za(e,l,o,r);return u.realConsumers.length<=1&&!(u.realConsumers.length>0&&dm(l.relativePath))}),a=i.semantic&&s.length>0?rn(o,um(e,t,s,{semantic:!0,sourceFallback:!1})):o,c=s.filter(l=>Za(e,l,a,r).realConsumers.length<=1);return rn(a,um(e,t,c,{semantic:!1,sourceFallback:!0}))}function Hz(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);r||(r=new Map,t.set(n.relativePath,r));let i=T(n.symbol);i&&r.set(i,n)}return t}function Za(e,t,n,r){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=Ba(e,t,o),l=Qz(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function Uz(e,t){let n=SR(e,t.definition.relativePath,t.definition.startLine),r=dm(t.definition.relativePath)?!0:Zz(e,t.definition),{confidence:i,reason:o}=eV(t.realConsumers.length,n,r),s=Wz(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:I(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:O(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function Wz(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 Gz(e,t,n,r,i){let o=Vz(e,zz(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=sn(on(e,t).forDefinitions(s,{semantic:i.semantic,sourceFallback:!0})),c=new Set;for(let{singleton:l,classId:u}of o)Kz(e,l,a)&&c.add(u);return c}function zz(e){let t=new Map;for(let n of e){let r=T(n.symbol);r&&t.set(bR(n.relativePath,r),n)}return t}function Vz(e,t,n){let r=[];for(let i of n){let o=qz(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function qz(e,t,n){if(SR(e,n.relativePath,n.startLine)!=="class")return null;let r=T(n.symbol);if(!r)return null;let i=Jz(e,n.relativePath,r);return i?t.get(bR(n.relativePath,i))??null:null}function Kz(e,t,n){let r=T(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!Fd(e,o,r))}function bR(e,t){return`${e}\0${t}`}function Jz(e,t,n){let r=P(e,t);if(!r)return null;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${i}\\s*\\(`);return r.match(o)?.[1]??null}function Yz(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function Xz(e){let t=ye(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let r=n[n.length-1],i=n[n.length-2];return r?.suffix==="type"&&i?.suffix==="type"}function dm(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 yR(e,t,n){return!(dm(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function Qz(e,t,n,r){let i=zc(e,t.relativePath),o=T(t.symbol);if(!o)return!1;let s=r.get(t.relativePath);if(!s)return!1;let a=[...i.get(o)??[]],c=new Set;for(;a.length>0;){let l=a.pop();if(c.has(l))continue;c.add(l);let u=s.get(l);if(!u)continue;let d=n.get(u.symbolId);if(d){for(let m of d)if(m!==t.relativePath&&!e.isIgnored(m))return!0}for(let m of i.get(l)??[])a.push(m)}return!1}function SR(e,t,n){let r=P(e,t);if(!r)return"other";let i=r.split(`
|
|
785
|
+
`),o=Math.max(0,n-2),s=Math.min(i.length-1,n+2);for(let a=o;a<=s;a++){let l=(i[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 Zz(e,t){let n=P(e,t.relativePath);if(!n)return!1;let r=T(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
|
|
786
|
+
`);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function eV(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 ec}from"path";function _o(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new _(e),a=sV(s.fileDependencyGraph(n));return gt({candidates:()=>rV(e,s,n,r),orderCandidates:Pa,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:c=>({callerFileMap:tV(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>nV(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function tV(e,t,n,r){let i=on(e,t),o=sn(i.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];r.semantic&&w("wrapper.semantic-candidates",()=>{s=n.filter(m=>mm(e,t,m,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=s.length===0?new Map:sn(i.forDefinitions(s,{semantic:!0,sourceFallback:!1})),c=a.size===0?o:rn(o,a),l=new Map(n.map(m=>[m.symbolId,m])),u=new Map;for(let m of n){let f=mm(e,t,m,c);if(f.length>1||(u.set(m.symbolId,m),f.length!==1))continue;let p=f[0],g=CR(e,m.symbolId,p);if(!g)continue;let y=xR(t,e,p,m.symbol,g);y?.isFunctionLike&&l.has(y.symbolId)&&u.set(y.symbolId,l.get(y.symbolId))}let d=[...u.values()];return d.length===0?c:rn(c,sn(i.forDefinitions(d,{semantic:!1,sourceFallback:!0})))}function nV(e,t,n,r){let i=mm(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=CR(e,n.symbolId,o);if(!s)return null;let a=xR(t,e,o,n.symbol,s);if(a&&hr(a.symbol))return null;let{fanIn:c,source:l}=iV(r.callerFileMap,r.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=cV(e,n,o,a);return{symbol:n.symbol,shortName:I(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:O(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?I(a.symbol):ri(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function rV(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(i=>!gi(e,i))}function mm(e,t,n,r){let i=ri(n.relativePath,ec(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>ri(s,ec(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return Ba(e,n,o).realConsumers}function CR(e,t,n){return e.get(`SELECT c.start_line, c.end_line
|
|
787
787
|
FROM mentions m
|
|
788
788
|
JOIN chunks c ON m.chunk_id = c.id
|
|
789
789
|
JOIN documents d ON c.document_id = d.id
|
|
790
790
|
WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
|
|
791
|
-
LIMIT 1`,t,n)}function xR(e,t,n,r,i){let o=e.definitionsForFile(n),s=
|
|
792
|
-
`),{path:r,findingCount:n.length}}function gm(e,t={}){let n=ii(e,t.path);if(!RR(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let r=JSON.parse(vR(n,"utf-8")),i=new Set((r.findings??[]).map(fm)),o=pm(e,{scope:t.scope}),s=new Set(o);return{baselinePath:n,baselineCount:i.size,current:o,newFindings:o.filter(a=>!i.has(a)),fixedFindings:[...i].filter(a=>!s.has(a))}}function IR(e,t={}){let n=ii(e,t.path);if(!RR(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let r=JSON.parse(vR(n,"utf-8")),i=new Set((r.findings??[]).map(fm).filter(a=>a.startsWith(cr))),o=xd(qr(e,{scope:t.scope})),s=new Set(o);return{baselinePath:n,baselineCount:i.size,current:o,newFindings:o.filter(a=>!i.has(a)),fixedFindings:[...i].filter(a=>!s.has(a))}}var
|
|
791
|
+
LIMIT 1`,t,n)}function xR(e,t,n,r,i){let o=e.definitionsForFile(n),s=oV(t,n,r,i.start_line,i.end_line);return Dt(o,s)}function iV(e,t,n,r){if(r?.isFunctionLike){let i=[...e.get(r.symbolId)??[]].filter(o=>o!==r.relativePath);if(i.length>0)return{fanIn:i.length,source:"function"}}return{fanIn:aV(t,n),source:"file"}}function oV(e,t,n,r,i){let o=T(n);if(!o)return r;let s=Xt(e,t).get(o);if(!s||s.length===0)return r;for(let a of s)if(a>=r&&a<=i)return a;return r}function sV(e){let t=new Map;for(let[n,r]of e){t.has(n)||t.set(n,t.get(n)??0);for(let i of r)t.set(i,(t.get(i)??0)+1)}return t}function aV(e,t){let n=e.get(t)??0;if(n>0)return n;let r=ri(t,ec(t)),i=0;for(let[o,s]of e)o!==t&&ri(o,ec(o))===r&&s>i&&(i=s);return i}function cV(e,t,n,r){return Qa(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:I(t.symbol)},{label:"caller name",value:r?.symbol?I(r.symbol):ri(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var mV=25e3,fV=2500,pV=2500;function gV(e){let t=or(e);return t.symbols>=mV||t.documents>=fV?pV:void 0}var hV=".scipquery-baseline.json";function fm(e){if(e.startsWith("similar:")){let t=e.slice(8).split("|");return t.length!==2?e:`similar:${t.map(I).sort().join("|")}`}if(e.startsWith("duplicate-bodies:")){let t=e.slice(17),n=t.indexOf(":");if(n<0)return e;let r=t.slice(0,n),i=t.slice(n+1).split("|");return i.length<2?e:`duplicate-bodies:${r}:${i.map(I).sort().join("|")}`}return e}function ii(e,t){return t&&uV(t)?t:dV(e.config.projectRoot,t??hV)}function pm(e,t={}){let{scope:n}=t,r=gV(e),i=[],o=sr(e,{scope:n,...me.dead,scanLimit:r});for(let s of o.symbols)Ee(e,s.relativePath)||de(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of uo(e,{scope:n,...me.isolated,scanLimit:r}))Ee(e,s.relativePath)||de(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of lo(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${yV(s.path)}`);for(let s of mo(e,{scope:n,...me.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of Io(e,{scope:n,...me.duplicateBodies,scanLimit:r}))i.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of yo(e,{scope:n,...me.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of _o(e,{scope:n,...me.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of ko(e,{scope:n,...me.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of To(e,{scope:n,...me.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of Eo(e,{scope:n,...me.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)s.kind!=="architecture-violation"&&i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return i.push(...xd(qr(e,{scope:n}))),[...new Set(i.map(fm))].sort()}function yV(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 bV(e,t={}){let n=pm(e,{scope:t.scope}),r=ii(e,t.path);return lV(r,JSON.stringify({version:1,findings:n},null,2)+`
|
|
792
|
+
`),{path:r,findingCount:n.length}}function gm(e,t={}){let n=ii(e,t.path);if(!RR(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let r=JSON.parse(vR(n,"utf-8")),i=new Set((r.findings??[]).map(fm)),o=pm(e,{scope:t.scope}),s=new Set(o);return{baselinePath:n,baselineCount:i.size,current:o,newFindings:o.filter(a=>!i.has(a)),fixedFindings:[...i].filter(a=>!s.has(a))}}function IR(e,t={}){let n=ii(e,t.path);if(!RR(n))throw new Error(`No baseline found at ${n}. Create one with: scip-query health --write-baseline`);let r=JSON.parse(vR(n,"utf-8")),i=new Set((r.findings??[]).map(fm).filter(a=>a.startsWith(cr))),o=xd(qr(e,{scope:t.scope})),s=new Set(o);return{baselinePath:n,baselineCount:i.size,current:o,newFindings:o.filter(a=>!i.has(a)),fixedFindings:[...i].filter(a=>!s.has(a))}}var SV=5;function ym(e,t={}){let{base:n="HEAD",minContainment:r=.7,minCallees:i=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:c}=t,l=t.semantic!==!1,u=t.diffPlan??Ln(e,{base:n}),d={available:u.note!==Co,base:n,changedFiles:u.changedFiles,helpersChecked:0,skipped:[],findings:[]};if(!d.available||u.changedFiles.length===0)return d;let m=new _(e),f=new Set(u.changedFiles),p=new Map(u.renamedFiles.map(R=>[R.to,R.from])),g=t.baseContentAt??xo(e.config.projectRoot,n,Ro(u)),y=wV(m,f,p,g);if(y.length===0)return d;let h=y.slice(0,s);y.length>s&&(d.note=`helper scoring capped at ${s} of ${y.length} new symbols`);let C=m.calleeMap(h,{semantic:l}),x=h.map(R=>({def:R,callees:Aa((C.get(R.symbolId)??[]).map(E=>E.symbol))})),S=Yr(e),b,v=()=>(b??=S.calleeIndex({minCallees:Math.min(3,i),scanLimit:c,semantic:l}),b);for(let{def:R,callees:E}of x){let D=I(R.symbol);if(E.size<i){d.skipped.push({helperShortName:D,helperFile:R.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let k=v(),L=IV(E,k);if(L===0){d.skipped.push({helperShortName:D,helperFile:R.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let ne=DV(e,R.symbolId);if(ne.length===0){d.skipped.push({helperShortName:D,helperFile:R.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let X=CV({candidateIndex:k,changed:f,helperCallees:E,helperFile:R.relativePath,helperSymbol:R.symbol,minContainment:r,minSiteCoverage:o,migratedFiles:ne});X.length!==0&&(X.sort((F,ae)=>wR(ae.migrationScope)-wR(F.migrationScope)||ae.containment-F.containment||ae.siteCoverage-F.siteCoverage||F.file.localeCompare(ae.file)),d.findings.push({helperSymbol:R.symbol,helperShortName:D,helperFile:R.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:E.size,specificHelperCalleeCount:L,migratedFiles:ne.sort(),leftovers:X.slice(0,SV)}))}return d.findings.sort((R,E)=>(E.leftovers[0]?.containment??0)-(R.leftovers[0]?.containment??0)||R.helperFile.localeCompare(E.helperFile)),d.findings=d.findings.slice(0,a),d}function CV(e){let t=[],n=xV(e.helperSymbol,e.helperFile,e.migratedFiles),r=new Set;for(let i of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(i)??[])r.add(o);for(let i of r){let o=e.candidateIndex.corpus[i];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=yC(e.helperCallees,o.callees);if(s<e.minContainment)continue;let a=[...e.helperCallees].filter(u=>o.callees.has(u)),c=o.callees.size===0?0:a.length/o.callees.size;if(c<e.minSiteCoverage||!a.some(u=>(e.candidateIndex.docFreq.get(u)??0)<=e.candidateIndex.ubiquityThreshold))continue;let l=RV(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:I(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(I).sort()})}return t}function wR(e){return e==="same-scope"?2:e==="unknown"?1:0}function xV(e,t,n){let r=new Set([...hm(t),...bm(T(e))]);for(let i of n)for(let o of hm(i))r.add(o);return r}function RV(e,t,n){let r=new Set([...hm(n),...bm(T(t))]);if(e.size===0||r.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let i=[...r].filter(o=>e.has(o)).sort();return i.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${i.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var vV=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 hm(e){return bm(e.replace(/\.[^.]+$/,""))}function bm(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!vV.has(t))}function IV(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function wV(e,t,n,r){return e.productionCallableDefinitions({files:[...t],requireFunctionLikeSymbol:!0}).filter(i=>{if(!t.has(i.relativePath))return!1;let o=n.get(i.relativePath)??i.relativePath,s=r(o);return s===null||!new RegExp(`\\b${$(i.leaf)}\\b`).test(s)})}function DV(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
|
|
793
793
|
FROM mentions m
|
|
794
794
|
JOIN chunks c ON m.chunk_id = c.id
|
|
795
795
|
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
796
796
|
WHERE m.symbol_id = ?
|
|
797
797
|
AND m.role != 1
|
|
798
|
-
${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}function Sm(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new _(e);return
|
|
799
|
-
`),{path:i}}function ER(e){let t=DR(e);if(!kV(t))return{suppressions:[],warnings:[]};let n=[],r=[];for(let i of TV(t).sort()){if(!i.endsWith(".json"))continue;let o=tc(t,i),s;try{s=JSON.parse(_V(o,"utf-8"))}catch{r.push(`${Fo}/${i}: malformed JSON \u2014 ignored`);continue}if(typeof s!="object"||s===null||Array.isArray(s)){r.push(`${Fo}/${i}: not a suppression object \u2014 ignored`);continue}let a=s;if(typeof a.reason!="string"||a.reason.trim()===""){r.push(`${Fo}/${i}: missing reason \u2014 ignored`);continue}if(!a.id&&!a.check){r.push(`${Fo}/${i}: needs an id or a check \u2014 ignored`);continue}n.push(a)}return{suppressions:n,warnings:r}}var MV=["echo","incomplete-migration","co-change-partner","twin-partner","coverage-contract","architecture","doc-reference","unused-params","new-dead","baseline"];function OV(e,t={}){let n=t.base??"HEAD",{minTogether:r=6,minConfidence:i=.6,maxEchoChecks:o=Number.POSITIVE_INFINITY,maxHelpers:s=Number.POSITIVE_INFINITY,minSimilarity:a=.8,includeBaseline:c=!1,scanLimit:l}=t,u=t.semantic!==!1,d=t.historyMode??"bounded",m=new Set(t.skip??[]),f=Fn(e,{base:n}),p=Zr(e,{base:n,plan:f}),g=p.changedFiles,y=new Set(g),h=new Set(f.changedFileLines),C=new Set([...y,...h]),x=xo(e.config.projectRoot,n,Ro(f,g)),S=mq(e.config.projectRoot,n,f,x),b={base:n,changedFiles:g,changedSymbols:p.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],attributionNotes:p.attributionNotes,rootCauseGroups:[],note:p.summary.note};if(g.length===0)return b;let v=(R,E)=>{if(m.has(R)){b.skipped.push({check:R,reason:"skipped via --skip"});return}let D=b.findings.length,k=b.skipped.length,L=b.checksRun.length;w(`diff-gate.check.${R}`,E,()=>({check:R,changedFiles:g.length,changedSymbols:p.changedSymbols.length,findingsAdded:b.findings.length-D,skippedAdded:b.skipped.length-k,checksRunAdded:b.checksRun.length-L}))};return v("echo",()=>WV(e,p.changedSymbols,y,S,o,a,l,u,b)),v("incomplete-migration",()=>JV(e,n,f,s,l,u,x,b)),v("co-change-partner",()=>YV(e,C,r,i,d,b)),v("twin-partner",()=>XV(e,p.changedSymbols,y,l,b)),v("coverage-contract",()=>QV(e,C,b)),v("architecture",()=>gq(e,b)),v("doc-reference",()=>rq(e,y,h,f.changedRanges,f.renamedFiles,b)),v("unused-params",()=>aq(e,g,b)),v("new-dead",()=>cq(e,p.changedSymbols,S,b)),c&&v("baseline",()=>pq(e,b)),HV(b,[...e.config.suppressions??[],...ER(e.config.projectRoot).suppressions]),b.rootCauseGroups=$V(b.findings),b}function jV(e){return e.checksRun.length===0&&e.note===Co}function BV(e){return e.filter(t=>!t.advisory)}function $V(e){let t=new Map;for(let n of e){let r=n.groupKey??`${n.check}:${n.id}`,i=t.get(r);i||(i={groupKey:r,check:n.check,severity:n.severity,actionTier:n.actionTier,sourceAnalyzer:n.sourceAnalyzer,rootCauseKey:n.rootCauseKey,count:0,findingIds:[],files:new Set,relatedFiles:new Set,message:n.message,remediation:n.remediation},t.set(r,i)),i.count+=1,i.findingIds.push(n.id),i.severity=LR(i.severity,n.severity),i.actionTier=NR(i.actionTier,n.actionTier),n.file&&i.files.add(n.file);for(let o of n.relatedFiles??[])i.relatedFiles.add(o)}return[...t.values()].map(n=>({...n,files:[...n.files].sort(),relatedFiles:[...n.relatedFiles].sort()})).sort((n,r)=>r.count-n.count||nc(r.severity)-nc(n.severity)||n.groupKey.localeCompare(r.groupKey))}function LR(e,t){return nc(t)>nc(e)?t:e}function nc(e){return e==="error"?2:e==="warning"?1:0}function NR(e,t){return e?t&&kR(t)>kR(e)?t:e:t}function kR(e){return e==="direct"?2:e==="signal"?1:0}function HV(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let r of e.findings){let i=t.find(o=>UV(o,r));i?e.suppressed.push({finding:r,suppression:i}):n.push(r)}e.findings=n}function UV(e,t){return!e.reason||e.reason.trim()===""||e.expiresAt&&Date.parse(e.expiresAt)<=Date.now()||e.id&&e.id!==t.id&&!t.legacySuppressionIds?.includes(e.id)||e.check&&e.check!==t.check||e.file&&e.file!==t.file?!1:!!(e.id||e.check)}function Ot(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function WV(e,t,n,r,i,o,s,a,c){c.checksRun.push("echo");for(let l of t.slice(0,i)){if(!le(l.symbol)||r(l))continue;let u=sm(e,l.symbol,{maxLoc:15,scanLimit:s}).filter(h=>!n.has(h.file)).slice(0,5).map(h=>({otherFile:h.file,otherShort:h.shortName,otherSymbol:h.symbol,similarity:1,similarityBasis:"exact-body",sharedEvidence:[`exact normalized body (${h.loc} LOC)`]}));if(u.length>0){let h=ve("echo",l.symbol,l.file),C=ve("echo",l.symbol,l.file,...u.map(S=>`${S.otherSymbol}|${S.otherFile}`).sort()),x=u[0];Ot(c,{id:h,legacySuppressionIds:C===h?void 0:[C],groupKey:h,actionTier:"direct",check:"echo",severity:"warning",evidence:"heuristic",confidence:1,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(u.map(S=>S.otherFile))].sort(),sourceAnalyzer:"duplicate-bodies",rootCauseKey:`${l.symbol}:${x.otherSymbol}`,message:TR(l,u),why:_R(l,u),remediation:FR("direct",l.shortName,x.otherShort)});continue}let d=Na(e,l.symbol,{minSimilarity:o,limit:5,scanLimit:s,semantic:a,sourceCandidateMode:"target-pruned"}),m=[];for(let h of d){let C=h.fileA===l.file?h.fileB:h.fileA,x=h.fileA===l.file?h.shortNameB:h.shortNameA,S=h.fileA===l.file?h.symbolB:h.symbolA;n.has(C)||m.push({otherFile:C,otherShort:x,otherSymbol:S,similarity:h.similarity,similarityBasis:h.similarityBasis??"callees",sharedEvidence:h.sharedCallees})}if(m.length===0)continue;let f=m[0],p=ve("echo",l.symbol,l.file,...m.map(h=>`${h.otherSymbol}|${h.otherFile}`).sort()),g=ve("echo",l.symbol,l.file),y=GV(l,m);Ot(c,{id:g,legacySuppressionIds:p===g?void 0:[p],groupKey:g,actionTier:y,check:"echo",severity:"warning",evidence:"heuristic",confidence:f.similarity,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(m.map(h=>h.otherFile))].sort(),message:TR(l,m),why:_R(l,m),remediation:FR(y,l.shortName,f.otherShort)})}t.length>i&&c.skipped.push({check:"echo",reason:`echo check capped at ${i} of ${t.length} changed symbols`})}function GV(e,t){return t.some(r=>zV(e.symbol,r))?"direct":"signal"}function zV(e,t){if(t.similarityBasis==="exact-body")return!0;if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let n=T(e),r=T(t.otherSymbol);return!n||!r?!1:n===r?!0:KV(t.sharedEvidence)?!1:VV(n,r)}function VV(e,t){let n=PR(e),r=PR(t);if(n.length===0||r.length===0)return!1;let i=new Set(r),o=n.filter(s=>i.has(s)).length;return o>=2&&o/Math.min(n.length,r.length)>=.5}function PR(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 qV=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function KV(e){return e.length>=3&&e.every(t=>qV.has(t.toLowerCase()))}function TR(e,t){let n=t[0],r=Math.round(n.similarity*100);return t.length===1?`${e.shortName} (${e.file}) is ${r}% similar to established ${n.otherShort} (${n.otherFile})`:`${e.shortName} (${e.file}) resembles ${t.length} established symbol(s); strongest is ${r}% similar to ${n.otherShort} (${n.otherFile})`}function _R(e,t){let n=[`${e.shortName} was changed in this diff.`];for(let r of t.slice(0,3))n.push(`${r.otherShort} is outside this diff and scored ${Math.round(r.similarity*100)}% similar by ${r.similarityBasis} evidence.`),n.push(`Shared evidence: ${r.sharedEvidence.slice(0,5).join(", ")||"(none listed)"}.`);return t.length>3&&n.push(`${t.length-3} additional similar match(es) grouped into this finding.`),n}function FR(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 JV(e,t,n,r,i,o,s,a){let c=ym(e,{base:t,maxHelpers:r,diffPlan:n,scanLimit:i,semantic:o,baseContentAt:s});if(!c.available){a.skipped.push({check:"incomplete-migration",reason:"no git history"});return}a.checksRun.push("incomplete-migration"),c.note&&a.skipped.push({check:"incomplete-migration",reason:c.note});for(let l of c.findings){let u=l.leftovers.map(h=>`${h.shortName} (${h.file}, ${Math.round(h.containment*100)}% helper / ${Math.round(h.siteCoverage*100)}% site, ${h.migrationScope})`).join(", "),d=l.leftovers.map(h=>`${h.shortName}: ${h.migrationScope} (${h.migrationScopeReasons[0]})`).join("; "),m=[...l.migratedFiles,...l.leftovers.map(h=>h.file)],f=l.leftovers.length===0?void 0:Math.max(...l.leftovers.map(h=>Math.min(h.containment,h.siteCoverage))),p=l.leftovers.some(h=>h.migrationScope==="possible-subtype"),g=ve("incomplete-migration",l.helperSymbol,l.helperFile,m.join("|")),y=ve("incomplete-migration",l.helperSymbol,l.helperFile);Ot(a,{id:y,legacySuppressionIds:g===y?void 0:[g],check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:f,file:l.helperFile,symbol:l.helperSymbol,relatedFiles:m,message:`new helper ${l.helperShortName} (${l.helperFile}) is wired into ${l.migratedFiles.length} file(s), but ${l.leftovers.length} similar un-migrated site(s) remain: ${u}`,why:[`${l.helperShortName} is new in this diff and already referenced by ${l.migratedFiles.join(", ")}.`,`Helper shape: ${l.helperShape}; ${l.specificHelperCalleeCount}/${l.helperCalleeCount} helper callees are specific enough to score.`,`Unchanged site(s) still contain the helper's callee pattern: ${u}.`,`Migration scope hints: ${d}.`],remediation:p?`Migrate same-scope sites to ${l.helperShortName}; review possible subtype/variant sites before applying the helper.`:`Migrate the remaining sites to ${l.helperShortName}, or confirm they are intentionally different.`})}}function YV(e,t,n,r,i,o){let s=ze(e,{historyMode:i}).directionalCoChangePairsForFiles(t,{minTogether:n,minConfidence:0,maxFilesPerCommit:20});if(!s){o.skipped.push({check:"co-change-partner",reason:"no git history"});return}o.checksRun.push("co-change-partner");let a=new Set,c;for(let l of s){let u=t.has(l.fileA),d=t.has(l.fileB);if(u===d)continue;let m=u?l.fileA:l.fileB,f=u?l.fileB:l.fileA,p=u?l.changesA:l.changesB,g=p>0?l.together/p:0;if(g<r||qd(f)||qd(m)||!rc(`${e.config.projectRoot}/${f}`))continue;let y=`${m}|${f}`;if(a.has(y))continue;a.add(y);let h=ve("co-change-partner",m,f,String(l.together)),C=ve("co-change-partner",m,f),x=Kd(m,f),S=Jd({fileA:m,fileB:f,together:l.together,confidence:g,commitScope:l.commitScope,recency:l.recency,subjectContext:l.subjectContext},x,(c??=Yd(e))(m,f)),b=[m,f].sort().join("|");o.findings.push({id:C,legacySuppressionIds:h===C?void 0:[h],check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${b}`,confidence:g,file:m,relatedFiles:[f],sourceAnalyzer:"co-change",rootCauseKey:b,partnerClass:x.partnerClass,partnerClassReasons:x.reasons,commitScope:l.commitScope,recency:l.recency,focusedTogether:l.focusedTogether,broadTogether:l.broadTogether,broadCommitRatio:l.broadCommitRatio,lastTogetherAt:l.lastTogetherAt,recentTogether:l.recentTogether,subjectContext:l.subjectContext,...S?{declaredCouplingSuggestion:S}:{},message:`${m} changed, but ${f} did not \u2014 they change together ${l.together}x (${Math.round(g*100)}% of the time)`,why:[`${m} is in this diff and ${f} is not.`,`Git history shows ${l.together} co-change(s), which is ${Math.round(g*100)}% of changes to the edited side.`,`History context: ${ZV(l)}.`,`Subject context: ${eq(l.subjectContext)}.`,...tq(l),`Partner class: ${x.partnerClass} (${x.reasons.join("; ")}).`],remediation:S?`Update ${f} alongside this change, declare the coupling "${S.name}", or confirm the coupling no longer holds.`:`Update ${f} alongside this change, or confirm the coupling no longer holds.`})}}function XV(e,t,n,r,i){i.checksRun.push("twin-partner");let o=ni(e,{scanLimit:r}).filter(c=>c.relationship==="divergent"||c.relationship==="identical");if(o.length===0)return;let s=new Map;for(let c of o)for(let l of c.members)s.set(l.symbol,c);let a=new Set;for(let c of t){if(!le(c.symbol))continue;let l=s.get(c.symbol);if(!l)continue;let u=l.members.filter(p=>p.symbol!==c.symbol&&!n.has(p.file));if(u.length===0)continue;let d=[c.symbol,...u.map(p=>p.symbol)].sort().join("|");if(a.has(d))continue;a.add(d);let m=u[0],f=ve("twin-partner",c.symbol,c.file,m.symbol);Ot(i,{id:f,groupKey:`twin-partner:${d}`,check:"twin-partner",severity:"warning",evidence:"heuristic",actionTier:"signal",advisory:!0,confidence:l.relationship==="identical"?1:Math.max(0,1-l.maxDivergence),file:c.file,symbol:c.symbol,relatedFiles:u.map(p=>p.file).sort(),sourceAnalyzer:"twin-drift",rootCauseKey:d,message:`${c.shortName} (${c.file}) changed but its same-name twin ${m.shortName} (${m.file}) did not \u2014 verify the change shouldn't apply to both, or consolidate them.`,why:[`${c.symbol} is in this diff.`,`${m.symbol} shares its (near-)name and is classified '${l.relationship}' with it, but ${m.file} is not in this diff.`,l.relationship==="divergent"?`The two bodies already diverge (~${Math.round(l.maxDivergence*100)}% token difference) \u2014 this diff may widen or narrow that drift.`:"The two bodies were byte-identical before this diff.","Advisory: twin-partner never fails the gate by itself \u2014 see the twin-partner entry in the diff-gate checks table."],remediation:`Update ${m.file} alongside this change, consolidate ${c.shortName}/${m.shortName} into one helper, or confirm the twin should diverge on purpose.`})}}function QV(e,t,n){n.checksRun.push("coverage-contract");let r=e.config.coverageContracts??[];for(let i of r){if(!cR(i,t))continue;let o=lm(e,i);if(o.status==="ok")continue;let s=ve("coverage-contract",i.name,i.file);Ot(n,{id:s,groupKey:`coverage-contract:${i.name}`,check:"coverage-contract",severity:o.status==="unavailable"?"warning":"error",evidence:"graph-fact",actionTier:"direct",file:i.file,sourceAnalyzer:"coverage-contracts",rootCauseKey:i.name,message:lR(o),why:[`Contract "${i.name}" declares that ${i.file} (${i.keys.type}) must track ${i.mustEqual.type}.`,o.status==="unavailable"?`The declared side could not be evaluated: ${o.unavailableReason}.`:`Missing: ${o.missing.join(", ")||"none"}. Extra: ${o.extra.join(", ")||"none"}.`,"Either side of this contract changed in this diff."],remediation:o.status==="unavailable"?"Investigate why the declared key set could not be parsed (see the reason above) \u2014 do not treat this as a pass.":`Update ${i.file} so its ${i.keys.type==="object-literal-keys"||i.keys.type==="string-array"?i.keys.identifier:i.keys.marker} matches ${i.mustEqual.type}, or fix the ground-truth source if the declared set is right.`})}}function ZV(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${nq(e.lastTogetherAt)}`}function eq(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",r=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(i=>`"${i}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${r}; external issue/PR labels ${e.externalIssueLabelStatus}`}function tq(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 nq(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}var Cm=3;function rq(e,t,n,r,i,o){o.checksRun.push("doc-reference");let s=sn.referenceTargets(e,t,r);if(s.size===0)return;let a=new Set(i.map(l=>l.from)),c=[];for(let l of Bx(e,s))n.has(l.doc)||Ja(e,l.doc)||c.push(iq(e,l,a));for(let l of oq(c))Ot(o,l)}function iq(e,t,n){let r=t.citedClaims.length>0?t.citedClaims:sn.citationContexts(e,t.doc,t.cited),i=sn.classifyCitation(r),o=sn.hasLineAnchoredCitation(t.citations),s=t.cited.some(d=>n.has(d)||!rc(`${e.config.projectRoot}/${d}`)),a=!(o||s),c=t.cited[0]??"",l=ve("doc-reference",t.doc,t.cited.join("|")),u=ve("doc-reference",t.doc,c);return{id:u,legacySuppressionIds:l===u?void 0:[l],check:"doc-reference",severity:"warning",evidence:"change-graph",actionTier:i.actionTier,groupKey:`doc-reference:${c}`,rootCauseKey:c,confidence:1,file:t.doc,relatedFiles:t.cited,citationKind:i.citationKind,citationKindReasons:i.reasons,citedClaims:r,...a?{advisory:!0}:{},message:`${t.doc} cites ${t.cited.join(", ")} as ${sn.citationKindLabel(i.citationKind)} \u2014 changed in this diff, doc untouched`,why:[`${t.cited.join(", ")} changed in this diff.`,`${t.doc} cites the changed file(s) but was not updated in the same diff.`,...i.reasons.map(d=>`Citation kind evidence: ${d}`),a?"Advisory: bare file-mention citation (no line anchor, cited file still present under the same path) \u2014 21.2 calibration found this citation shape low-precision; verify at your leisure.":o?"Blocking: citation includes a line anchor that may now point at the wrong lines.":"Blocking: the cited file was deleted or renamed in this diff \u2014 the citation almost certainly needs an update."],remediation:sn.citationRemediation(i.citationKind,t.doc)}}function oq(e){let t=new Map;for(let r of e){let i=r.rootCauseKey??"",o=t.get(i);o?o.push(r):t.set(i,[r])}let n=[];for(let[r,i]of t)i.length<=Cm?n.push(...i):n.push(sq(r,i));return n}function sq(e,t){let n=[...t].sort((u,d)=>(u.file??"").localeCompare(d.file??"")),r=n.slice(0,Cm).map(u=>({doc:u.file??"",citedClaims:u.citedClaims??[]})),i=n.length-r.length,o=n.every(u=>u.advisory===!0),s=n.reduce((u,d)=>LR(u,d.severity),"info"),a=n.reduce((u,d)=>NR(u,d.actionTier),void 0),c=n.map(u=>u.file??"").filter(u=>u.length>0),l=[...new Set(n.flatMap(u=>[u.id,...u.legacySuppressionIds??[]]))];return{id:ve("doc-reference","hub-cluster",e),memberFindingIds:l,check:"doc-reference",severity:s,evidence:"change-graph",actionTier:a,groupKey:`doc-reference:${e}`,rootCauseKey:e,confidence:1,file:r[0]?.doc,relatedFiles:[e],citationCount:n.length,citationExemplars:r,suppressedCount:i,...o?{advisory:!0}:{},message:`${e} is cited by ${n.length} doc(s) changed in this diff, doc(s) untouched \u2014 showing ${r.length} example(s), ${i} more damped`,why:[`${e} changed in this diff.`,`${n.length} doc(s) cite it but were not updated in the same diff: ${c.join(", ")}.`,...r.map(u=>`Example \u2014 ${u.doc}: ${u.citedClaims[0]??"(no captured citation text)"}`),`${i} additional doc(s) also cite this file, past the per-hub-file cascade cap (${Cm}) \u2014 not silently dropped: counted in citationCount/suppressedCount and individually addressable via memberFindingIds.`,o?"Advisory: every citation in this cluster is a bare file-mention (no line anchor, cited file still present).":"Blocking: at least one citation in this cluster is line-anchored or cites a deleted/renamed file."],remediation:`Review the ${r.length} example doc(s) above; ${n.length} total doc(s) cite ${e} the same way \u2014 see citationExemplars and memberFindingIds in --json for the complete list.`}}function aq(e,t,n){n.checksRun.push("unused-params");for(let r of Sm(e,{files:t,limit:50})){let i=ve("unused-params",r.symbol,r.file,r.unusedTrailing.join("|")),o=ve("unused-params",r.symbol,r.file);Ot(n,{id:o,legacySuppressionIds:i===o?void 0:[i],check:"unused-params",severity:"warning",evidence:"heuristic",confidence:.85,file:r.file,startLine:r.startLine,endLine:r.endLine,symbol:r.symbol,message:`${r.shortName} (${r.file}) has trailing unused parameter(s): ${r.unusedTrailing.join(", ")}`,why:[`${r.shortName} is in a changed file.`,`The trailing parameter(s) ${r.unusedTrailing.join(", ")} are not referenced in the function body.`],remediation:"Drop the unused trailing parameters and their call-site arguments."})}}function cq(e,t,n,r){r.checksRun.push("new-dead");let i=new _(e),o=Rr(e.config.projectRoot),s=o.length>1;for(let a of t){if(n(a)||a.fanIn>0||i.fileKind(a.file)==="test"||Ee(e,a.file)||de(e,a.symbol,a.file)||dq(a.symbol))continue;let c=ve("new-dead",a.symbol,a.file),l=s&&lq(o,a.file)&&uq(e,a.symbol);Ot(r,{id:c,check:"new-dead",severity:"warning",evidence:l?"heuristic":"graph-fact",confidence:l?.4:.9,file:a.file,symbol:a.symbol,message:l?`${a.shortName} (${a.file}) unconfirmed (cross-package ambiguous-name resolution gap): zero indexed consumers found, but this name is ambiguous project-wide and lives in a workspace package \u2014 verify manually before treating as dead`:`${a.shortName} (${a.file}) was changed but has zero indexed consumers`,why:l?[`${a.shortName} is a changed production symbol in a workspace package.`,"The index, semantic, and source-fallback layers all report zero consumers for this symbol.","Its leaf name is ambiguous project-wide (a same-named definition exists elsewhere), and cross-package consumers reached only through a re-exporting barrel are a known unresolvable shape for this tool \u2014 see docs/plans/2026-07-02-followups.md item 2."]:[`${a.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:l?"Verify with a direct code search before deleting; this tool cannot confidently resolve this symbol.":"Wire it up, or remove it before it becomes permanent dead code."})}}function lq(e,t){return e.some(n=>t===n.relativeDir||t.startsWith(`${n.relativeDir}/`))}function uq(e,t){let n=T(t);return n?(Xt(e).get(n)?.length??0)>1:!1}function dq(e){if(ue(e)!=="type")return!1;let t=T(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function mq(e,t,n,r){let i=new Map(n.renamedFiles.map(s=>[s.to,s.from])),o=r??xo(e,t,Ro(n));return s=>{let a=i.get(s.file)??s.file,c=T(s.symbol);if(!c)return!1;let l=o(a);return l!==null&&fq(l,c)}}function fq(e,t){return new RegExp(`\\b${$(t)}\\b`).test(e)}function pq(e,t){if(!rc(ii(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=gm(e);for(let r of n.newFindings.filter(i=>!i.startsWith(cr))){let i=tm(r),o=ve("baseline",r);Ot(t,{id:o,groupKey:`baseline:${i.sourceAnalyzer}:${i.rootCauseKey}`,check:"baseline",severity:"error",evidence:"baseline",actionTier:i.actionTier,confidence:1,file:i.file,relatedFiles:i.relatedFiles.length>0?i.relatedFiles:void 0,sourceAnalyzer:i.sourceAnalyzer,rootCauseKey:i.rootCauseKey,message:`new ${i.label} vs committed baseline: ${r}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline.",`Underlying analyzer: ${i.sourceAnalyzer}.`,`Inherited action tier: ${i.actionTier}.`,`Root cause key: ${i.rootCauseKey}.`,...i.why],remediation:i.remediation})}}function gq(e,t){if(!fC(e.config.architecture)){t.skipped.push({check:"architecture",reason:"no closed architecture dependency rows, requireCompletePolicy rule, or requireAcyclic rule configured"});return}if(!rc(ii(e))){t.skipped.push({check:"architecture",reason:"no .scipquery-baseline.json \u2014 run health --write-baseline to enable"});return}t.checksRun.push("architecture");let n=IR(e);for(let r of n.newFindings){let i=tm(r),o=ve("architecture",r);Ot(t,{id:o,groupKey:`architecture:${i.rootCauseKey}`,check:"architecture",severity:"error",evidence:"baseline",actionTier:"direct",confidence:1,sourceAnalyzer:"architecture",rootCauseKey:i.rootCauseKey,message:`new ${i.label} vs committed baseline: ${r}`,why:["The project declares an enforceable architecture rule.","The current boundary graph contains a violation not present in the committed baseline.",...i.why],remediation:i.remediation})}}function ve(e,...t){return`SQ${AV("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}import{dirname as hq,relative as yq,resolve as bq}from"path";var Sq=new Set(Ft());function Cq(e,t){return`tests/generated/twin-ab/${AR(e)}-vs-${AR(t)}.test.ts`}function AR(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function xq(e,t,n,r){let i=MR(e,t);if(!i.ok)return i;let o=MR(e,n);if(!o.ok)return o;let s=i.symbol.paramCount===null||o.symbol.paramCount===null?null:i.symbol.paramCount===o.symbol.paramCount,a=vq(i.symbol,o.symbol,e.config.projectRoot,r,s);return{ok:!0,a:i.symbol,b:o.symbol,signatureCompatible:s,testSource:a}}function MR(e,t){let r=Ii(e,t).match;if(!r)return{ok:!1,reason:`${t} does not resolve to an indexed symbol.`};let o=e.get("SELECT kind FROM global_symbols WHERE id = ?",r.symbolId)?.kind??null;if(!(o!==null?Sq.has(o):ee(r.symbol)))return{ok:!1,reason:`${t} resolves to ${I(r.symbol)}${o!==null?` with SCIP kind ${so(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!Po(e,r))return{ok:!1,reason:`${t} (${I(r.symbol)} at ${r.relativePath}:${r.startLine+1}) is not exported \u2014 twin-ab needs an importable named binding for both twins.`};let a=e.get("SELECT documentation FROM global_symbols WHERE id = ?",r.symbolId),c=Kt(Jt(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:r.symbol,shortName:T(r.symbol)||I(r.symbol),file:r.relativePath,startLine:r.startLine,signature:c,paramCount:c?Rq(c):null}}}function Rq(e){let t=e.indexOf("(");if(t===-1)return null;let n=0,r=-1;for(let a=t;a<e.length;a+=1){let c=e[a];if(c==="(")n+=1;else if(c===")"&&(n-=1,n===0)){r=a;break}}if(r===-1)return null;let i=e.slice(t+1,r).trim();if(!i)return 0;let o=1,s=0;for(let a of i)a==="("||a==="["||a==="{"?s+=1:a===")"||a==="]"||a==="}"?s=Math.max(0,s-1):a===","&&s===0&&(o+=1);return o}function OR(e,t,n){let r=hq(t),i=bq(e,n),s=yq(r,i).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function vq(e,t,n,r,i){let o=OR(n,r,e.file),s=OR(n,r,t.file),a=i===null?"Signature comparison: unknown (one or both signatures unavailable in the index) \u2014 check by hand.":i?"Signature comparison: param counts match.":"Signature comparison: param counts DIFFER \u2014 twins may not be directly comparable; check by hand.";return`/**
|
|
798
|
+
${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}function Sm(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new _(e);return gt({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>EV(s.relativePath),scanLimit:i,profile:{name:"unused-params"},evaluate:s=>{let a=G(e,s.relativePath)?.callables.find(u=>u.startLine===s.startLine&&u.endLine===s.endLine);if(!a||a.params.length===0||a.params.some(u=>!u.simple)||a.paramsEndLine>=a.endLine)return null;let c=Xt(e,s.relativePath),l=[];for(let u=a.params.length-1;u>=0;u--){let d=a.params[u];if(d.name===""||d.name.startsWith("_")||kV(c.get(d.name),a.paramsEndLine,a.endLine))break;l.unshift(d.name)}return l.length===0?null:{symbol:s.symbol,shortName:I(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:l}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:r})}function EV(e){let t=M(e);return t==="typescript"||t==="tsx"||t==="javascript"}function kV(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}import{existsSync as PV,mkdirSync as TV,readdirSync as _V,readFileSync as FV,writeFileSync as LV}from"fs";import{createHash as NV}from"crypto";import{join as tc}from"path";var Fo=tc(".scipquery","suppressions");function DR(e){return tc(e,Fo)}function AV(e){if(e.id&&e.id.trim()!=="")return`${e.id.trim()}.json`;let t=`${e.check??""}\0${e.file??""}`;return`CHECK-${NV("sha256").update(t).digest("hex").slice(0,12).toUpperCase()}.json`}function ede(e,t,n=new Date){if(!t.reason||t.reason.trim()==="")throw new Error("suppression requires a non-empty reason");if(!t.id&&!t.check)throw new Error("suppression requires an id or a check");let r=DR(e);TV(r,{recursive:!0});let i=tc(r,AV(t)),o={...t,createdAt:t.createdAt??n.toISOString()};return LV(i,JSON.stringify(o,null,2)+`
|
|
799
|
+
`),{path:i}}function ER(e){let t=DR(e);if(!PV(t))return{suppressions:[],warnings:[]};let n=[],r=[];for(let i of _V(t).sort()){if(!i.endsWith(".json"))continue;let o=tc(t,i),s;try{s=JSON.parse(FV(o,"utf-8"))}catch{r.push(`${Fo}/${i}: malformed JSON \u2014 ignored`);continue}if(typeof s!="object"||s===null||Array.isArray(s)){r.push(`${Fo}/${i}: not a suppression object \u2014 ignored`);continue}let a=s;if(typeof a.reason!="string"||a.reason.trim()===""){r.push(`${Fo}/${i}: missing reason \u2014 ignored`);continue}if(!a.id&&!a.check){r.push(`${Fo}/${i}: needs an id or a check \u2014 ignored`);continue}n.push(a)}return{suppressions:n,warnings:r}}var OV=["echo","incomplete-migration","co-change-partner","twin-partner","coverage-contract","architecture","doc-reference","unused-params","new-dead","baseline"];function jV(e,t={}){let n=t.base??"HEAD",{minTogether:r=6,minConfidence:i=.6,maxEchoChecks:o=Number.POSITIVE_INFINITY,maxHelpers:s=Number.POSITIVE_INFINITY,minSimilarity:a=.8,includeBaseline:c=!1,scanLimit:l}=t,u=t.semantic!==!1,d=t.historyMode??"bounded",m=new Set(t.skip??[]),f=Ln(e,{base:n}),p=Zr(e,{base:n,plan:f}),g=p.changedFiles,y=new Set(g),h=new Set(f.changedFileLines),C=new Set([...y,...h]),x=xo(e.config.projectRoot,n,Ro(f,g)),S=fq(e.config.projectRoot,n,f,x),b={base:n,changedFiles:g,changedSymbols:p.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],attributionNotes:p.attributionNotes,rootCauseGroups:[],note:p.summary.note};if(g.length===0)return b;let v=(R,E)=>{if(m.has(R)){b.skipped.push({check:R,reason:"skipped via --skip"});return}let D=b.findings.length,k=b.skipped.length,L=b.checksRun.length;w(`diff-gate.check.${R}`,E,()=>({check:R,changedFiles:g.length,changedSymbols:p.changedSymbols.length,findingsAdded:b.findings.length-D,skippedAdded:b.skipped.length-k,checksRunAdded:b.checksRun.length-L}))};return v("echo",()=>GV(e,p.changedSymbols,y,S,o,a,l,u,b)),v("incomplete-migration",()=>YV(e,n,f,s,l,u,x,b)),v("co-change-partner",()=>XV(e,C,r,i,d,b)),v("twin-partner",()=>QV(e,p.changedSymbols,y,l,b)),v("coverage-contract",()=>ZV(e,C,b)),v("architecture",()=>hq(e,b)),v("doc-reference",()=>iq(e,y,h,f.changedRanges,f.renamedFiles,b)),v("unused-params",()=>cq(e,g,b)),v("new-dead",()=>lq(e,p.changedSymbols,S,b)),c&&v("baseline",()=>gq(e,b)),UV(b,[...e.config.suppressions??[],...ER(e.config.projectRoot).suppressions]),b.rootCauseGroups=HV(b.findings),b}function BV(e){return e.checksRun.length===0&&e.note===Co}function $V(e){return e.filter(t=>!t.advisory)}function HV(e){let t=new Map;for(let n of e){let r=n.groupKey??`${n.check}:${n.id}`,i=t.get(r);i||(i={groupKey:r,check:n.check,severity:n.severity,actionTier:n.actionTier,sourceAnalyzer:n.sourceAnalyzer,rootCauseKey:n.rootCauseKey,count:0,findingIds:[],files:new Set,relatedFiles:new Set,message:n.message,remediation:n.remediation},t.set(r,i)),i.count+=1,i.findingIds.push(n.id),i.severity=LR(i.severity,n.severity),i.actionTier=NR(i.actionTier,n.actionTier),n.file&&i.files.add(n.file);for(let o of n.relatedFiles??[])i.relatedFiles.add(o)}return[...t.values()].map(n=>({...n,files:[...n.files].sort(),relatedFiles:[...n.relatedFiles].sort()})).sort((n,r)=>r.count-n.count||nc(r.severity)-nc(n.severity)||n.groupKey.localeCompare(r.groupKey))}function LR(e,t){return nc(t)>nc(e)?t:e}function nc(e){return e==="error"?2:e==="warning"?1:0}function NR(e,t){return e?t&&kR(t)>kR(e)?t:e:t}function kR(e){return e==="direct"?2:e==="signal"?1:0}function UV(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let r of e.findings){let i=t.find(o=>WV(o,r));i?e.suppressed.push({finding:r,suppression:i}):n.push(r)}e.findings=n}function WV(e,t){return!e.reason||e.reason.trim()===""||e.expiresAt&&Date.parse(e.expiresAt)<=Date.now()||e.id&&e.id!==t.id&&!t.legacySuppressionIds?.includes(e.id)||e.check&&e.check!==t.check||e.file&&e.file!==t.file?!1:!!(e.id||e.check)}function jt(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function GV(e,t,n,r,i,o,s,a,c){c.checksRun.push("echo");for(let l of t.slice(0,i)){if(!le(l.symbol)||r(l))continue;let u=sm(e,l.symbol,{maxLoc:15,scanLimit:s}).filter(h=>!n.has(h.file)).slice(0,5).map(h=>({otherFile:h.file,otherShort:h.shortName,otherSymbol:h.symbol,similarity:1,similarityBasis:"exact-body",sharedEvidence:[`exact normalized body (${h.loc} LOC)`]}));if(u.length>0){let h=ve("echo",l.symbol,l.file),C=ve("echo",l.symbol,l.file,...u.map(S=>`${S.otherSymbol}|${S.otherFile}`).sort()),x=u[0];jt(c,{id:h,legacySuppressionIds:C===h?void 0:[C],groupKey:h,actionTier:"direct",check:"echo",severity:"warning",evidence:"heuristic",confidence:1,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(u.map(S=>S.otherFile))].sort(),sourceAnalyzer:"duplicate-bodies",rootCauseKey:`${l.symbol}:${x.otherSymbol}`,message:TR(l,u),why:_R(l,u),remediation:FR("direct",l.shortName,x.otherShort)});continue}let d=Na(e,l.symbol,{minSimilarity:o,limit:5,scanLimit:s,semantic:a,sourceCandidateMode:"target-pruned"}),m=[];for(let h of d){let C=h.fileA===l.file?h.fileB:h.fileA,x=h.fileA===l.file?h.shortNameB:h.shortNameA,S=h.fileA===l.file?h.symbolB:h.symbolA;n.has(C)||m.push({otherFile:C,otherShort:x,otherSymbol:S,similarity:h.similarity,similarityBasis:h.similarityBasis??"callees",sharedEvidence:h.sharedCallees})}if(m.length===0)continue;let f=m[0],p=ve("echo",l.symbol,l.file,...m.map(h=>`${h.otherSymbol}|${h.otherFile}`).sort()),g=ve("echo",l.symbol,l.file),y=zV(l,m);jt(c,{id:g,legacySuppressionIds:p===g?void 0:[p],groupKey:g,actionTier:y,check:"echo",severity:"warning",evidence:"heuristic",confidence:f.similarity,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(m.map(h=>h.otherFile))].sort(),message:TR(l,m),why:_R(l,m),remediation:FR(y,l.shortName,f.otherShort)})}t.length>i&&c.skipped.push({check:"echo",reason:`echo check capped at ${i} of ${t.length} changed symbols`})}function zV(e,t){return t.some(r=>VV(e.symbol,r))?"direct":"signal"}function VV(e,t){if(t.similarityBasis==="exact-body")return!0;if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let n=T(e),r=T(t.otherSymbol);return!n||!r?!1:n===r?!0:JV(t.sharedEvidence)?!1:qV(n,r)}function qV(e,t){let n=PR(e),r=PR(t);if(n.length===0||r.length===0)return!1;let i=new Set(r),o=n.filter(s=>i.has(s)).length;return o>=2&&o/Math.min(n.length,r.length)>=.5}function PR(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 KV=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function JV(e){return e.length>=3&&e.every(t=>KV.has(t.toLowerCase()))}function TR(e,t){let n=t[0],r=Math.round(n.similarity*100);return t.length===1?`${e.shortName} (${e.file}) is ${r}% similar to established ${n.otherShort} (${n.otherFile})`:`${e.shortName} (${e.file}) resembles ${t.length} established symbol(s); strongest is ${r}% similar to ${n.otherShort} (${n.otherFile})`}function _R(e,t){let n=[`${e.shortName} was changed in this diff.`];for(let r of t.slice(0,3))n.push(`${r.otherShort} is outside this diff and scored ${Math.round(r.similarity*100)}% similar by ${r.similarityBasis} evidence.`),n.push(`Shared evidence: ${r.sharedEvidence.slice(0,5).join(", ")||"(none listed)"}.`);return t.length>3&&n.push(`${t.length-3} additional similar match(es) grouped into this finding.`),n}function FR(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 YV(e,t,n,r,i,o,s,a){let c=ym(e,{base:t,maxHelpers:r,diffPlan:n,scanLimit:i,semantic:o,baseContentAt:s});if(!c.available){a.skipped.push({check:"incomplete-migration",reason:"no git history"});return}a.checksRun.push("incomplete-migration"),c.note&&a.skipped.push({check:"incomplete-migration",reason:c.note});for(let l of c.findings){let u=l.leftovers.map(h=>`${h.shortName} (${h.file}, ${Math.round(h.containment*100)}% helper / ${Math.round(h.siteCoverage*100)}% site, ${h.migrationScope})`).join(", "),d=l.leftovers.map(h=>`${h.shortName}: ${h.migrationScope} (${h.migrationScopeReasons[0]})`).join("; "),m=[...l.migratedFiles,...l.leftovers.map(h=>h.file)],f=l.leftovers.length===0?void 0:Math.max(...l.leftovers.map(h=>Math.min(h.containment,h.siteCoverage))),p=l.leftovers.some(h=>h.migrationScope==="possible-subtype"),g=ve("incomplete-migration",l.helperSymbol,l.helperFile,m.join("|")),y=ve("incomplete-migration",l.helperSymbol,l.helperFile);jt(a,{id:y,legacySuppressionIds:g===y?void 0:[g],check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:f,file:l.helperFile,symbol:l.helperSymbol,relatedFiles:m,message:`new helper ${l.helperShortName} (${l.helperFile}) is wired into ${l.migratedFiles.length} file(s), but ${l.leftovers.length} similar un-migrated site(s) remain: ${u}`,why:[`${l.helperShortName} is new in this diff and already referenced by ${l.migratedFiles.join(", ")}.`,`Helper shape: ${l.helperShape}; ${l.specificHelperCalleeCount}/${l.helperCalleeCount} helper callees are specific enough to score.`,`Unchanged site(s) still contain the helper's callee pattern: ${u}.`,`Migration scope hints: ${d}.`],remediation:p?`Migrate same-scope sites to ${l.helperShortName}; review possible subtype/variant sites before applying the helper.`:`Migrate the remaining sites to ${l.helperShortName}, or confirm they are intentionally different.`})}}function XV(e,t,n,r,i,o){let s=ze(e,{historyMode:i}).directionalCoChangePairsForFiles(t,{minTogether:n,minConfidence:0,maxFilesPerCommit:20});if(!s){o.skipped.push({check:"co-change-partner",reason:"no git history"});return}o.checksRun.push("co-change-partner");let a=new Set,c;for(let l of s){let u=t.has(l.fileA),d=t.has(l.fileB);if(u===d)continue;let m=u?l.fileA:l.fileB,f=u?l.fileB:l.fileA,p=u?l.changesA:l.changesB,g=p>0?l.together/p:0;if(g<r||qd(f)||qd(m)||!rc(`${e.config.projectRoot}/${f}`))continue;let y=`${m}|${f}`;if(a.has(y))continue;a.add(y);let h=ve("co-change-partner",m,f,String(l.together)),C=ve("co-change-partner",m,f),x=Kd(m,f),S=Jd({fileA:m,fileB:f,together:l.together,confidence:g,commitScope:l.commitScope,recency:l.recency,subjectContext:l.subjectContext},x,(c??=Yd(e))(m,f)),b=[m,f].sort().join("|");o.findings.push({id:C,legacySuppressionIds:h===C?void 0:[h],check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${b}`,confidence:g,file:m,relatedFiles:[f],sourceAnalyzer:"co-change",rootCauseKey:b,partnerClass:x.partnerClass,partnerClassReasons:x.reasons,commitScope:l.commitScope,recency:l.recency,focusedTogether:l.focusedTogether,broadTogether:l.broadTogether,broadCommitRatio:l.broadCommitRatio,lastTogetherAt:l.lastTogetherAt,recentTogether:l.recentTogether,subjectContext:l.subjectContext,...S?{declaredCouplingSuggestion:S}:{},message:`${m} changed, but ${f} did not \u2014 they change together ${l.together}x (${Math.round(g*100)}% of the time)`,why:[`${m} is in this diff and ${f} is not.`,`Git history shows ${l.together} co-change(s), which is ${Math.round(g*100)}% of changes to the edited side.`,`History context: ${eq(l)}.`,`Subject context: ${tq(l.subjectContext)}.`,...nq(l),`Partner class: ${x.partnerClass} (${x.reasons.join("; ")}).`],remediation:S?`Update ${f} alongside this change, declare the coupling "${S.name}", or confirm the coupling no longer holds.`:`Update ${f} alongside this change, or confirm the coupling no longer holds.`})}}function QV(e,t,n,r,i){i.checksRun.push("twin-partner");let o=ni(e,{scanLimit:r}).filter(c=>c.relationship==="divergent"||c.relationship==="identical");if(o.length===0)return;let s=new Map;for(let c of o)for(let l of c.members)s.set(l.symbol,c);let a=new Set;for(let c of t){if(!le(c.symbol))continue;let l=s.get(c.symbol);if(!l)continue;let u=l.members.filter(p=>p.symbol!==c.symbol&&!n.has(p.file));if(u.length===0)continue;let d=[c.symbol,...u.map(p=>p.symbol)].sort().join("|");if(a.has(d))continue;a.add(d);let m=u[0],f=ve("twin-partner",c.symbol,c.file,m.symbol);jt(i,{id:f,groupKey:`twin-partner:${d}`,check:"twin-partner",severity:"warning",evidence:"heuristic",actionTier:"signal",advisory:!0,confidence:l.relationship==="identical"?1:Math.max(0,1-l.maxDivergence),file:c.file,symbol:c.symbol,relatedFiles:u.map(p=>p.file).sort(),sourceAnalyzer:"twin-drift",rootCauseKey:d,message:`${c.shortName} (${c.file}) changed but its same-name twin ${m.shortName} (${m.file}) did not \u2014 verify the change shouldn't apply to both, or consolidate them.`,why:[`${c.symbol} is in this diff.`,`${m.symbol} shares its (near-)name and is classified '${l.relationship}' with it, but ${m.file} is not in this diff.`,l.relationship==="divergent"?`The two bodies already diverge (~${Math.round(l.maxDivergence*100)}% token difference) \u2014 this diff may widen or narrow that drift.`:"The two bodies were byte-identical before this diff.","Advisory: twin-partner never fails the gate by itself \u2014 see the twin-partner entry in the diff-gate checks table."],remediation:`Update ${m.file} alongside this change, consolidate ${c.shortName}/${m.shortName} into one helper, or confirm the twin should diverge on purpose.`})}}function ZV(e,t,n){n.checksRun.push("coverage-contract");let r=e.config.coverageContracts??[];for(let i of r){if(!cR(i,t))continue;let o=lm(e,i);if(o.status==="ok")continue;let s=ve("coverage-contract",i.name,i.file);jt(n,{id:s,groupKey:`coverage-contract:${i.name}`,check:"coverage-contract",severity:o.status==="unavailable"?"warning":"error",evidence:"graph-fact",actionTier:"direct",file:i.file,sourceAnalyzer:"coverage-contracts",rootCauseKey:i.name,message:lR(o),why:[`Contract "${i.name}" declares that ${i.file} (${i.keys.type}) must track ${i.mustEqual.type}.`,o.status==="unavailable"?`The declared side could not be evaluated: ${o.unavailableReason}.`:`Missing: ${o.missing.join(", ")||"none"}. Extra: ${o.extra.join(", ")||"none"}.`,"Either side of this contract changed in this diff."],remediation:o.status==="unavailable"?"Investigate why the declared key set could not be parsed (see the reason above) \u2014 do not treat this as a pass.":`Update ${i.file} so its ${i.keys.type==="object-literal-keys"||i.keys.type==="string-array"?i.keys.identifier:i.keys.marker} matches ${i.mustEqual.type}, or fix the ground-truth source if the declared set is right.`})}}function eq(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${rq(e.lastTogetherAt)}`}function tq(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",r=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(i=>`"${i}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${r}; external issue/PR labels ${e.externalIssueLabelStatus}`}function nq(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 rq(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}var Cm=3;function iq(e,t,n,r,i,o){o.checksRun.push("doc-reference");let s=an.referenceTargets(e,t,r);if(s.size===0)return;let a=new Set(i.map(l=>l.from)),c=[];for(let l of Bx(e,s))n.has(l.doc)||Ja(e,l.doc)||c.push(oq(e,l,a));for(let l of sq(c))jt(o,l)}function oq(e,t,n){let r=t.citedClaims.length>0?t.citedClaims:an.citationContexts(e,t.doc,t.cited),i=an.classifyCitation(r),o=an.hasLineAnchoredCitation(t.citations),s=t.cited.some(d=>n.has(d)||!rc(`${e.config.projectRoot}/${d}`)),a=!(o||s),c=t.cited[0]??"",l=ve("doc-reference",t.doc,t.cited.join("|")),u=ve("doc-reference",t.doc,c);return{id:u,legacySuppressionIds:l===u?void 0:[l],check:"doc-reference",severity:"warning",evidence:"change-graph",actionTier:i.actionTier,groupKey:`doc-reference:${c}`,rootCauseKey:c,confidence:1,file:t.doc,relatedFiles:t.cited,citationKind:i.citationKind,citationKindReasons:i.reasons,citedClaims:r,...a?{advisory:!0}:{},message:`${t.doc} cites ${t.cited.join(", ")} as ${an.citationKindLabel(i.citationKind)} \u2014 changed in this diff, doc untouched`,why:[`${t.cited.join(", ")} changed in this diff.`,`${t.doc} cites the changed file(s) but was not updated in the same diff.`,...i.reasons.map(d=>`Citation kind evidence: ${d}`),a?"Advisory: bare file-mention citation (no line anchor, cited file still present under the same path) \u2014 21.2 calibration found this citation shape low-precision; verify at your leisure.":o?"Blocking: citation includes a line anchor that may now point at the wrong lines.":"Blocking: the cited file was deleted or renamed in this diff \u2014 the citation almost certainly needs an update."],remediation:an.citationRemediation(i.citationKind,t.doc)}}function sq(e){let t=new Map;for(let r of e){let i=r.rootCauseKey??"",o=t.get(i);o?o.push(r):t.set(i,[r])}let n=[];for(let[r,i]of t)i.length<=Cm?n.push(...i):n.push(aq(r,i));return n}function aq(e,t){let n=[...t].sort((u,d)=>(u.file??"").localeCompare(d.file??"")),r=n.slice(0,Cm).map(u=>({doc:u.file??"",citedClaims:u.citedClaims??[]})),i=n.length-r.length,o=n.every(u=>u.advisory===!0),s=n.reduce((u,d)=>LR(u,d.severity),"info"),a=n.reduce((u,d)=>NR(u,d.actionTier),void 0),c=n.map(u=>u.file??"").filter(u=>u.length>0),l=[...new Set(n.flatMap(u=>[u.id,...u.legacySuppressionIds??[]]))];return{id:ve("doc-reference","hub-cluster",e),memberFindingIds:l,check:"doc-reference",severity:s,evidence:"change-graph",actionTier:a,groupKey:`doc-reference:${e}`,rootCauseKey:e,confidence:1,file:r[0]?.doc,relatedFiles:[e],citationCount:n.length,citationExemplars:r,suppressedCount:i,...o?{advisory:!0}:{},message:`${e} is cited by ${n.length} doc(s) changed in this diff, doc(s) untouched \u2014 showing ${r.length} example(s), ${i} more damped`,why:[`${e} changed in this diff.`,`${n.length} doc(s) cite it but were not updated in the same diff: ${c.join(", ")}.`,...r.map(u=>`Example \u2014 ${u.doc}: ${u.citedClaims[0]??"(no captured citation text)"}`),`${i} additional doc(s) also cite this file, past the per-hub-file cascade cap (${Cm}) \u2014 not silently dropped: counted in citationCount/suppressedCount and individually addressable via memberFindingIds.`,o?"Advisory: every citation in this cluster is a bare file-mention (no line anchor, cited file still present).":"Blocking: at least one citation in this cluster is line-anchored or cites a deleted/renamed file."],remediation:`Review the ${r.length} example doc(s) above; ${n.length} total doc(s) cite ${e} the same way \u2014 see citationExemplars and memberFindingIds in --json for the complete list.`}}function cq(e,t,n){n.checksRun.push("unused-params");for(let r of Sm(e,{files:t,limit:50})){let i=ve("unused-params",r.symbol,r.file,r.unusedTrailing.join("|")),o=ve("unused-params",r.symbol,r.file);jt(n,{id:o,legacySuppressionIds:i===o?void 0:[i],check:"unused-params",severity:"warning",evidence:"heuristic",confidence:.85,file:r.file,startLine:r.startLine,endLine:r.endLine,symbol:r.symbol,message:`${r.shortName} (${r.file}) has trailing unused parameter(s): ${r.unusedTrailing.join(", ")}`,why:[`${r.shortName} is in a changed file.`,`The trailing parameter(s) ${r.unusedTrailing.join(", ")} are not referenced in the function body.`],remediation:"Drop the unused trailing parameters and their call-site arguments."})}}function lq(e,t,n,r){r.checksRun.push("new-dead");let i=new _(e),o=Rr(e.config.projectRoot),s=o.length>1;for(let a of t){if(n(a)||a.fanIn>0||i.fileKind(a.file)==="test"||Ee(e,a.file)||de(e,a.symbol,a.file)||mq(a.symbol))continue;let c=ve("new-dead",a.symbol,a.file),l=s&&uq(o,a.file)&&dq(e,a.symbol);jt(r,{id:c,check:"new-dead",severity:"warning",evidence:l?"heuristic":"graph-fact",confidence:l?.4:.9,file:a.file,symbol:a.symbol,message:l?`${a.shortName} (${a.file}) unconfirmed (cross-package ambiguous-name resolution gap): zero indexed consumers found, but this name is ambiguous project-wide and lives in a workspace package \u2014 verify manually before treating as dead`:`${a.shortName} (${a.file}) was changed but has zero indexed consumers`,why:l?[`${a.shortName} is a changed production symbol in a workspace package.`,"The index, semantic, and source-fallback layers all report zero consumers for this symbol.","Its leaf name is ambiguous project-wide (a same-named definition exists elsewhere), and cross-package consumers reached only through a re-exporting barrel are a known unresolvable shape for this tool \u2014 see docs/plans/2026-07-02-followups.md item 2."]:[`${a.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:l?"Verify with a direct code search before deleting; this tool cannot confidently resolve this symbol.":"Wire it up, or remove it before it becomes permanent dead code."})}}function uq(e,t){return e.some(n=>t===n.relativeDir||t.startsWith(`${n.relativeDir}/`))}function dq(e,t){let n=T(t);return n?(Qt(e).get(n)?.length??0)>1:!1}function mq(e){if(ue(e)!=="type")return!1;let t=T(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function fq(e,t,n,r){let i=new Map(n.renamedFiles.map(s=>[s.to,s.from])),o=r??xo(e,t,Ro(n));return s=>{let a=i.get(s.file)??s.file,c=T(s.symbol);if(!c)return!1;let l=o(a);return l!==null&&pq(l,c)}}function pq(e,t){return new RegExp(`\\b${$(t)}\\b`).test(e)}function gq(e,t){if(!rc(ii(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=gm(e);for(let r of n.newFindings.filter(i=>!i.startsWith(cr))){let i=tm(r),o=ve("baseline",r);jt(t,{id:o,groupKey:`baseline:${i.sourceAnalyzer}:${i.rootCauseKey}`,check:"baseline",severity:"error",evidence:"baseline",actionTier:i.actionTier,confidence:1,file:i.file,relatedFiles:i.relatedFiles.length>0?i.relatedFiles:void 0,sourceAnalyzer:i.sourceAnalyzer,rootCauseKey:i.rootCauseKey,message:`new ${i.label} vs committed baseline: ${r}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline.",`Underlying analyzer: ${i.sourceAnalyzer}.`,`Inherited action tier: ${i.actionTier}.`,`Root cause key: ${i.rootCauseKey}.`,...i.why],remediation:i.remediation})}}function hq(e,t){if(!fC(e.config.architecture)){t.skipped.push({check:"architecture",reason:"no closed architecture dependency rows, requireCompletePolicy rule, or requireAcyclic rule configured"});return}if(!rc(ii(e))){t.skipped.push({check:"architecture",reason:"no .scipquery-baseline.json \u2014 run health --write-baseline to enable"});return}t.checksRun.push("architecture");let n=IR(e);for(let r of n.newFindings){let i=tm(r),o=ve("architecture",r);jt(t,{id:o,groupKey:`architecture:${i.rootCauseKey}`,check:"architecture",severity:"error",evidence:"baseline",actionTier:"direct",confidence:1,sourceAnalyzer:"architecture",rootCauseKey:i.rootCauseKey,message:`new ${i.label} vs committed baseline: ${r}`,why:["The project declares an enforceable architecture rule.","The current boundary graph contains a violation not present in the committed baseline.",...i.why],remediation:i.remediation})}}function ve(e,...t){return`SQ${MV("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}import{dirname as yq,relative as bq,resolve as Sq}from"path";var Cq=new Set(Lt());function xq(e,t){return`tests/generated/twin-ab/${AR(e)}-vs-${AR(t)}.test.ts`}function AR(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function Rq(e,t,n,r){let i=MR(e,t);if(!i.ok)return i;let o=MR(e,n);if(!o.ok)return o;let s=i.symbol.paramCount===null||o.symbol.paramCount===null?null:i.symbol.paramCount===o.symbol.paramCount,a=Iq(i.symbol,o.symbol,e.config.projectRoot,r,s);return{ok:!0,a:i.symbol,b:o.symbol,signatureCompatible:s,testSource:a}}function MR(e,t){let r=Ii(e,t).match;if(!r)return{ok:!1,reason:`${t} does not resolve to an indexed symbol.`};let o=e.get("SELECT kind FROM global_symbols WHERE id = ?",r.symbolId)?.kind??null;if(!(o!==null?Cq.has(o):ee(r.symbol)))return{ok:!1,reason:`${t} resolves to ${I(r.symbol)}${o!==null?` with SCIP kind ${so(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!Po(e,r))return{ok:!1,reason:`${t} (${I(r.symbol)} at ${r.relativePath}:${r.startLine+1}) is not exported \u2014 twin-ab needs an importable named binding for both twins.`};let a=e.get("SELECT documentation FROM global_symbols WHERE id = ?",r.symbolId),c=Jt(Yt(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:r.symbol,shortName:T(r.symbol)||I(r.symbol),file:r.relativePath,startLine:r.startLine,signature:c,paramCount:c?vq(c):null}}}function vq(e){let t=e.indexOf("(");if(t===-1)return null;let n=0,r=-1;for(let a=t;a<e.length;a+=1){let c=e[a];if(c==="(")n+=1;else if(c===")"&&(n-=1,n===0)){r=a;break}}if(r===-1)return null;let i=e.slice(t+1,r).trim();if(!i)return 0;let o=1,s=0;for(let a of i)a==="("||a==="["||a==="{"?s+=1:a===")"||a==="]"||a==="}"?s=Math.max(0,s-1):a===","&&s===0&&(o+=1);return o}function OR(e,t,n){let r=yq(t),i=Sq(e,n),s=bq(r,i).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function Iq(e,t,n,r,i){let o=OR(n,r,e.file),s=OR(n,r,t.file),a=i===null?"Signature comparison: unknown (one or both signatures unavailable in the index) \u2014 check by hand.":i?"Signature comparison: param counts match.":"Signature comparison: param counts DIFFER \u2014 twins may not be directly comparable; check by hand.";return`/**
|
|
800
800
|
* Generated by 'scip-query twin-ab'. scip-integrity-audit drill 5
|
|
801
801
|
* ("cross-examine same-concept twins"): where one concept is computed in
|
|
802
802
|
* more than one place, feed both the same input and require the same
|
|
@@ -834,10 +834,10 @@ describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}'
|
|
|
834
834
|
expect(callA(...args)).toEqual(callB(...args));
|
|
835
835
|
});
|
|
836
836
|
});
|
|
837
|
-
`}var jR={caller:3,"entry-surface":2,rooted:1},
|
|
838
|
-
`&&(n+=1);return n}function WR(e,t){let n=e.slice(t,t+400),r=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return r?r[2]:"(anonymous)"}var Qq=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),UR=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function Zq(e){let t=new Set(["expect","assert"]);UR.lastIndex=0;let n;for(;n=UR.exec(e);){let[,r,i,o,s]=n;if(!(!s||!Qq.has(s))&&(r&&t.add(r),o&&t.add(o),i))for(let a of i.split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let l=/^(\w+)\s+as\s+(\w+)$/.exec(c);t.add(l?l[2]:c)}}return t}function GR(e,t){if(/\.should\b/.test(e)||/\bawait\s+(?:[\w$.]+\.)?findBy[A-Z]\w*\s*\(/.test(e)||/\bawait\s+\w*waitFor(?:Text|Value|Condition|Result|Event)\s*\(/.test(e)||/\bthrow\b/.test(e))return!0;for(let n of t){let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\b${r}\\s*(?:<[^<>]*>)?\\s*[.(]`).test(e))return!0}return!1}var eK=/\bfunction\s+(\w+)\s*\(/g,tK=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,nK=60;function rK(e,t){let n=new Set;for(let r of[eK,tK]){r.lastIndex=0;let i;for(;i=r.exec(e);){let o=i[1],s=i.index+i[0].length-1,a=No(e,s),c=e.indexOf("{",a+1);if(c===-1||c-a>nK)continue;let l=iK(e,c),u=e.slice(c+1,l);GR(u,t)&&n.add(o)}}return n}function iK(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return r}return e.length-1}var oK=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,vm=/\bexpect\s*\(/g,sK=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,zR=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function aK(e,t){let n=cK(e,t,oK);if(n.length===0)return null;let r=lK(e,t);for(let i of r)if(n.includes(i))return i;return null}function cK(e,t,n){let r=[];n.lastIndex=0;let i;for(;i=n.exec(e);){let o=i.index+i[0].length-1,s=No(e,o),a=t.slice(o+1,s).trim();zR.test(a)&&r.push(a),n.lastIndex=s+1}return r}function lK(e,t){let n=[];vm.lastIndex=0;let r;for(;r=vm.exec(e);){let i=r.index+r[0].length-1,o=No(e,i),s=e.slice(o+1),a=sK.exec(s);if(vm.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,l=No(e,c),u=t.slice(c+1,l).trim();zR.test(u)&&n.push(u)}return n}function uK(e,t,n,r){let i=P(e,t),o=WR(i,n.argsStart),s=Lo(i,n.callStart),a=dK(e.config.projectRoot,t,s),c=a===null?"unknown":a>=r?"rot":"workflow";return{file:t,startLine:s,title:o,skipKind:n.skipKind,blockKind:n.kind,ageDays:a,rot:c}}function dK(e,t,n){let r=n+1;try{let i=At(e,["blame","-L",`${r},${r}`,"--porcelain","--",t]),o=/^author-time (\d+)$/m.exec(i);if(!o)return null;let s=Number(o[1]);return Number.isFinite(s)?Math.max(0,Math.round((Date.now()/1e3-s)/86400)):null}catch{return null}}var mK=.7,VR=.62,qR=.45;function fK(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=ze(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let a=RK(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=pK(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:Number.isFinite(r)?void 0:a}).map(d=>vK(d,s,n)).filter(d=>d!==null);l.sort((d,m)=>(d.kind===m.kind?0:d.kind==="echo"?-1:1)||m.similarity-d.similarity||d.echoFile.localeCompare(m.echoFile)||d.echoSymbol.localeCompare(m.echoSymbol)||d.domain.localeCompare(m.domain));let u=l.slice(0,r).map(IK);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:wK(u)}}function pK(e,t){let n=EK(t.limit),r=[...gK(e,{scope:t.scope,minSimilarity:t.minSimilarity??mK,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=as(e,{scope:t.scope});return i.react&&r.push(...hK(e,{scope:t.scope,minSimilarity:t.minSimilarity??VR,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...yK(e,{scope:t.scope,minSimilarity:t.minSimilarity??qR,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...CK(e,{scope:t.scope,minSimilarity:t.minSimilarity??VR,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...xK(e,{scope:t.scope,minSimilarity:t.minSimilarity??qR,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function gK(e,t){return mo(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!Ie(n.symbolA)&&!Ie(n.symbolB)).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 hK(e,t){return oc(e,t,{query:fo,domain:"react-component",basis:"jsx-structure",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]]})}function oc(e,t,n){return n.query(e,t).filter(r=>r.fileA!==r.fileB).filter(r=>n.acceptPair?.(r)??!0).map(r=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(r),fileA:r.fileA,symbolB:n.symbolB(r),fileB:r.fileB,similarity:r.similarity,sharedEvidence:kK(...n.evidenceBuckets(r)),sharedCallees:[]}))}function yK(e,t){return oc(e,t,{query:po,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:SK,evidenceBuckets:n=>[["hook",n.sharedHooks],["react-hook",n.sharedReactHooks],["effect",n.sharedEffects],["state",n.sharedState],["request",n.sharedRequests],["handler",n.sharedHandlers],["action",n.sharedHandlerVerbs]]})}var bK=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function SK(e){return e.sharedHooks.some(t=>!bK.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function CK(e,t){return oc(e,t,{query:go,domain:"vue-component",basis:"vue-template",symbolA:n=>ic(n.fileA),symbolB:n=>ic(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function xK(e,t){return oc(e,t,{query:ho,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>ic(n.fileA),symbolB:n=>ic(n.fileB),evidenceBuckets:n=>[["composable",n.sharedComposables],["store",n.sharedStores],["reactivity",n.sharedReactivity],["lifecycle",n.sharedLifecycle],["request",n.sharedRequests],["function",n.sharedFunctions],["action",n.sharedFunctionVerbs],["binding",n.sharedBindings],["template-event",n.sharedTemplateEvents]]})}function RK(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function vK(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 IK(e){let t=KR(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function KR(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 wK(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??KR(r),o=r.groupKey??`recent-duplicate:${i}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:i,kind:r.kind,domain:r.domain,basis:r.basis,count:0,maxSimilarity:r.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:r.kind==="echo"?r.establishedFile:void 0,establishedSymbol:r.kind==="echo"?r.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:DK(r)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,r.similarity),s.findingIndexes.push(n),s.echoFiles.add(r.echoFile),s.relatedFiles.add(r.echoFile),s.relatedFiles.add(r.establishedFile);for(let a of r.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,r)=>r.count-n.count||r.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(r.groupKey))}function DK(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 EK(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function kK(...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 ic(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var PK=J("suppression-inventory",{clearGroups:["whole-project"]});function sc(e){return PK.get(e,()=>TK(e))}function TK(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,twin:0,uncategorized:0},n=new Map,r=0;for(let i of $e(e)){let o=P(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=di(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=_K(a);t[c]+=1}}return{total:r,byCategory:t,byFile:n}}function _K(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as FK}from"fs";import{join as LK}from"path";function Im(e,t,n={}){let r=B(e,t);if(!r)return null;let i=new _(e),o=NK(e,r),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:I(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:l.size,fanIn:MK(e,r.symbolId),fanOut:OK(c,r.relativePath)}}function NK(e,t){let n=q(e,t.relativePath);if(n){let r=QR(n.rootNode,t.startLine,t.endLine);if(r)return{branches:jK(r),estimateBasis:"ast"}}return{branches:ev(XR(e,t.relativePath,t.startLine,t.endLine),YR(e,t.relativePath)),estimateBasis:"regex-fallback"}}function JR(e,t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath)??[];o.push(i),r.set(i.relativePath,o)}for(let[i,o]of r){let s=q(e,i),a=s===null?[]:o.filter(l=>s.rootNode.startPosition.row<=l.startLine&&s.rootNode.endPosition.row>=l.endLine),c=new Set(a.map(l=>l.symbolId));if(s&&a.length>0){for(let l of a)n.set(l.symbolId,{branches:0,estimateBasis:"ast"});BK(s.rootNode,a,n)}for(let l of o)c.has(l.symbolId)||n.set(l.symbolId,AK(e,l))}return n}function AK(e,t){return{branches:ev(XR(e,t.relativePath,t.startLine,t.endLine),YR(e,t.relativePath)),estimateBasis:"regex-fallback"}}function YR(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function XR(e,t,n,r){try{return FK(LK(e.config.projectRoot,t),"utf-8").split(`
|
|
837
|
+
`}var jR={caller:3,"entry-surface":2,rooted:1},wq=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,Dq=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,Eq=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,kq=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,Pq=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function Tq(e,t={}){let{scope:n,limit:r=30,scanLimit:i,semantic:o=!0}=t,s=new _(e),a=se(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),c=[];for(let f of a){let p=Fq(e,f);p&&c.push(p)}if(c.length===0)return[];let l=Mq(e,c,a),u=c.filter(f=>!l.has(f.def.symbol));if(u.length===0)return[];let d=on(e,s).forDefinitions(u.map(f=>f.def),{semantic:o}),m=[];for(let f of u){let g=d.get(f.def.symbolId)?.realConsumers.length??0,y=_q(e,f.def,g);y&&m.push({symbol:f.def.symbol,shortName:I(f.def.symbol),file:f.def.relativePath,startLine:f.def.startLine,endLine:f.def.endLine,loc:O(f.def),stubKind:f.stubKind,reachability:y,callerFanIn:g,stubText:f.stubText})}return m.sort((f,p)=>jR[p.reachability]-jR[f.reachability]||p.callerFanIn-f.callerFanIn||f.file.localeCompare(p.file)||f.startLine-p.startLine),r?m.slice(0,r):m}function _q(e,t,n){return n>0?"caller":de(e,t.symbol,t.relativePath)?"rooted":Ee(e,t.relativePath)?"entry-surface":null}function Fq(e,t){let n=cn(e,t);if(!n)return null;let r=Ot(n),i=r.trim();if(i==="")return!Aq(n)||!Po(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=Si(r),s=st(r),a=Lq(o,s);if(a.length!==1)return null;let c=a[0];return Nq(c)?{def:t,stubKind:"throw-stub",stubText:c.trim()}:kq.test(r)&&Eq.test(c.trim())?{def:t,stubKind:"todo-return-default",stubText:i}:null}function Lq(e,t){let n=[],r=0,i="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="("||s==="["||s==="{"?r+=1:(s===")"||s==="]"||s==="}")&&(r=Math.max(0,r-1)),s===";"&&r===0){n.push(i),i="";continue}i+=e[o]??""}return i.trim()&&n.push(i),n.map(o=>o.trim()).filter(o=>o.length>0)}function Nq(e){let t=Dq.exec(e.trim());return t?wq.test(t[1]??""):!1}function Aq(e){return Pq.test(e.trimEnd())}function Mq(e,t,n){let r=new Set,i=new Set(t.map(a=>a.def.parentTypeName).filter(a=>a!==null));if(i.size===0)return r;let o=jq(e,i),s=new Map;for(let a of n){if(!a.parentTypeName)continue;let c=s.get(a.leaf)??new Set;c.add(a.parentTypeName),s.set(a.leaf,c)}for(let a of t){let c=a.def.parentTypeName;if(!c)continue;let l=o.get(c);if(!l||l.size===0)continue;let u=s.get(a.def.leaf)??new Set;[...l].every(m=>u.has(m))&&r.add(a.def.symbol)}return r}var Oq=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function jq(e,t){let n=new Map;for(let r of N(e,{includeIgnored:!1})){let i=P(e,r);if(i)for(let o of i.matchAll(Oq)){let s=o[1],a=o[2];if(!s||!a||!t.has(a))continue;let c=n.get(a)??new Set;c.add(s),n.set(a,c)}}return n}var Bq=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,$q=/^(?:is|has)(?:[A-Z].*)?$/,Hq=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,xm=/\breturn\b/g,Uq=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,Wq=/\.(?:addIssue|push)\s*\(/;function Gq(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new _(e),s=se(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),a=[];for(let c of s){let l=Vq(e,c);l&&a.push({symbol:c.symbol,shortName:I(c.symbol),file:c.relativePath,startLine:c.startLine,endLine:c.endLine,loc:O(c),...l})}return a.sort((c,l)=>c.file.localeCompare(l.file)||c.startLine-l.startLine||c.loc-l.loc),r?a.slice(0,r):a}function zq(e){return Bq.test(e)?"imperative":$q.test(e)?"predicate":null}function Vq(e,t){let n=zq(t.leaf);if(!n||Vr(e,t))return null;let r=cn(e,t);if(!r||!Uq.test(r))return null;let i=G(e,t.relativePath)?.callables.find(s=>s.startLine===t.startLine&&s.endLine===t.endLine);if(n==="predicate"&&i?.paramCount===0)return null;if(nR(r)){let s=Jq(e,t);return!s||HR(s.body,$R(s.snippet))||BR(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=Ot(r);return HR(o,$R(r))||BR(o)?null:{nameKind:n,resolvedVia:"direct"}}var qq=new Set(["if","for","while","switch","catch","function"]);function BR(e){let t=Si(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!qq.has(n[1]))return!0;return!1}function $R(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function HR(e,t){let n=Si(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||Hq.test(n)||Wq.test(n))return!0;let r=Kq(n);if(t&&r.length===0){let i=n.trim();return i!==""&&i!=="true"}for(let i of r)if(i!==""&&i!=="true")return!0;return!1}function Kq(e){let t=[];xm.lastIndex=0;let n;for(;n=xm.exec(e);){let r=n.index+n[0].length,i=0,o=e.length;for(let s=r;s<e.length;s+=1){let a=e[s];if(a==="("||a==="["||a==="{")i+=1;else if(a===")"||a==="]"||a==="}"){if(i===0){o=s;break}i-=1}else if(a===";"&&i===0){o=s;break}}t.push(e.slice(r,o).trim()),xm.lastIndex=o}return t}function Jq(e,t){let n=ft(e,t,{callableOnly:!0,limit:3,semanticEvidence:H}),r=[...new Set(n.map(c=>c.symbol))].filter(c=>c!==t.symbol);if(r.length!==1)return null;let o=Ii(e,r[0]).match;if(!o)return null;let s=Q(e,o.relativePath).find(c=>c.symbolId===o.symbolId);if(!s)return null;let a=cn(e,s);return a?{body:Ot(a),snippet:a,shortName:I(s.symbol)}:null}var Yq=60;function Xq(e,t={}){let{scope:n,limit:r=30,scanLimit:i,rotDays:o=Yq}=t,s=se($e(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>Y(u)==="test").filter(u=>!n||u.includes(n)).filter(u=>!e.isIgnored(u)).sort(),i),a=[],c=[],l=[];for(let u of s){let d=P(e,u);if(!d)continue;let m=Cp(d),f=eK(d);for(let g of iK(m,f))f.add(g);let p=Qq(m);for(let g of p){if(g.skip){c.push(dK(e,u,g,o));continue}if(g.kind==="describe")continue;let y=WR(d,g.argsStart),h=m.slice(g.argsStart,g.callEnd),C=d.slice(g.argsStart,g.callEnd);GR(h,f)||a.push({file:u,startLine:Lo(d,g.callStart),endLine:Lo(d,g.callEnd),title:y,severity:/\bawait\b/.test(h)?"low":"high"});let x=cK(h,C);x&&l.push({file:u,startLine:Lo(d,g.callStart),endLine:Lo(d,g.callEnd),title:y,echoedValue:x})}}return{assertionFree:r?a.slice(0,r):a,skipped:r?c.slice(0,r):c,mockEcho:r?l.slice(0,r):l}}var Rm=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function Qq(e){let t=[];Rm.lastIndex=0;let n;for(;n=Rm.exec(e);){let r=n[1],i=r??n[2];if(!i)continue;let o=n[3]?.split(/\s*\(/)[0],s=n.index,a=n.index+n[0].length-1,c=No(e,a);Rm.lastIndex=a+1,o!=="each"&&t.push({kind:i,skip:r!==void 0||o==="skip"||o==="todo",skipKind:o==="todo"?"todo":"skip",callStart:s,argsStart:a+1,callEnd:c+1})}return t}function No(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="(")n+=1;else if(i===")"&&(n-=1,n===0))return r}return e.length-1}function Lo(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
|
|
838
|
+
`&&(n+=1);return n}function WR(e,t){let n=e.slice(t,t+400),r=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return r?r[2]:"(anonymous)"}var Zq=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),UR=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function eK(e){let t=new Set(["expect","assert"]);UR.lastIndex=0;let n;for(;n=UR.exec(e);){let[,r,i,o,s]=n;if(!(!s||!Zq.has(s))&&(r&&t.add(r),o&&t.add(o),i))for(let a of i.split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let l=/^(\w+)\s+as\s+(\w+)$/.exec(c);t.add(l?l[2]:c)}}return t}function GR(e,t){if(/\.should\b/.test(e)||/\bawait\s+(?:[\w$.]+\.)?findBy[A-Z]\w*\s*\(/.test(e)||/\bawait\s+\w*waitFor(?:Text|Value|Condition|Result|Event)\s*\(/.test(e)||/\bthrow\b/.test(e))return!0;for(let n of t){let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\b${r}\\s*(?:<[^<>]*>)?\\s*[.(]`).test(e))return!0}return!1}var tK=/\bfunction\s+(\w+)\s*\(/g,nK=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,rK=60;function iK(e,t){let n=new Set;for(let r of[tK,nK]){r.lastIndex=0;let i;for(;i=r.exec(e);){let o=i[1],s=i.index+i[0].length-1,a=No(e,s),c=e.indexOf("{",a+1);if(c===-1||c-a>rK)continue;let l=oK(e,c),u=e.slice(c+1,l);GR(u,t)&&n.add(o)}}return n}function oK(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return r}return e.length-1}var sK=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,vm=/\bexpect\s*\(/g,aK=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,zR=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function cK(e,t){let n=lK(e,t,sK);if(n.length===0)return null;let r=uK(e,t);for(let i of r)if(n.includes(i))return i;return null}function lK(e,t,n){let r=[];n.lastIndex=0;let i;for(;i=n.exec(e);){let o=i.index+i[0].length-1,s=No(e,o),a=t.slice(o+1,s).trim();zR.test(a)&&r.push(a),n.lastIndex=s+1}return r}function uK(e,t){let n=[];vm.lastIndex=0;let r;for(;r=vm.exec(e);){let i=r.index+r[0].length-1,o=No(e,i),s=e.slice(o+1),a=aK.exec(s);if(vm.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,l=No(e,c),u=t.slice(c+1,l).trim();zR.test(u)&&n.push(u)}return n}function dK(e,t,n,r){let i=P(e,t),o=WR(i,n.argsStart),s=Lo(i,n.callStart),a=mK(e.config.projectRoot,t,s),c=a===null?"unknown":a>=r?"rot":"workflow";return{file:t,startLine:s,title:o,skipKind:n.skipKind,blockKind:n.kind,ageDays:a,rot:c}}function mK(e,t,n){let r=n+1;try{let i=Mt(e,["blame","-L",`${r},${r}`,"--porcelain","--",t]),o=/^author-time (\d+)$/m.exec(i);if(!o)return null;let s=Number(o[1]);return Number.isFinite(s)?Math.max(0,Math.round((Date.now()/1e3-s)/86400)):null}catch{return null}}var fK=.7,VR=.62,qR=.45;function pK(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=ze(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let a=vK(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=gK(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:Number.isFinite(r)?void 0:a}).map(d=>IK(d,s,n)).filter(d=>d!==null);l.sort((d,m)=>(d.kind===m.kind?0:d.kind==="echo"?-1:1)||m.similarity-d.similarity||d.echoFile.localeCompare(m.echoFile)||d.echoSymbol.localeCompare(m.echoSymbol)||d.domain.localeCompare(m.domain));let u=l.slice(0,r).map(wK);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:DK(u)}}function gK(e,t){let n=kK(t.limit),r=[...hK(e,{scope:t.scope,minSimilarity:t.minSimilarity??fK,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=as(e,{scope:t.scope});return i.react&&r.push(...yK(e,{scope:t.scope,minSimilarity:t.minSimilarity??VR,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...bK(e,{scope:t.scope,minSimilarity:t.minSimilarity??qR,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...xK(e,{scope:t.scope,minSimilarity:t.minSimilarity??VR,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...RK(e,{scope:t.scope,minSimilarity:t.minSimilarity??qR,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function hK(e,t){return mo(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!Ie(n.symbolA)&&!Ie(n.symbolB)).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 yK(e,t){return oc(e,t,{query:fo,domain:"react-component",basis:"jsx-structure",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]]})}function oc(e,t,n){return n.query(e,t).filter(r=>r.fileA!==r.fileB).filter(r=>n.acceptPair?.(r)??!0).map(r=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(r),fileA:r.fileA,symbolB:n.symbolB(r),fileB:r.fileB,similarity:r.similarity,sharedEvidence:PK(...n.evidenceBuckets(r)),sharedCallees:[]}))}function bK(e,t){return oc(e,t,{query:po,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:CK,evidenceBuckets:n=>[["hook",n.sharedHooks],["react-hook",n.sharedReactHooks],["effect",n.sharedEffects],["state",n.sharedState],["request",n.sharedRequests],["handler",n.sharedHandlers],["action",n.sharedHandlerVerbs]]})}var SK=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function CK(e){return e.sharedHooks.some(t=>!SK.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function xK(e,t){return oc(e,t,{query:go,domain:"vue-component",basis:"vue-template",symbolA:n=>ic(n.fileA),symbolB:n=>ic(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function RK(e,t){return oc(e,t,{query:ho,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>ic(n.fileA),symbolB:n=>ic(n.fileB),evidenceBuckets:n=>[["composable",n.sharedComposables],["store",n.sharedStores],["reactivity",n.sharedReactivity],["lifecycle",n.sharedLifecycle],["request",n.sharedRequests],["function",n.sharedFunctions],["action",n.sharedFunctionVerbs],["binding",n.sharedBindings],["template-event",n.sharedTemplateEvents]]})}function vK(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function IK(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 wK(e){let t=KR(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function KR(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 DK(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??KR(r),o=r.groupKey??`recent-duplicate:${i}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:i,kind:r.kind,domain:r.domain,basis:r.basis,count:0,maxSimilarity:r.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:r.kind==="echo"?r.establishedFile:void 0,establishedSymbol:r.kind==="echo"?r.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:EK(r)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,r.similarity),s.findingIndexes.push(n),s.echoFiles.add(r.echoFile),s.relatedFiles.add(r.echoFile),s.relatedFiles.add(r.establishedFile);for(let a of r.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,r)=>r.count-n.count||r.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(r.groupKey))}function EK(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 kK(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function PK(...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 ic(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var TK=J("suppression-inventory",{clearGroups:["whole-project"]});function sc(e){return TK.get(e,()=>_K(e))}function _K(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,twin:0,uncategorized:0},n=new Map,r=0;for(let i of $e(e)){let o=P(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=di(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=FK(a);t[c]+=1}}return{total:r,byCategory:t,byFile:n}}function FK(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as LK}from"fs";import{join as NK}from"path";function Im(e,t,n={}){let r=B(e,t);if(!r)return null;let i=new _(e),o=AK(e,r),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:I(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:l.size,fanIn:OK(e,r.symbolId),fanOut:jK(c,r.relativePath)}}function AK(e,t){let n=q(e,t.relativePath);if(n){let r=QR(n.rootNode,t.startLine,t.endLine);if(r)return{branches:BK(r),estimateBasis:"ast"}}return{branches:ev(XR(e,t.relativePath,t.startLine,t.endLine),YR(e,t.relativePath)),estimateBasis:"regex-fallback"}}function JR(e,t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath)??[];o.push(i),r.set(i.relativePath,o)}for(let[i,o]of r){let s=q(e,i),a=s===null?[]:o.filter(l=>s.rootNode.startPosition.row<=l.startLine&&s.rootNode.endPosition.row>=l.endLine),c=new Set(a.map(l=>l.symbolId));if(s&&a.length>0){for(let l of a)n.set(l.symbolId,{branches:0,estimateBasis:"ast"});$K(s.rootNode,a,n)}for(let l of o)c.has(l.symbolId)||n.set(l.symbolId,MK(e,l))}return n}function MK(e,t){return{branches:ev(XR(e,t.relativePath,t.startLine,t.endLine),YR(e,t.relativePath)),estimateBasis:"regex-fallback"}}function YR(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function XR(e,t,n,r){try{return LK(NK(e.config.projectRoot,t),"utf-8").split(`
|
|
839
839
|
`).slice(n,r+1).join(`
|
|
840
|
-
`)}catch{return""}}function
|
|
840
|
+
`)}catch{return""}}function OK(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
|
|
841
841
|
FROM mentions m
|
|
842
842
|
JOIN chunks c ON m.chunk_id = c.id
|
|
843
843
|
JOIN (
|
|
@@ -849,9 +849,9 @@ describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}'
|
|
|
849
849
|
) sym_def ON sym_def.symbol_id = m.symbol_id
|
|
850
850
|
WHERE m.symbol_id = ?
|
|
851
851
|
AND m.role != 1
|
|
852
|
-
AND sym_def.document_id != c.document_id`,t)?.c??0}function
|
|
852
|
+
AND sym_def.document_id != c.document_id`,t)?.c??0}function jK(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function BK(e){let t=0;return wm(e,n=>{t+=ZR(n)}),t}function $K(e,t,n){let r=[...t].sort((i,o)=>i.startLine-o.startLine||o.endLine-i.endLine);wm(e,i=>{let o=ZR(i);if(o===0)return;let s=i.startPosition.row,a=i.endPosition.row;for(let c of r){if(c.startLine>s)break;if(c.endLine<a)continue;let l=n.get(c.symbolId);l&&(l.branches+=o)}})}function wm(e,t){t(e);for(let n of e.namedChildren)wm(n,t)}function QR(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let r of e.namedChildren){let i=QR(r,t,n);if(i)return i}return e}var HK=new Set(["if_statement","conditional_expression","ternary_expression","for_statement","for_in_statement","for_of_statement","while_statement","do_statement","switch_case","case_statement","catch_clause","except_clause","elif_clause","match_arm"]);function ZR(e){return HK.has(e.type)?1:e.type==="binary_expression"&&e.parent?.type!=="binary_expression"&&(e.text.includes("&&")||e.text.includes("||"))?UK(e.text):0}function UK(e){return(e.match(/&&|\|\|/g)??[]).length}function ev(e,t){let n=st(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 Dm(e,t,n={}){let r=B(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=Et(e,r,{semantic:n.semantic,semanticEvidence:H}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?I(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=WK(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:I(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:I(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)":I(c.symbol),file:c.file}))}}function WK(e,t,n,r){let i=zr(ft(e,t,{limit:30,semantic:r.semantic,semanticEvidence:H}).map(a=>({symbol:a.symbol,file:a.file}))),o=zr(xt(e,t,{limit:30,semantic:r.semantic,semanticEvidence:H})),s=o.length>0?o:zr(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function ac(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=B(e,t);return o?r==="backward"?GK(e,o,i,{semantic:n.semantic!==!1}):zK(e,o,{semantic:n.semantic!==!1}):null}function GK(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=ft(e,l,{semantic:r.semantic,semanticEvidence:H});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),i.push({symbol:d.symbol,shortName:I(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=wi(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:I(t.symbol),direction:"backward",connectedSymbols:i}}function zK(e,t,n){let r=new Set,i=[],o=new _(e);for(let s of Et(e,t,{semantic:n.semantic,semanticEvidence:H})){if(i.length>=30)break;let a=s.enclosingSymbol??Dt(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=wi(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:I(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:I(t.symbol),direction:"forward",connectedSymbols:i}}function VK(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=!KK(t),a=s?Ne("trace",t,()=>ud(e,t,{semantic:o}),R=>({definitions:R.definitions.length,references:R.referencedBy.length})):{definitions:[],referencedBy:[]},c=s?Ne("call-graph",t,()=>Rd(e,t,{semantic:o}),R=>({callers:R?.callers.length??0,callees:R?.callees.length??0})):null,l=s?Ne("complexity",t,()=>Im(e,t,{semantic:o}),R=>({callees:R?.calleeCount??0})):null,u=s?Ne("dataflow",t,()=>Dm(e,t,{semantic:o}),R=>({references:R?.usageSites.length??0,producers:R?.producers.length??0,consumers:R?.consumers.length??0})):null,d=s?Ne("backward-slice",t,()=>ac(e,t,{direction:"backward",maxDepth:i,semantic:o}),R=>({maxDepth:i,connectedSymbols:R?.connectedSymbols.length??0})):null,m=s?Ne("forward-slice",t,()=>ac(e,t,{direction:"forward",maxDepth:i,semantic:o}),R=>({maxDepth:i,connectedSymbols:R?.connectedSymbols.length??0})):null,f=s?Ne("affected",t,()=>jd(e,t,{maxDepth:r,scope:n.scope}),R=>({maxDepth:r,affectedSymbols:R.length})):[],p=Ne("change-surface",t,()=>Bd(e,t,{semantic:o}),R=>({symbols:R?.symbols.length??0,externalConsumers:R?.totalExternalConsumers??0})),g=Ne("system",t,()=>fd(e,t),R=>({files:R.files.length,symbols:R.symbols.length})),y=g.files.length===1,h=Ne("deps",t,()=>y?g.dependsOn.map(R=>({relativePath:R})):dd(e,t),R=>({files:R.length,reusedSystem:y})),C=Ne("rdeps",t,()=>y?g.dependedOnBy.map(R=>({relativePath:R})):md(e,t),R=>({files:R.length,reusedSystem:y})),x=Ne("surface",t,()=>pd(e,t),R=>({consumers:R.length})),S={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||d!==null||m!==null||f.length>0,file:p!==null||h.length>0||C.length>0,module:g.files.length>0||g.symbols.length>0||x.length>0},b=[];!S.symbol&&!S.file&&!S.module&&b.push("No symbol, file, or module matched target.");let v=p?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:S,history:Ne("history",v??t,()=>qK(e,v,n.gitHead)),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:d,forwardSlice:m,affected:f,changeSurface:p,deps:h,rdeps:C,system:g,surface:x,warnings:b}}function Ne(e,t,n,r=()=>({})){let i;return w(`plan-context.${e}`,()=>(i=n(),i),()=>({target:t,...r(i)}))}function qK(e,t,n){let r={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return r;let i=ze(e,n?{head:n}:{}),o=Ne("history.churn",t,()=>i.fileChurn(),c=>({files:c?.size??0}));if(!o)return r;let s=Ne("history.co-change",t,()=>So(e,t,{limit:5,...n?{head:n}:{}}),c=>({commits:c.commitsAnalyzed,partners:c.findings.length})),a=Ne("history.suppressions",t,()=>sc(e).byFile.get(t)??0,c=>({suppressions:c}));return{available:!0,file:t,churn:o.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:s.findings.map(c=>({file:c.fileA===t?c.fileB:c.fileA,together:c.together,confidence:c.confidence,subjectContext:c.subjectContext})),suppressionsInFile:a}}function KK(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var JK=new Set(Lt());function Em(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new _(e);return gt({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:r,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:YK,profile:{name:"complexity-hotspots"},prepare:a=>{let c=QK(e,a),l=t?.semantic!==!1,u=l?We(e):null;u?.materializeReferences(a,{prefetchCallees:!0});let d=s.crossFileCallerMap(a,{semantic:!1});return{callerMap:u?rn(d,u.callerMap(a)):d,calleeMap:s.calleeMap(a,{semantic:l}),languageByFile:c,clojureCallableIds:ZK(e,a,c),branchEstimates:JR(e,a)}},evaluate:(a,c)=>XK(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function YK(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&JK.has(e.kind):!0}function XK(e,t,n){if(t.languageByFile.get(e.relativePath)==="clojure"&&!t.clojureCallableIds.has(e.symbolId))return null;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=new Set,a=new Set;for(let m of o){let f=`${m.symbol}|${m.file}`;s.add(f),m.file!==e.relativePath&&a.add(f)}let c=a.size,l=s.size,u=t.branchEstimates.get(e.symbolId)??{branches:0,estimateBasis:"regex-fallback"},d=u.branches+1;return{symbol:e.symbol,shortName:I(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:c,calleeCount:l,branches:u.branches,estimateBasis:u.estimateBasis,score:Math.round(r/50*(i/5)*Math.max(c/5,1)*Math.max(d/5,1)*100)/100}}function QK(e,t){let n=[...new Set(t.map(o=>o.relativePath))];if(n.length===0)return new Map;let r=n.map(()=>"?").join(", "),i=e.all(`SELECT relative_path, language
|
|
853
853
|
FROM documents
|
|
854
|
-
WHERE relative_path IN (${r})`,...n);return new Map(i.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function QK(e,t,n){let r=new Set,i=new Map;for(let o of t){if(n.get(o.relativePath)!=="clojure")continue;let s=i.get(o.relativePath);s||(s=new Set((G(e,o.relativePath)?.callables??[]).map(a=>`${a.name}:${a.startLine}`)),i.set(o.relativePath,s)),s.has(`${o.leaf}:${o.startLine}`)&&r.add(o.symbolId)}return r}function jt(e,t){return`${e}\0${t}`}function yfe(e,t,n,r,i,o={}){let s=new Map(e.map(l=>[jt(l.check,l.findingId),l])),a=[],c=(l,u)=>{let d=n.get(l.findingId),m=u==="resolved"?o.verifiedAgainstByFinding?.get(jt(l.check,l.findingId)):void 0;a.push({ts:i,check:l.check,findingId:l.findingId,event:u,commit:r,...o.comparisonBaseCommit?{comparisonBaseCommit:o.comparisonBaseCommit}:{},...m?{verifiedAgainstCommit:m}:{},...d?{symbol:d}:{}})};for(let l of t){let u=s.get(jt(l.check,l.findingId));if(!u){c(l,"caught"),l.outcome==="suppressed"&&c(l,"suppressed");continue}u.outcome!==l.outcome&&(l.outcome==="resolved"?c(l,"resolved"):l.outcome==="suppressed"?c(l,"suppressed"):l.outcome==="still-open"&&c(l,"reopened"))}return a}function bfe(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n?.event==="caught"||n?.event==="reopened")return n}}function ZK(e,t,n,r,i=new Set){let o=new Map(e.map(c=>[jt(c.check,c.findingId),c])),s=new Set(t.map(c=>jt(c.check,c.findingId))),a=new Set(n);for(let c of t){let l=jt(c.check,c.findingId),u=o.get(l),d=c.suppressed?"suppressed":"still-open";u?o.set(l,{...u,lastSeen:r,timesShown:u.timesShown+1,outcome:d}):o.set(l,{check:c.check,findingId:c.findingId,firstSeen:r,lastSeen:r,timesShown:1,outcome:d})}for(let c of e){if(!a.has(c.check))continue;let l=jt(c.check,c.findingId);s.has(l)||i.has(l)||c.outcome!=="resolved"&&o.set(l,{...c,outcome:"resolved"})}return[...o.values()]}function km(e,t){let n=new Map;for(let i of e){let o=n.get(i.check)??[];o.push(i),n.set(i.check,o)}let r=[];for(let[i,o]of n){let s=o.filter(d=>d.outcome==="resolved").length,a=o.filter(d=>d.outcome==="suppressed").length,c=o.filter(d=>d.outcome==="still-open").length,l=o.length,u=o.filter(d=>d.outcome==="still-open").sort((d,m)=>d.firstSeen-m.firstSeen)[0];r.push({check:i,seen:l,resolved:s,suppressed:a,stillOpen:c,resolutionRate:l>0?s/l:0,suppressionRate:l>0?a/l:0,oldestOpenAgeDays:u?Math.floor((t-u.firstSeen)/tv):null})}return r.sort((i,o)=>i.check.localeCompare(o.check))}var tv=864e5,e2=50,t2=.1,n2=10;function r2(e,t,n){return e.filter(r=>r.check===t).sort((r,i)=>i.firstSeen-r.firstSeen).slice(0,n)}function Rfe(e,t,n){if(t.length===0)return null;let r=new Map(e.map(s=>[jt(s.check,s.findingId),s])),i=t.map(s=>r.get(jt(s.check,s.findingId))).filter(s=>s!==void 0&&s.timesShown>1);if(i.length===0)return null;let o=Math.max(...i.map(s=>Math.floor((n-s.firstSeen)/tv)));return`${t.length} finding(s), ${i.length} shown before and unresolved (oldest: ${o} day(s))`}function vfe(e,t){let n=[];for(let r of[...new Set(t)].sort()){let i=r2(e,r,e2);i.length<n2||i.filter(a=>a.outcome==="resolved").length/i.length>=t2||n.push(`(the ${r} check's findings are rarely acted on in this repo \u2014 consider suppressing with reasons or tuning its config)`)}return n}function cc(e){return nf(e).map(t=>({check:t.check,findingId:t.findingId,firstSeen:t.firstSeen,lastSeen:t.lastSeen,timesShown:t.timesShown,outcome:t.outcome}))}function Ife(e,t,n,r=Date.now(),i=new Set){let o=cc(e),s=ZK(o,t,n,r,i);return rf(e,s),s}function cn(e){return e.scoreCount??e.count}function iv(e){let t=a2(e),{breakdown:n,pressure:r}=c2(e),i=rv(n,"risk"),o=rv(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,duplicateBodyGroups:e.duplicateBodies.count,duplicateBodyLoc:e.duplicateBodies.loc,twinDriftGroups:e.twinDrift.count,twinDriftLoc:e.twinDrift.loc,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:cn(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:cn(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:cn(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,coverageContractViolations:e.coverageContracts.count},axes:i2(e),validation:s2(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0,detectorPrecision:[]}}function i2(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:o2(e),evidenceQuality:{graphFindings:e.dead.count+e.isolated.count+e.realCycleCount,heuristicFindings:e.similarCount+e.duplicateBodies.count+e.twinDrift.count+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 o2(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:Bt(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function s2(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],twinDrift:e.twinDrift.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?Bt(i/r.size):0,c=s>0?Bt(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let f=0;for(let g of m)f+=t[g]?.fixChanges??0;let p=Bt(f/m.size);l[u]={flaggedFiles:m.size,fixDensity:p,lift:c>0?Bt(p/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?Bt(a/c):null,byCategory:l,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function Bt(e){return Math.round(e*100)/100}function ov(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function lc(e,t="existing shared infrastructure discount"){let n=cn(e);return Math.abs(n-e.count)<.01?"":` (${ov(n)} score-weighted after ${t})`}function Ao(e,t){let n=cn(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${ov(n)} score-weighted)`}function a2(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",description:`${e.dead.count} indexed symbols with no visible repository references \u2014 review runtime/framework roots and the capability disclosure, then verify any deletion with cleanup-plan --verify`,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} indexed dependency cycle(s) \u2014 inspect ownership and runtime order before choosing whether or how to break them`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",description:`${e.similarCount} pairs share disclosed call or source-token evidence beyond imports \u2014 review domain identity before considering consolidation`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.duplicateBodies.count>0&&t.push({category:"Duplicate function bodies",evidence:"heuristic",description:`${e.duplicateBodies.count} exact small-body group(s) across files \u2014 consolidate only when the domain concept matches`,effort:"low",impact:"medium",count:e.duplicateBodies.count,locRecoverable:e.duplicateBodies.loc}),e.twinDrift.count>0&&t.push({category:"Drifted twin implementations",evidence:"heuristic",description:`${e.twinDrift.count} same-name (or near-name) function group(s) across files with diverged or identical bodies \u2014 determine whether they represent the same concept before acting`,effort:"medium",impact:"medium",count:e.twinDrift.count,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 review whether local product intent justifies reuse`,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${lc(e.reactHookCandidates)} \u2014 review whether a common hook would preserve ownership and lifecycle semantics`,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 review whether local product intent justifies reuse`,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${lc(e.vueComposableCandidates)} \u2014 review whether a common composable would preserve ownership and lifecycle semantics`,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${lc(e.wrappers,"boundary-evidence discount")} \u2014 inspect whether each is indirection or an intentional API, framework, or ownership boundary`,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 literally forward to one callee \u2014 inspect whether each is unnecessary indirection or an intentional boundary`,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 review public, runtime-registration, and ownership evidence before removing, moving, or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.architectureViolations>0&&i.push(`${e.drift.architectureViolations} declared architecture violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${i.join(", ")} \u2014 repair direct dependency-rule breaks; inspect boundary signals with \`drift --architecture\``,effort:e.drift.architectureViolations>0?"medium":"low",impact:e.drift.architectureViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(e.coverageContracts.count>0&&t.push({category:"Coverage contract drift",evidence:"graph-fact",description:`${e.coverageContracts.count} configured coverage contract(s) drifted from their ground-truth source (enumeration rot) \u2014 run \`scip-query diff-gate\` or \`scip-query health --json\` for the missing/extra keys`,effort:"low",impact:"medium",count:e.coverageContracts.count,locRecoverable:0}),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`+lc({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(i?` (e.g. ${i.fileA} \u2194 ${i.fileB})`:"")+" \u2014 inspect whether a shared concept, generated artifact, or coordinated contract explains the history",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 nv={"dead-code":"risk",isolated:"risk",cycles:"risk",complexity:"risk","hidden-coupling":"risk","cycles-pressure":"risk","complexity-pressure":"risk","hidden-coupling-pressure":"risk",similar:"hygiene","duplicate-bodies":"hygiene","twin-drift":"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","duplicate-bodies-pressure":"hygiene","twin-drift-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 rv(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 c2(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(R,E,D)=>{E>0&&r.push({axis:R,points:E,detail:D,kind:nv[R]??"hygiene"})},s=(R,E,D,k,L,ne,X)=>{let F=Math.max(k,1);if(D<=F)return;let ae=D/F,Z=Math.min(L,Math.ceil(Math.log2(ae)*ne));if(Z<=0)return;let ln=nv[R]??"hygiene";i.push({axis:R,category:E,kind:ln,count:D,threshold:Bt(F),ratio:Bt(ae),extraPenalty:Z}),o(R,Z,`${D} ${X} exceed pressure threshold ${Bt(F)} (${Bt(ae)}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.duplicateBodies.count/n*1e3;o("duplicate-bodies",Math.min(10,Math.round(u*2)),`${e.duplicateBodies.count} exact duplicate small-body group(s) (${e.duplicateBodies.loc} duplicate LOC)`);let d=e.twinDrift.count/n*1e3;o("twin-drift",Math.min(10,Math.round(d*2)),`${e.twinDrift.count} drifted twin implementation group(s) (same or near-same name, diverged or identical bodies)`);let m=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(m)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let f=cn(e.reactHookCandidates),p=f/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(p)),Ao(e.reactHookCandidates,"duplicated React behavior pair(s)"));let g=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(g/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let y=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(y)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let h=cn(e.vueComposableCandidates),C=h/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(C)),Ao(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let x=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(x/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let S=cn(e.wrappers);o("wrappers",Math.min(3,S),Ao(e.wrappers,"wrapper candidate(s)"));let b=cn(e.passthroughs);o("passthroughs",Math.min(3,b),Ao(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 v=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(v*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 R=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(R/10)),Ao({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:R},"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 R=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",R,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("duplicate-bodies-pressure","Duplicate function bodies",e.duplicateBodies.count,Math.max(20,n*.005),8,4,"exact duplicate small-body group(s)"),s("twin-drift-pressure","Drifted twin implementations",e.twinDrift.count,Math.max(20,n*.005),8,4,"drifted twin implementation group(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",f,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",S,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",b,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:r,pressure:i}}import{getHeapStatistics as l2}from"v8";var u2=64*1024*1024;function Pm(){let e=globalThis.gc;if(!e)return;let t=l2();t.heap_size_limit-t.used_heap_size<u2||e()}var d2=50,m2=25e3,f2=2500,sv=2500,av=50,p2=10,uc=["overview","dead","isolated","cycles","similar","duplicate-bodies","twin-drift","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","coverage-contracts"],g2={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:S2(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:C2(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:x2(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:R2(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:I2(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:w2(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:D2(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:E2(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:k2(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:P2(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:T2(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:_2(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:v2(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:F2(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:L2(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:N2(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:j2(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:B2(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:A2(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:M2(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:O2(e,n)})};function Tm(e,t,n={}){return h2(e,[t],n)[0]}function h2(e,t,n={}){return y2(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>g2[s](e,n.scope,o,r))})}function y2(e,t,n){let r=or(e),i=$2(r,t);try{return n(r,i)}finally{yd(e,{semanticProvider:!0}),Pm()}}function _m(e){return iv(b2(e))}function b2(e){let t=ge(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:ge(e,"dead").dead,isolated:ge(e,"isolated").isolated,realCycleCount:ge(e,"cycles").realCycleCount,similarCount:ge(e,"similar").similarCount,duplicateBodies:ge(e,"duplicate-bodies").duplicateBodies,twinDrift:ge(e,"twin-drift").twinDrift,reactComponentDuplicates:ge(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:ge(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:ge(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:ge(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:ge(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:ge(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:ge(e,"extract-candidates").extractCount,wrappers:ge(e,"wrapper-candidates").wrappers,passthroughs:ge(e,"passthrough-candidates").passthroughs,stale:ge(e,"stale-abstractions").stale,drift:ge(e,"drift").drift,complexity:ge(e,"complexity-hotspots").complexity,gitEvidence:cv(e,"git-evidence")?.gitEvidence??null,suppressions:cv(e,"suppressions")?.suppressions??null,coverageContracts:ge(e,"coverage-contracts").coverageContracts}}function cv(e,t){return e.find(n=>n.phase===t)}function ge(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function S2(e,t,n){return fe(e,n,"dead",()=>{let r=sr(e,{scope:t,...me.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return dc(W2(e,r.symbols))})}function C2(e,t,n){return fe(e,n,"isolated",()=>{let r=uo(e,{scope:t,...me.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return dc(G2(e,r))})}function x2(e,t,n){return fe(e,n,"cycles",()=>lo(e,{scope:t}).filter(i=>i.kind==="real").length)}function R2(e,t,n){let r=fe(e,n,"similar",()=>kd(e,{scope:t,...me.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(r,n.candidateResultLimit)}function v2(e,t,n){return fe(e,n,"extract-candidates",()=>yo(e,{scope:t,...me.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function I2(e,t,n){return fe(e,n,"duplicate-bodies",()=>{let r=Io(e,{scope:t,...me.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=new Set,o=0;for(let s of r)for(let a of s.functions.slice(1))i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i]}})}function w2(e,t,n){return fe(e,n,"twin-drift",()=>{let r=ni(e,{scope:t,...me.twinDrift,scanLimit:n.candidateScanLimit}).filter(s=>s.relationship==="divergent"||s.relationship==="identical"),i=new Set,o=0;for(let s of r)for(let a of s.members)i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i].sort()}})}function D2(e,t,n){return fe(e,n,"react-component-duplicates",()=>{let r=fo(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Fm(r)})}function E2(e,t,n){return fe(e,n,"react-hook-candidates",()=>{let r=po(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return dv(r,V2)})}function k2(e,t,n){return fe(e,n,"react-large-component-pressure",()=>{let r=Pd(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return z2(r)})}function P2(e,t,n){return fe(e,n,"vue-component-duplicates",()=>{let r=go(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Fm(r)})}function T2(e,t,n){return fe(e,n,"vue-composable-candidates",()=>{let r=ho(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return dv(r,q2)})}function _2(e,t,n){return fe(e,n,"vue-large-view-pressure",()=>{let r=Td(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return dc(r)})}function F2(e,t,n){return fe(e,n,"wrapper-candidates",()=>{let r=_o(e,{scope:t,...me.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return uv(r,K2)})}function L2(e,t,n){return fe(e,n,"passthrough-candidates",()=>{let r=ko(e,{scope:t,...me.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return uv(r,J2)})}function N2(e,t,n){return fe(e,n,"stale-abstractions",()=>{let r=To(e,{scope:t,...me.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),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 A2(e,t){return fe(e,t,"git-evidence",()=>{let n=ze(e,{historyMode:t.gitHistoryMode}),r=n.fileChurn();if(!r)return null;let i=n.commitHistory(),o=So(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[a,c]of r)s[a]={changes:c.changes,fixChanges:c.fixChanges};return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:o.findings.length,scoreCount:Lm(o.findings.reduce((a,c)=>a+lv(c),0)),top:o.findings.slice(0,5).map(a=>({fileA:a.fileA,fileB:a.fileB,together:a.together,confidence:a.confidence,focusedTogether:a.focusedTogether,broadTogether:a.broadTogether,broadCommitRatio:a.broadCommitRatio,lastTogetherAt:a.lastTogetherAt,recentTogether:a.recentTogether,commitScope:a.commitScope,recency:a.recency,scoreWeight:lv(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:i?.commits.length??0}})}function M2(e,t){return fe(e,t,"suppressions",()=>{let n=sc(e);return{total:n.total,byCategory:{...n.byCategory}}})}function O2(e,t){return fe(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],i=aR(e,n).filter(o=>o.status!=="ok");return{count:i.length,loc:0,files:[...new Set(i.map(o=>o.file))].sort()}})}function j2(e,t,n){return fe(e,n,"drift",()=>{let r=Eo(e,{scope:t,...me.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY,semantic:n.semantic}),i=r.results.filter(a=>a.kind!=="pattern-deviation"),o=i.filter(a=>a.actionTier==="direct").length,s=i.length-o;return{count:i.length,unusedImports:r.unusedImports,architectureViolations:r.architectureViolations,layerViolations:r.layerViolations,direct:o,signal:s}})}function B2(e,t,n){return fe(e,n,"complexity-hotspots",()=>{let r=Em(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.filter(i=>i.score>d2).length}})}function $2(e,t){let n=e.symbols>=m2||e.documents>=f2,r=t?Number.POSITIVE_INFINITY:av,i=t?Number.POSITIVE_INFINITY:p2;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:r,complexityResultLimit:i,semantic:!0,gitHistoryMode:t?"full":"bounded",releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:sv,candidateResultLimit:r,complexityResultLimit:i,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${sv} symbols and reported their top ${av} findings. Enable full mode for unbounded candidate counts.`]}}function H2(e,t){t.releaseCachesBetweenPhases&&(yd(e),Pm())}function fe(e,t,n,r){U2(n);try{return r()}finally{H2(e,t)}}function U2(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function W2(e,t){return t.filter(n=>!Ee(e,n.relativePath)&&!de(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function G2(e,t){return t.filter(n=>!Ee(e,n.relativePath)&&!de(e,n.symbol,n.relativePath))}function dc(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 uv(e,t){return{...dc(e),scoreCount:Lm(e.reduce((r,i)=>r+t(i),0))}}function z2(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 Fm(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 dv(e,t){return{...Fm(e),scoreCount:Lm(e.reduce((r,i)=>r+t(i),0))}}function V2(e){let t=e.sharedHooks.length>0,n=mv({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:fv(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function q2(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=mv({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:fv(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function mv(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!gv.has(pv(t))).length+Math.min(e.functions.length,3)}function fv(e,t,n){let r=[...e,...t,...n].map(pv);return r.length>0&&r.every(i=>gv.has(i))}function pv(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function K2(e){return e.actionTier==="signal"?.25:1}function J2(e){return e.actionTier==="signal"?.25:1}function lv(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 Lm(e){return Math.round(e*100)/100}var gv=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 Y2(e,t,n,r={}){let i=Ed(e,t,n,r);return i?{symbolA:i.symbolA,symbolB:i.symbolB,similarity:i.similarity,sharedCallees:i.sharedEvidence,uniqueToA:i.uniqueToA,uniqueToB:i.uniqueToB,consolidationStrategy:i.consolidationStrategy}:null}function X2(e,t={}){let{scope:n,limit:r}=t,i=new _(e),o=oJ([...Q2(e,n),...tJ(e,i,n)]);return sJ(o),r?o.slice(0,r):o}function Q2(e,t){let n=[];for(let r of Z2(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||od(e,r.barrel_path)||P(e,r.barrel_path)&&hs(e,r.barrel_path).length===0)continue;let i=eJ(e,r),o=i?.barrel_consumers??0,s=i?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:I(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s,...yv(e,r.barrel_path)})}return n}function Z2(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT
|
|
854
|
+
WHERE relative_path IN (${r})`,...n);return new Map(i.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function ZK(e,t,n){let r=new Set,i=new Map;for(let o of t){if(n.get(o.relativePath)!=="clojure")continue;let s=i.get(o.relativePath);s||(s=new Set((G(e,o.relativePath)?.callables??[]).map(a=>`${a.name}:${a.startLine}`)),i.set(o.relativePath,s)),s.has(`${o.leaf}:${o.startLine}`)&&r.add(o.symbolId)}return r}function Bt(e,t){return`${e}\0${t}`}function bfe(e,t,n,r,i,o={}){let s=new Map(e.map(l=>[Bt(l.check,l.findingId),l])),a=[],c=(l,u)=>{let d=n.get(l.findingId),m=u==="resolved"?o.verifiedAgainstByFinding?.get(Bt(l.check,l.findingId)):void 0;a.push({ts:i,check:l.check,findingId:l.findingId,event:u,commit:r,...o.comparisonBaseCommit?{comparisonBaseCommit:o.comparisonBaseCommit}:{},...m?{verifiedAgainstCommit:m}:{},...d?{symbol:d}:{}})};for(let l of t){let u=s.get(Bt(l.check,l.findingId));if(!u){c(l,"caught"),l.outcome==="suppressed"&&c(l,"suppressed");continue}u.outcome!==l.outcome&&(l.outcome==="resolved"?c(l,"resolved"):l.outcome==="suppressed"?c(l,"suppressed"):l.outcome==="still-open"&&c(l,"reopened"))}return a}function Sfe(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n?.event==="caught"||n?.event==="reopened")return n}}function e2(e,t,n,r,i=new Set){let o=new Map(e.map(c=>[Bt(c.check,c.findingId),c])),s=new Set(t.map(c=>Bt(c.check,c.findingId))),a=new Set(n);for(let c of t){let l=Bt(c.check,c.findingId),u=o.get(l),d=c.suppressed?"suppressed":"still-open";u?o.set(l,{...u,lastSeen:r,timesShown:u.timesShown+1,outcome:d}):o.set(l,{check:c.check,findingId:c.findingId,firstSeen:r,lastSeen:r,timesShown:1,outcome:d})}for(let c of e){if(!a.has(c.check))continue;let l=Bt(c.check,c.findingId);s.has(l)||i.has(l)||c.outcome!=="resolved"&&o.set(l,{...c,outcome:"resolved"})}return[...o.values()]}function km(e,t){let n=new Map;for(let i of e){let o=n.get(i.check)??[];o.push(i),n.set(i.check,o)}let r=[];for(let[i,o]of n){let s=o.filter(d=>d.outcome==="resolved").length,a=o.filter(d=>d.outcome==="suppressed").length,c=o.filter(d=>d.outcome==="still-open").length,l=o.length,u=o.filter(d=>d.outcome==="still-open").sort((d,m)=>d.firstSeen-m.firstSeen)[0];r.push({check:i,seen:l,resolved:s,suppressed:a,stillOpen:c,resolutionRate:l>0?s/l:0,suppressionRate:l>0?a/l:0,oldestOpenAgeDays:u?Math.floor((t-u.firstSeen)/tv):null})}return r.sort((i,o)=>i.check.localeCompare(o.check))}var tv=864e5,t2=50,n2=.1,r2=10;function i2(e,t,n){return e.filter(r=>r.check===t).sort((r,i)=>i.firstSeen-r.firstSeen).slice(0,n)}function vfe(e,t,n){if(t.length===0)return null;let r=new Map(e.map(s=>[Bt(s.check,s.findingId),s])),i=t.map(s=>r.get(Bt(s.check,s.findingId))).filter(s=>s!==void 0&&s.timesShown>1);if(i.length===0)return null;let o=Math.max(...i.map(s=>Math.floor((n-s.firstSeen)/tv)));return`${t.length} finding(s), ${i.length} shown before and unresolved (oldest: ${o} day(s))`}function Ife(e,t){let n=[];for(let r of[...new Set(t)].sort()){let i=i2(e,r,t2);i.length<r2||i.filter(a=>a.outcome==="resolved").length/i.length>=n2||n.push(`(the ${r} check's findings are rarely acted on in this repo \u2014 consider suppressing with reasons or tuning its config)`)}return n}function cc(e){return nf(e).map(t=>({check:t.check,findingId:t.findingId,firstSeen:t.firstSeen,lastSeen:t.lastSeen,timesShown:t.timesShown,outcome:t.outcome}))}function wfe(e,t,n,r=Date.now(),i=new Set){let o=cc(e),s=e2(o,t,n,r,i);return rf(e,s),s}function ln(e){return e.scoreCount??e.count}function iv(e){let t=c2(e),{breakdown:n,pressure:r}=l2(e),i=rv(n,"risk"),o=rv(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,duplicateBodyGroups:e.duplicateBodies.count,duplicateBodyLoc:e.duplicateBodies.loc,twinDriftGroups:e.twinDrift.count,twinDriftLoc:e.twinDrift.loc,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:ln(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:ln(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:ln(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,coverageContractViolations:e.coverageContracts.count},axes:o2(e),validation:a2(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0,detectorPrecision:[]}}function o2(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:s2(e),evidenceQuality:{graphFindings:e.dead.count+e.isolated.count+e.realCycleCount,heuristicFindings:e.similarCount+e.duplicateBodies.count+e.twinDrift.count+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 s2(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:$t(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function a2(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],twinDrift:e.twinDrift.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?$t(i/r.size):0,c=s>0?$t(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let f=0;for(let g of m)f+=t[g]?.fixChanges??0;let p=$t(f/m.size);l[u]={flaggedFiles:m.size,fixDensity:p,lift:c>0?$t(p/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?$t(a/c):null,byCategory:l,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function $t(e){return Math.round(e*100)/100}function ov(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function lc(e,t="existing shared infrastructure discount"){let n=ln(e);return Math.abs(n-e.count)<.01?"":` (${ov(n)} score-weighted after ${t})`}function Ao(e,t){let n=ln(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${ov(n)} score-weighted)`}function c2(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",description:`${e.dead.count} indexed symbols with no visible repository references \u2014 review runtime/framework roots and the capability disclosure, then verify any deletion with cleanup-plan --verify`,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} indexed dependency cycle(s) \u2014 inspect ownership and runtime order before choosing whether or how to break them`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",description:`${e.similarCount} pairs share disclosed call or source-token evidence beyond imports \u2014 review domain identity before considering consolidation`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.duplicateBodies.count>0&&t.push({category:"Duplicate function bodies",evidence:"heuristic",description:`${e.duplicateBodies.count} exact small-body group(s) across files \u2014 consolidate only when the domain concept matches`,effort:"low",impact:"medium",count:e.duplicateBodies.count,locRecoverable:e.duplicateBodies.loc}),e.twinDrift.count>0&&t.push({category:"Drifted twin implementations",evidence:"heuristic",description:`${e.twinDrift.count} same-name (or near-name) function group(s) across files with diverged or identical bodies \u2014 determine whether they represent the same concept before acting`,effort:"medium",impact:"medium",count:e.twinDrift.count,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 review whether local product intent justifies reuse`,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${lc(e.reactHookCandidates)} \u2014 review whether a common hook would preserve ownership and lifecycle semantics`,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 review whether local product intent justifies reuse`,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${lc(e.vueComposableCandidates)} \u2014 review whether a common composable would preserve ownership and lifecycle semantics`,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${lc(e.wrappers,"boundary-evidence discount")} \u2014 inspect whether each is indirection or an intentional API, framework, or ownership boundary`,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 literally forward to one callee \u2014 inspect whether each is unnecessary indirection or an intentional boundary`,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 review public, runtime-registration, and ownership evidence before removing, moving, or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.architectureViolations>0&&i.push(`${e.drift.architectureViolations} declared architecture violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${i.join(", ")} \u2014 repair direct dependency-rule breaks; inspect boundary signals with \`drift --architecture\``,effort:e.drift.architectureViolations>0?"medium":"low",impact:e.drift.architectureViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(e.coverageContracts.count>0&&t.push({category:"Coverage contract drift",evidence:"graph-fact",description:`${e.coverageContracts.count} configured coverage contract(s) drifted from their ground-truth source (enumeration rot) \u2014 run \`scip-query diff-gate\` or \`scip-query health --json\` for the missing/extra keys`,effort:"low",impact:"medium",count:e.coverageContracts.count,locRecoverable:0}),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`+lc({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(i?` (e.g. ${i.fileA} \u2194 ${i.fileB})`:"")+" \u2014 inspect whether a shared concept, generated artifact, or coordinated contract explains the history",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 nv={"dead-code":"risk",isolated:"risk",cycles:"risk",complexity:"risk","hidden-coupling":"risk","cycles-pressure":"risk","complexity-pressure":"risk","hidden-coupling-pressure":"risk",similar:"hygiene","duplicate-bodies":"hygiene","twin-drift":"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","duplicate-bodies-pressure":"hygiene","twin-drift-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 rv(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 l2(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(R,E,D)=>{E>0&&r.push({axis:R,points:E,detail:D,kind:nv[R]??"hygiene"})},s=(R,E,D,k,L,ne,X)=>{let F=Math.max(k,1);if(D<=F)return;let ae=D/F,Z=Math.min(L,Math.ceil(Math.log2(ae)*ne));if(Z<=0)return;let un=nv[R]??"hygiene";i.push({axis:R,category:E,kind:un,count:D,threshold:$t(F),ratio:$t(ae),extraPenalty:Z}),o(R,Z,`${D} ${X} exceed pressure threshold ${$t(F)} (${$t(ae)}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.duplicateBodies.count/n*1e3;o("duplicate-bodies",Math.min(10,Math.round(u*2)),`${e.duplicateBodies.count} exact duplicate small-body group(s) (${e.duplicateBodies.loc} duplicate LOC)`);let d=e.twinDrift.count/n*1e3;o("twin-drift",Math.min(10,Math.round(d*2)),`${e.twinDrift.count} drifted twin implementation group(s) (same or near-same name, diverged or identical bodies)`);let m=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(m)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let f=ln(e.reactHookCandidates),p=f/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(p)),Ao(e.reactHookCandidates,"duplicated React behavior pair(s)"));let g=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(g/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let y=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(y)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let h=ln(e.vueComposableCandidates),C=h/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(C)),Ao(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let x=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(x/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let S=ln(e.wrappers);o("wrappers",Math.min(3,S),Ao(e.wrappers,"wrapper candidate(s)"));let b=ln(e.passthroughs);o("passthroughs",Math.min(3,b),Ao(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 v=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(v*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 R=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(R/10)),Ao({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:R},"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 R=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",R,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("duplicate-bodies-pressure","Duplicate function bodies",e.duplicateBodies.count,Math.max(20,n*.005),8,4,"exact duplicate small-body group(s)"),s("twin-drift-pressure","Drifted twin implementations",e.twinDrift.count,Math.max(20,n*.005),8,4,"drifted twin implementation group(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",f,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",S,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",b,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:r,pressure:i}}import{getHeapStatistics as u2}from"v8";var d2=64*1024*1024;function Pm(){let e=globalThis.gc;if(!e)return;let t=u2();t.heap_size_limit-t.used_heap_size<d2||e()}var m2=50,f2=25e3,p2=2500,sv=2500,av=50,g2=10,uc=["overview","dead","isolated","cycles","similar","duplicate-bodies","twin-drift","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","coverage-contracts"],h2={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:C2(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:x2(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:R2(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:v2(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:w2(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:D2(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:E2(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:k2(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:P2(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:T2(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:_2(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:F2(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:I2(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:L2(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:N2(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:A2(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:B2(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:$2(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:M2(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:O2(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:j2(e,n)})};function Tm(e,t,n={}){return y2(e,[t],n)[0]}function y2(e,t,n={}){return b2(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>h2[s](e,n.scope,o,r))})}function b2(e,t,n){let r=or(e),i=H2(r,t);try{return n(r,i)}finally{yd(e,{semanticProvider:!0}),Pm()}}function _m(e){return iv(S2(e))}function S2(e){let t=ge(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:ge(e,"dead").dead,isolated:ge(e,"isolated").isolated,realCycleCount:ge(e,"cycles").realCycleCount,similarCount:ge(e,"similar").similarCount,duplicateBodies:ge(e,"duplicate-bodies").duplicateBodies,twinDrift:ge(e,"twin-drift").twinDrift,reactComponentDuplicates:ge(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:ge(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:ge(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:ge(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:ge(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:ge(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:ge(e,"extract-candidates").extractCount,wrappers:ge(e,"wrapper-candidates").wrappers,passthroughs:ge(e,"passthrough-candidates").passthroughs,stale:ge(e,"stale-abstractions").stale,drift:ge(e,"drift").drift,complexity:ge(e,"complexity-hotspots").complexity,gitEvidence:cv(e,"git-evidence")?.gitEvidence??null,suppressions:cv(e,"suppressions")?.suppressions??null,coverageContracts:ge(e,"coverage-contracts").coverageContracts}}function cv(e,t){return e.find(n=>n.phase===t)}function ge(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function C2(e,t,n){return fe(e,n,"dead",()=>{let r=sr(e,{scope:t,...me.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return dc(G2(e,r.symbols))})}function x2(e,t,n){return fe(e,n,"isolated",()=>{let r=uo(e,{scope:t,...me.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return dc(z2(e,r))})}function R2(e,t,n){return fe(e,n,"cycles",()=>lo(e,{scope:t}).filter(i=>i.kind==="real").length)}function v2(e,t,n){let r=fe(e,n,"similar",()=>kd(e,{scope:t,...me.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(r,n.candidateResultLimit)}function I2(e,t,n){return fe(e,n,"extract-candidates",()=>yo(e,{scope:t,...me.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function w2(e,t,n){return fe(e,n,"duplicate-bodies",()=>{let r=Io(e,{scope:t,...me.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=new Set,o=0;for(let s of r)for(let a of s.functions.slice(1))i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i]}})}function D2(e,t,n){return fe(e,n,"twin-drift",()=>{let r=ni(e,{scope:t,...me.twinDrift,scanLimit:n.candidateScanLimit}).filter(s=>s.relationship==="divergent"||s.relationship==="identical"),i=new Set,o=0;for(let s of r)for(let a of s.members)i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i].sort()}})}function E2(e,t,n){return fe(e,n,"react-component-duplicates",()=>{let r=fo(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Fm(r)})}function k2(e,t,n){return fe(e,n,"react-hook-candidates",()=>{let r=po(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return dv(r,q2)})}function P2(e,t,n){return fe(e,n,"react-large-component-pressure",()=>{let r=Pd(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return V2(r)})}function T2(e,t,n){return fe(e,n,"vue-component-duplicates",()=>{let r=go(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Fm(r)})}function _2(e,t,n){return fe(e,n,"vue-composable-candidates",()=>{let r=ho(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return dv(r,K2)})}function F2(e,t,n){return fe(e,n,"vue-large-view-pressure",()=>{let r=Td(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return dc(r)})}function L2(e,t,n){return fe(e,n,"wrapper-candidates",()=>{let r=_o(e,{scope:t,...me.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return uv(r,J2)})}function N2(e,t,n){return fe(e,n,"passthrough-candidates",()=>{let r=ko(e,{scope:t,...me.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return uv(r,Y2)})}function A2(e,t,n){return fe(e,n,"stale-abstractions",()=>{let r=To(e,{scope:t,...me.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),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 M2(e,t){return fe(e,t,"git-evidence",()=>{let n=ze(e,{historyMode:t.gitHistoryMode}),r=n.fileChurn();if(!r)return null;let i=n.commitHistory(),o=So(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[a,c]of r)s[a]={changes:c.changes,fixChanges:c.fixChanges};return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:o.findings.length,scoreCount:Lm(o.findings.reduce((a,c)=>a+lv(c),0)),top:o.findings.slice(0,5).map(a=>({fileA:a.fileA,fileB:a.fileB,together:a.together,confidence:a.confidence,focusedTogether:a.focusedTogether,broadTogether:a.broadTogether,broadCommitRatio:a.broadCommitRatio,lastTogetherAt:a.lastTogetherAt,recentTogether:a.recentTogether,commitScope:a.commitScope,recency:a.recency,scoreWeight:lv(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:i?.commits.length??0}})}function O2(e,t){return fe(e,t,"suppressions",()=>{let n=sc(e);return{total:n.total,byCategory:{...n.byCategory}}})}function j2(e,t){return fe(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],i=aR(e,n).filter(o=>o.status!=="ok");return{count:i.length,loc:0,files:[...new Set(i.map(o=>o.file))].sort()}})}function B2(e,t,n){return fe(e,n,"drift",()=>{let r=Eo(e,{scope:t,...me.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY,semantic:n.semantic}),i=r.results.filter(a=>a.kind!=="pattern-deviation"),o=i.filter(a=>a.actionTier==="direct").length,s=i.length-o;return{count:i.length,unusedImports:r.unusedImports,architectureViolations:r.architectureViolations,layerViolations:r.layerViolations,direct:o,signal:s}})}function $2(e,t,n){return fe(e,n,"complexity-hotspots",()=>{let r=Em(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.filter(i=>i.score>m2).length}})}function H2(e,t){let n=e.symbols>=f2||e.documents>=p2,r=t?Number.POSITIVE_INFINITY:av,i=t?Number.POSITIVE_INFINITY:g2;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:r,complexityResultLimit:i,semantic:!0,gitHistoryMode:t?"full":"bounded",releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:sv,candidateResultLimit:r,complexityResultLimit:i,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${sv} symbols and reported their top ${av} findings. Enable full mode for unbounded candidate counts.`]}}function U2(e,t){t.releaseCachesBetweenPhases&&(yd(e),Pm())}function fe(e,t,n,r){W2(n);try{return r()}finally{U2(e,t)}}function W2(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function G2(e,t){return t.filter(n=>!Ee(e,n.relativePath)&&!de(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function z2(e,t){return t.filter(n=>!Ee(e,n.relativePath)&&!de(e,n.symbol,n.relativePath))}function dc(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 uv(e,t){return{...dc(e),scoreCount:Lm(e.reduce((r,i)=>r+t(i),0))}}function V2(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 Fm(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 dv(e,t){return{...Fm(e),scoreCount:Lm(e.reduce((r,i)=>r+t(i),0))}}function q2(e){let t=e.sharedHooks.length>0,n=mv({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:fv(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function K2(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=mv({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:fv(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function mv(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!gv.has(pv(t))).length+Math.min(e.functions.length,3)}function fv(e,t,n){let r=[...e,...t,...n].map(pv);return r.length>0&&r.every(i=>gv.has(i))}function pv(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function J2(e){return e.actionTier==="signal"?.25:1}function Y2(e){return e.actionTier==="signal"?.25:1}function lv(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 Lm(e){return Math.round(e*100)/100}var gv=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 X2(e,t,n,r={}){let i=Ed(e,t,n,r);return i?{symbolA:i.symbolA,symbolB:i.symbolB,similarity:i.similarity,sharedCallees:i.sharedEvidence,uniqueToA:i.uniqueToA,uniqueToB:i.uniqueToB,consolidationStrategy:i.consolidationStrategy}:null}function Q2(e,t={}){let{scope:n,limit:r}=t,i=new _(e),o=sJ([...Z2(e,n),...nJ(e,i,n)]);return aJ(o),r?o.slice(0,r):o}function Z2(e,t){let n=[];for(let r of eJ(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||od(e,r.barrel_path)||P(e,r.barrel_path)&&hs(e,r.barrel_path).length===0)continue;let i=tJ(e,r),o=i?.barrel_consumers??0,s=i?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:I(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s,...yv(e,r.barrel_path)})}return n}function eJ(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT
|
|
855
855
|
barrel_d.id AS barrel_doc_id,
|
|
856
856
|
barrel_d.relative_path AS barrel_path,
|
|
857
857
|
gs.id AS symbol_id,
|
|
@@ -881,7 +881,7 @@ describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}'
|
|
|
881
881
|
-- Only function-level symbols (ending with ().), not module-level
|
|
882
882
|
AND gs.symbol LIKE '%().'
|
|
883
883
|
${n}
|
|
884
|
-
ORDER BY barrel_d.relative_path, gs.symbol`,...r)}function
|
|
884
|
+
ORDER BY barrel_d.relative_path, gs.symbol`,...r)}function tJ(e,t){return e.get(`SELECT
|
|
885
885
|
SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
|
|
886
886
|
SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
|
|
887
887
|
FROM (
|
|
@@ -910,18 +910,18 @@ describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}'
|
|
|
910
910
|
AND consumer_d.id != ?
|
|
911
911
|
${e.pathExclusionsFor("consumer_d")}
|
|
912
912
|
GROUP BY consumer_d.id
|
|
913
|
-
)`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function tJ(e,t,n){let r=[];for(let i of nJ(e,n))bv(e,i,i)>0||r.push(...rJ(e,t,i));return r}function nJ(e,t){return N(e,{scope:t,includeIgnored:!1}).filter(n=>hs(e,n).length>0||qt(e,n).length>0)}function rJ(e,t,n){let r=hs(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>hv(e,t,n,o.sourcePath,[iJ(o.specifier)])),i=qt(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>hv(e,t,n,o.sourcePath,o.kind==="named"&&o.names.length>0?o.names:[o.kind==="star"?`* from ${o.sourcePath}`:`* namespace from ${o.sourcePath}`]));return[...r,...i]}function hv(e,t,n,r,i){let o=t.definitionsForFile(r);return i.map(s=>{let a=o.find(c=>c.leaf===s);return{barrelFile:n,symbol:a?.symbol??`source-reexport:${n}:${s}`,shortName:a?I(a.symbol):s,originalFile:r,barrelConsumers:0,directConsumers:bv(e,r,n),...yv(e,n)}})}function iJ(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function yv(e,t){return ir(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 bv(e,t,n){let r=new Set;for(let i of N(e,{includeIgnored:!1}))if(i!==n)for(let o of re(e,i))o.sourcePath===t&&r.add(i);return r.size}function oJ(e){let t=new Set,n=[];for(let r of e){let i=`${r.barrelFile}|${r.symbol}|${r.originalFile}`;t.has(i)||(t.add(i),n.push(r))}return n}function sJ(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function aJ(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new _(e),s=cJ(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=lJ(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:Sv(),callees:Sv()},l=[],u=0,d=a==="semantic"?ra(e,s):new Map,m=a==="source"?mJ(e,o,s):null;for(let f of s){let p=mc(f,a==="semantic"?na(e,f).map(S=>S.file):[...m?.referencesBySymbolId.get(f.symbolId)??[]]),g=mc(f,a==="semantic"?(d.get(f.symbolId)??[]).map(S=>S.file):[...m?.calleesBySymbolId.get(f.symbolId)??[]]);u+=1;let y=mc(f,Dt(e,f,{semanticEvidence:H}).map(S=>S.file)),h=mc(f,(o.calleeMap([f],{semantic:!1}).get(f.symbolId)??[]).map(S=>S.file)),C=Nm(a,"references"),x=Nm(a,"callees");Cv(c.references,f,"references",y,p,C,l),Cv(c.callees,f,"callees",h,g,x,l)}return l.sort((f,p)=>p.cheapOnly.length+p.oracleOnly.length-(f.cheapOnly.length+f.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?Mm(u/s.length):0,oracleKind:a,scores:["references","callees"].map(f=>dJ(f,c[f],a)),topDisagreements:l.slice(0,i)}}function Sv(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0}}function cJ(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let r=n.length/t,i=[];for(let o=0;o<t;o++)i.push(n[Math.floor(o*r)]);return i}function lJ(e,t){let n=t[0];if(!n)return null;if(Am(e,n))return"source";try{if(We(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(r=>Am(e,r))?"source":null}function mc(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function Cv(e,t,n,r,i,o,s){if(!o&&i.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=r.size,e.oracleTotal+=i.size;let a=[],c=[];for(let l of r)i.has(l)?e.agreed+=1:a.push(l);for(let l of i)r.has(l)||c.push(l);(a.length>0||c.length>0)&&s.push({symbol:I(t.symbol),question:n,cheapOnly:a,oracleOnly:c})}var uJ={references:!0,callees:!1};function dJ(e,t,n){let r=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed,o=Nm(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?Mm(t.agreed/t.cheapTotal):null,recall:Mm(r),unverified:i,skippedOraclePartial:t.skippedOraclePartial}}function Nm(e,t){return e==="semantic"?uJ[t]:!1}function Am(e,t){return M(t.relativePath)==="clojure"&&G(e,t.relativePath)!==null}function mJ(e,t,n){let r=new Map,i=new Map,o=n.filter(c=>Am(e,c)),s=new Map;for(let c of o){let l=s.get(c.leaf)??[];l.push(c),s.set(c.leaf,l)}for(let c of t.sourceFiles()){if(M(c)!=="clojure")continue;let l=G(e,c);if(l)for(let u of l.fileIdentifiers)for(let d of s.get(u)??[])xv(r,d.symbolId,c)}let a=new Map;for(let c of t.scopedDefinitions()){if(M(c.relativePath)!=="clojure")continue;let l=a.get(c.leaf)??[];l.push(c),a.set(c.leaf,l)}for(let c of o){let l=G(e,c.relativePath);if(l){for(let u of l.callSites)if(!(u.line<c.startLine||u.line>c.endLine))for(let d of a.get(u.calleeLeaf)??[])xv(i,c.symbolId,d.relativePath)}}return{referencesBySymbolId:r,calleesBySymbolId:i}}function xv(e,t,n){let r=e.get(t);if(r){r.add(n);return}e.set(t,new Set([n]))}function Mm(e){return Math.round(e*1e3)/1e3}var fJ=new Set(Ft());function pJ(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=yJ(e,gJ(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),l=SJ(c);return i?l.slice(0,i):l}function gJ(e,t){let n=xe(e,{scope:t.scope}).filter(r=>hJ(r)&&!e.isIgnored(r.relativePath)).filter(r=>O(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>O(i)-O(r)||r.relativePath.localeCompare(i.relativePath)),se(n,t.scanLimit)}function hJ(e){return!e.isFunctionLike||Ie(e.symbol)?!1:e.kind===null||fJ.has(e.kind)}function yJ(e,t,n){let r=[];for(let s of t){let a=xJ(e,s,n);a&&r.push({signature:a,definition:s,fn:bJ(s)})}let i=new Map;for(let s of r)i.set(s.signature,(i.get(s.signature)??0)+1);let o=new Map;for(let s of r){let a=CJ(s.fn.loc),c=(i.get(s.signature)??0)>n.maxShapeFrequency,l=c?am(e,s.definition):null;if(c&&!l)continue;let u=c?`${s.signature}\0body\0${l}`:`${s.signature}\0band\0${a}`,d=o.get(u)??{signature:s.signature,locBand:a,exactBody:c,functions:[]};d.functions.push(s.fn),o.set(u,d)}return[...o.values()]}function bJ(e){return{symbol:e.symbol,shortName:I(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:O(e)}}function SJ(e){let t=[];for(let n of e)n.functions.length>=2&&t.push(n);return t.sort((n,r)=>{let i=r.functions.length-n.functions.length;if(i!==0)return i;let o=n.functions.reduce((a,c)=>a+c.loc,0);return r.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function CJ(e){return e<=5?"<=5":e<=20?"6-20":">20"}function xJ(e,t,n){if(n.semantic){let o=Sy(e,t);if(o)return o}let r=RJ(t.documentation),i=r?wJ(r):null;return i||DJ(vJ(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function RJ(e){return Kt(Jt(e))}function vJ(e,t,n,r,i){let o=P(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=kJ(s,n,r,i);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,IJ(u)))return u}if(u&&u.includes("("))return u}return null}function IJ(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||Ci(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function wJ(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 DJ(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),r=n.indexOf("(");if(r===-1)return null;let i=n.slice(0,r),s=new RegExp(`\\b${$(t)}\\b`,"i").exec(i);s&&typeof s.index=="number"&&(i=i.slice(0,s.index)),i=i.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=EJ(n.slice(r)).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=`${i?`${i} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function EJ(e){let t=0,n=0,r=0,i=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==="[")r+=1;else if(c==="]")r=Math.max(0,r-1);else if(c==="<")i+=1;else if(c===">")i=Math.max(0,i-1);else if(c==="{"){if(t===0&&r===0&&i===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&&r===0&&i===0)return e.slice(0,a)}return e}function kJ(e,t,n,r){let i=$(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${i}\\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}import{spawn as TJ,spawnSync as Wge}from"child_process";var oi=class extends Error{constructor(n,r){super(`${n} timed out after ${r}ms.`);this.label=n;this.timeoutMs=r}label;timeoutMs;timedOut=!0};function Rv(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function fc(e){return new Promise((t,n)=>{let r=e.maxBuffer??10485760,i=TJ(process.execPath,[...process.execArgv,e.cliPath,e.command,...e.args??[]],{cwd:process.cwd(),env:e.env??process.env,stdio:["ignore","pipe","pipe"]}),o=[],s=[],a=0,c=0,l=!1,u=e.timeoutMs&&e.timeoutMs>0?setTimeout(()=>d(new oi(e.label,e.timeoutMs)),e.timeoutMs):null,d=m=>{l||(l=!0,u&&clearTimeout(u),i.kill(),n(m))};i.stdout.on("data",m=>{if(a+=m.length,a>r){d(new Error(`${e.label} exceeded stdout buffer limit (${r} bytes).`));return}o.push(m)}),i.stderr.on("data",m=>{if(c+=m.length,c>r){d(new Error(`${e.label} exceeded stderr buffer limit (${r} bytes).`));return}s.push(m)}),i.on("error",d),i.on("close",m=>{if(l)return;l=!0,u&&clearTimeout(u);let f=Buffer.concat(s).toString("utf8").trim();if(m!==0){n(new Error(`${e.label} failed${f?`:
|
|
914
|
-
${f}`:""}`));return}try{t(JSON.parse(Buffer.concat(o).toString("utf8")))}catch(p){n(new Error(`${e.label} returned invalid JSON: ${p instanceof Error?p.message:p}`))}})})}async function Om(e,t,n){let r=new Array(e.length),i=0;async function o(){for(;i<e.length;){let s=i++;r[s]=await n(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),r}function vv(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=t.find(a=>a.has(i));if(!o){n.add(i),r.push([i]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),r.push(s)}return r}import{spawnSync as
|
|
915
|
-
`)}function
|
|
913
|
+
)`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function nJ(e,t,n){let r=[];for(let i of rJ(e,n))bv(e,i,i)>0||r.push(...iJ(e,t,i));return r}function rJ(e,t){return N(e,{scope:t,includeIgnored:!1}).filter(n=>hs(e,n).length>0||Kt(e,n).length>0)}function iJ(e,t,n){let r=hs(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>hv(e,t,n,o.sourcePath,[oJ(o.specifier)])),i=Kt(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>hv(e,t,n,o.sourcePath,o.kind==="named"&&o.names.length>0?o.names:[o.kind==="star"?`* from ${o.sourcePath}`:`* namespace from ${o.sourcePath}`]));return[...r,...i]}function hv(e,t,n,r,i){let o=t.definitionsForFile(r);return i.map(s=>{let a=o.find(c=>c.leaf===s);return{barrelFile:n,symbol:a?.symbol??`source-reexport:${n}:${s}`,shortName:a?I(a.symbol):s,originalFile:r,barrelConsumers:0,directConsumers:bv(e,r,n),...yv(e,n)}})}function oJ(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function yv(e,t){return ir(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 bv(e,t,n){let r=new Set;for(let i of N(e,{includeIgnored:!1}))if(i!==n)for(let o of re(e,i))o.sourcePath===t&&r.add(i);return r.size}function sJ(e){let t=new Set,n=[];for(let r of e){let i=`${r.barrelFile}|${r.symbol}|${r.originalFile}`;t.has(i)||(t.add(i),n.push(r))}return n}function aJ(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function cJ(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new _(e),s=lJ(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=uJ(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:Sv(),callees:Sv()},l=[],u=0,d=a==="semantic"?ra(e,s):new Map,m=a==="source"?fJ(e,o,s):null;for(let f of s){let p=mc(f,a==="semantic"?na(e,f).map(S=>S.file):[...m?.referencesBySymbolId.get(f.symbolId)??[]]),g=mc(f,a==="semantic"?(d.get(f.symbolId)??[]).map(S=>S.file):[...m?.calleesBySymbolId.get(f.symbolId)??[]]);u+=1;let y=mc(f,Et(e,f,{semanticEvidence:H}).map(S=>S.file)),h=mc(f,(o.calleeMap([f],{semantic:!1}).get(f.symbolId)??[]).map(S=>S.file)),C=Nm(a,"references"),x=Nm(a,"callees");Cv(c.references,f,"references",y,p,C,l),Cv(c.callees,f,"callees",h,g,x,l)}return l.sort((f,p)=>p.cheapOnly.length+p.oracleOnly.length-(f.cheapOnly.length+f.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?Mm(u/s.length):0,oracleKind:a,scores:["references","callees"].map(f=>mJ(f,c[f],a)),topDisagreements:l.slice(0,i)}}function Sv(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0}}function lJ(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let r=n.length/t,i=[];for(let o=0;o<t;o++)i.push(n[Math.floor(o*r)]);return i}function uJ(e,t){let n=t[0];if(!n)return null;if(Am(e,n))return"source";try{if(We(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(r=>Am(e,r))?"source":null}function mc(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function Cv(e,t,n,r,i,o,s){if(!o&&i.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=r.size,e.oracleTotal+=i.size;let a=[],c=[];for(let l of r)i.has(l)?e.agreed+=1:a.push(l);for(let l of i)r.has(l)||c.push(l);(a.length>0||c.length>0)&&s.push({symbol:I(t.symbol),question:n,cheapOnly:a,oracleOnly:c})}var dJ={references:!0,callees:!1};function mJ(e,t,n){let r=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed,o=Nm(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?Mm(t.agreed/t.cheapTotal):null,recall:Mm(r),unverified:i,skippedOraclePartial:t.skippedOraclePartial}}function Nm(e,t){return e==="semantic"?dJ[t]:!1}function Am(e,t){return M(t.relativePath)==="clojure"&&G(e,t.relativePath)!==null}function fJ(e,t,n){let r=new Map,i=new Map,o=n.filter(c=>Am(e,c)),s=new Map;for(let c of o){let l=s.get(c.leaf)??[];l.push(c),s.set(c.leaf,l)}for(let c of t.sourceFiles()){if(M(c)!=="clojure")continue;let l=G(e,c);if(l)for(let u of l.fileIdentifiers)for(let d of s.get(u)??[])xv(r,d.symbolId,c)}let a=new Map;for(let c of t.scopedDefinitions()){if(M(c.relativePath)!=="clojure")continue;let l=a.get(c.leaf)??[];l.push(c),a.set(c.leaf,l)}for(let c of o){let l=G(e,c.relativePath);if(l){for(let u of l.callSites)if(!(u.line<c.startLine||u.line>c.endLine))for(let d of a.get(u.calleeLeaf)??[])xv(i,c.symbolId,d.relativePath)}}return{referencesBySymbolId:r,calleesBySymbolId:i}}function xv(e,t,n){let r=e.get(t);if(r){r.add(n);return}e.set(t,new Set([n]))}function Mm(e){return Math.round(e*1e3)/1e3}var pJ=new Set(Lt());function gJ(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=bJ(e,hJ(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),l=CJ(c);return i?l.slice(0,i):l}function hJ(e,t){let n=xe(e,{scope:t.scope}).filter(r=>yJ(r)&&!e.isIgnored(r.relativePath)).filter(r=>O(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>O(i)-O(r)||r.relativePath.localeCompare(i.relativePath)),se(n,t.scanLimit)}function yJ(e){return!e.isFunctionLike||Ie(e.symbol)?!1:e.kind===null||pJ.has(e.kind)}function bJ(e,t,n){let r=[];for(let s of t){let a=RJ(e,s,n);a&&r.push({signature:a,definition:s,fn:SJ(s)})}let i=new Map;for(let s of r)i.set(s.signature,(i.get(s.signature)??0)+1);let o=new Map;for(let s of r){let a=xJ(s.fn.loc),c=(i.get(s.signature)??0)>n.maxShapeFrequency,l=c?am(e,s.definition):null;if(c&&!l)continue;let u=c?`${s.signature}\0body\0${l}`:`${s.signature}\0band\0${a}`,d=o.get(u)??{signature:s.signature,locBand:a,exactBody:c,functions:[]};d.functions.push(s.fn),o.set(u,d)}return[...o.values()]}function SJ(e){return{symbol:e.symbol,shortName:I(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:O(e)}}function CJ(e){let t=[];for(let n of e)n.functions.length>=2&&t.push(n);return t.sort((n,r)=>{let i=r.functions.length-n.functions.length;if(i!==0)return i;let o=n.functions.reduce((a,c)=>a+c.loc,0);return r.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function xJ(e){return e<=5?"<=5":e<=20?"6-20":">20"}function RJ(e,t,n){if(n.semantic){let o=Sy(e,t);if(o)return o}let r=vJ(t.documentation),i=r?DJ(r):null;return i||EJ(IJ(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function vJ(e){return Jt(Yt(e))}function IJ(e,t,n,r,i){let o=P(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=PJ(s,n,r,i);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,wJ(u)))return u}if(u&&u.includes("("))return u}return null}function wJ(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||Ci(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function DJ(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 EJ(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),r=n.indexOf("(");if(r===-1)return null;let i=n.slice(0,r),s=new RegExp(`\\b${$(t)}\\b`,"i").exec(i);s&&typeof s.index=="number"&&(i=i.slice(0,s.index)),i=i.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=kJ(n.slice(r)).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=`${i?`${i} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function kJ(e){let t=0,n=0,r=0,i=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==="[")r+=1;else if(c==="]")r=Math.max(0,r-1);else if(c==="<")i+=1;else if(c===">")i=Math.max(0,i-1);else if(c==="{"){if(t===0&&r===0&&i===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&&r===0&&i===0)return e.slice(0,a)}return e}function PJ(e,t,n,r){let i=$(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${i}\\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}import{spawn as _J,spawnSync as Gge}from"child_process";var oi=class extends Error{constructor(n,r){super(`${n} timed out after ${r}ms.`);this.label=n;this.timeoutMs=r}label;timeoutMs;timedOut=!0};function Rv(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function fc(e){return new Promise((t,n)=>{let r=e.maxBuffer??10485760,i=_J(process.execPath,[...process.execArgv,e.cliPath,e.command,...e.args??[]],{cwd:process.cwd(),env:e.env??process.env,stdio:["ignore","pipe","pipe"]}),o=[],s=[],a=0,c=0,l=!1,u=e.timeoutMs&&e.timeoutMs>0?setTimeout(()=>d(new oi(e.label,e.timeoutMs)),e.timeoutMs):null,d=m=>{l||(l=!0,u&&clearTimeout(u),i.kill(),n(m))};i.stdout.on("data",m=>{if(a+=m.length,a>r){d(new Error(`${e.label} exceeded stdout buffer limit (${r} bytes).`));return}o.push(m)}),i.stderr.on("data",m=>{if(c+=m.length,c>r){d(new Error(`${e.label} exceeded stderr buffer limit (${r} bytes).`));return}s.push(m)}),i.on("error",d),i.on("close",m=>{if(l)return;l=!0,u&&clearTimeout(u);let f=Buffer.concat(s).toString("utf8").trim();if(m!==0){n(new Error(`${e.label} failed${f?`:
|
|
914
|
+
${f}`:""}`));return}try{t(JSON.parse(Buffer.concat(o).toString("utf8")))}catch(p){n(new Error(`${e.label} returned invalid JSON: ${p instanceof Error?p.message:p}`))}})})}async function Om(e,t,n){let r=new Array(e.length),i=0;async function o(){for(;i<e.length;){let s=i++;r[s]=await n(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),r}function vv(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=t.find(a=>a.has(i));if(!o){n.add(i),r.push([i]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),r.push(s)}return r}import{spawnSync as FJ}from"child_process";import{existsSync as LJ,mkdirSync as NJ,readFileSync as AJ,renameSync as MJ,writeFileSync as OJ}from"fs";import{dirname as Iv,join as jJ}from"path";var pc=3,BJ="health-report-cache.json";function jm(e,t,n,r=WJ()){let i=Te(e);return i?{version:pc,projectFingerprint:i,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:r.gitHead(e.config.projectRoot)}:null}function wv(e,t,n=Pv()){let r=Ev(e),i=kv(t),o=!1;return w("health.report-cache.read",()=>{if(!n.existsSync(r))return null;try{let s=JSON.parse(n.readFileSync(r,"utf8"));return!$J(s)||s.keyHash!==i?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:i}))}function Dv(e,t,n,r=Pv()){let i=Ev(e),o={version:pc,keyHash:kv(t),key:t,writtenAt:r.nowIso(),report:n};r.mkdirSync(Iv(i),{recursive:!0});let s=`${i}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(s,JSON.stringify(o)),r.renameSync(s,i)}function Ev(e){return jJ(Iv(e.config.dbPath),BJ)}function kv(e){return he(JSON.stringify(e))}function $J(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===pc&&typeof t.keyHash=="string"&&HJ(t.key)&&typeof t.writtenAt=="string"&&UJ(t.report)}function HJ(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===pc&&typeof t.projectFingerprint=="string"&&typeof t.cliVersion=="string"&&(t.scope===null||typeof t.scope=="string")&&typeof t.full=="boolean"&&(t.phaseTimeoutMs===null||typeof t.phaseTimeoutMs=="number")&&(t.gitHead===null||typeof t.gitHead=="string")}function UJ(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.score=="number"&&typeof t.riskScore=="number"&&typeof t.hygieneScore=="number"&&typeof t.overview=="object"&&typeof t.findings=="object"&&Array.isArray(t.scoreBreakdown)&&Array.isArray(t.actions)&&Array.isArray(t.pressure)&&Array.isArray(t.topComplexity)&&Array.isArray(t.detectorPrecision)}function WJ(){return{gitHead(e){let t=FJ("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8"});return t.status===0?t.stdout.trim():null}}}function Pv(){return{existsSync:LJ,mkdirSync:NJ,readFileSync:AJ,renameSync:MJ,writeFileSync:OJ,nowIso:()=>new Date().toISOString()}}var Fv="__health-phase",zJ="__diff-impact-batch",VJ=10,qJ=4,KJ=8,JJ=25e3,YJ=2500,Bm=2500,XJ=4,QJ=12,Tv=3e4,Lv=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),Nv=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),ZJ=new Set([...Nv,"suppressions"]),eY=new Set(["similar","extract-candidates"]),gc=2,_v=jn({kind:"health-semantic-prewarm",invalidation:K("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:tY});function tY(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==gc||typeof n.definitions!="number"||!Number.isFinite(n.definitions)||typeof n.referenceCacheWrites!="number"||!Number.isFinite(n.referenceCacheWrites)||typeof n.referenceIncomplete!="number"||!Number.isFinite(n.referenceIncomplete)||typeof n.calleeRows!="number"||!Number.isFinite(n.calleeRows)||typeof n.warmedAt!="number"||!Number.isFinite(n.warmedAt)?null:{version:gc,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function Av(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
|
|
915
|
+
`)}function nY(e){let t=or(e);return t.symbols>=JJ||t.documents>=YJ}function Mv(e,t,n,r={}){return nY(e)?n?(r.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0}):(r.quiet||console.error(`Large index detected; ${t} will scan the highest-priority ${Bm} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:Bm,semantic:!1,analysisBudget:{scanLimit:Bm,semanticEnrichment:!1,reason:"large index default budget; pass --full for unbounded semantic analysis"}}):{semantic:!0}}function ghe(e){return e?`analysis budget: scanning up to ${e.scanLimit} candidate(s); semantic enrichment=${e.semanticEnrichment}; ${e.reason}`:null}var rY={env:process.env,projectFingerprint:Te,semanticEngineFingerprint:aY,readMarker:(e,t,n)=>_v.read(e,t,n),writeMarker:(e,t,n,r)=>_v.write(e,t,n,r),candidateDefinitions:(e,t)=>new _(e).scopedDefinitions(t.scope).filter(n=>De(n.relativePath)!==null),materializeReferences:(e,t,n)=>We(e).materializeReferences(t,n),materializeCallees:Cu};function iY(e,t,n=rY){if(t.full!==!0)return Nn("default-mode");if((n.env??process.env).SCIP_QUERY_HEALTH_SEMANTIC_PREWARM==="0")return Nn("disabled");let r=Nn("error");return w("health.semantic-prewarm",()=>{try{r=oY(e,t,n)}catch(i){r=Nn("error",{error:i instanceof Error?i.message:String(i)})}return r},()=>cY(r))}function oY(e,t,n){let r=n.projectFingerprint(e);if(!r)return Nn("missing-project-fingerprint");let i=sY(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,i,r);if(o&&o.referenceIncomplete===0)return Nn("cache-hit");let s=[];if(s=w("health.semantic-prewarm.candidate-definitions",()=>(s=n.candidateDefinitions(e,t),s),()=>({definitions:s.length})),s.length===0)return Nn("no-semantic-definitions");let a=0,c=w("health.semantic-prewarm.references",()=>{let m=n.materializeReferences(e,s,{prefetchCallees:!0});return a=m.cacheHits+m.cacheWrites+m.inMemoryHits,m},()=>({definitions:s.length,rows:a}));if(c.cacheHits+c.cacheWrites+c.inMemoryHits===0&&c.misses+c.unkeyed>0)return Nn("provider-unavailable",{definitions:s.length,referenceMisses:c.misses});let u=0,d=w("health.semantic-prewarm.callees",()=>{let m=n.materializeCallees(e,s);return u=m.size,m},()=>({definitions:s.length,rows:u}));return c.incomplete>0?{status:"partial",reason:"incomplete-references",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:d.size}:(w("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,i,r,{version:gc,definitions:s.length,referenceCacheWrites:c.cacheWrites,referenceIncomplete:c.incomplete,calleeRows:d.size,warmedAt:Date.now()})),{status:"warmed",reason:"cache-miss",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:d.size})}function sY(e,t){return JSON.stringify({version:gc,cliVersion:Xn,semanticEngineFingerprint:t,scope:e.scope??null})}function aY(e){return he(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:Kn(e.config.projectRoot)}))}function Nn(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function cY(e){return{status:e.status,reason:e.reason,definitions:e.definitions,referenceCacheHits:e.referenceCacheHits,referenceCacheWrites:e.referenceCacheWrites,referenceMisses:e.referenceMisses,referenceIncomplete:e.referenceIncomplete,calleeRows:e.calleeRows,error:e.error}}async function hhe(e){let t=pY(e),n={...e,phaseTimeoutMs:t??null},r=tn(m=>{let f=jm(m,n,Xn);if(!f)return null;let p=wv(m,f);return p?(p.detectorPrecision=km(cc(m),Date.now()),p):null});if(r)return r;let{applicability:i,overview:o}=tn(m=>({applicability:lY(m,e),overview:Tm(m,"overview",e)})),s=new Map;s.set("overview",o);let a=uc.filter(m=>m==="overview"?!1:uY(m,i)?!0:(s.set(m,dr(m)),!1)),c=dY(a);e.full&&tn(m=>iY(m,e));let l=await Om(c,gY(c.length),m=>mY(m,e,t)),u=[];if(l.flat().forEach(m=>{m.healthPhaseMeta&&u.push(`Health phase "${m.phase}" deferred: ${m.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),s.set(m.phase,m)}),u.length>0){let m=s.get("overview");s.set("overview",{...m,warnings:[...m.warnings,...u]})}let d=_m(uc.map(m=>s.get(m)));return d.detectorPrecision=tn(m=>km(cc(m),Date.now())),tn(m=>{let f=jm(m,n,Xn);f&&Dv(m,f,d)}),d}function lY(e,t){return as(e,{scope:t.scope})}function uY(e,t){return Lv.has(e)?t.react:Nv.has(e)?t.vue:!0}function dY(e){return vv(e,[Lv,ZJ,eY])}function dr(e){switch(e){case"react-component-duplicates":return{phase:e,reactComponentDuplicates:{count:0,loc:0,files:[]}};case"react-hook-candidates":return{phase:e,reactHookCandidates:{count:0,loc:0,files:[]}};case"react-large-component-pressure":return{phase:e,reactLargeComponentPressure:{count:0,loc:0,files:[]}};case"vue-component-duplicates":return{phase:e,vueComponentDuplicates:{count:0,loc:0,files:[]}};case"vue-composable-candidates":return{phase:e,vueComposableCandidates:{count:0,loc:0,files:[]}};case"vue-large-view-pressure":return{phase:e,vueLargeViewPressure:{count:0,loc:0,files:[]}};default:throw new Error(`Health phase "${e}" cannot be synthesized.`)}}function mY(e,t,n){if(e.length===1)return fY(e[0],t,n).then(s=>[s]);let r=e.join(","),i=process.argv[1]??Hm(import.meta.url),o=[r];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),fc({cliPath:i,command:Fv,args:o,label:`Health phases "${r}"`,timeoutMs:n}).catch(s=>{if(t.full||!(s instanceof oi))throw s;return e.map(a=>Ov(a,s.timeoutMs,`timed out after ${s.timeoutMs}ms`))})}function fY(e,t,n){let r=process.argv[1]??Hm(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),fc({cliPath:r,command:Fv,args:i,label:`Health phase "${e}"`,timeoutMs:n}).catch(o=>{if(t.full||!(o instanceof oi))throw o;return Ov(e,o.timeoutMs,`timed out after ${o.timeoutMs}ms`)})}function pY(e,t=process.env){if(e.full)return;let n=t.SCIP_QUERY_HEALTH_PHASE_TIMEOUT_MS;if(!n)return Tv;let r=parseInt(n,10);return!Number.isFinite(r)||r<0?Tv:r===0?void 0:r}function Ov(e,t,n){let r={healthPhaseMeta:{status:"deferred",reason:n,timeoutMs:t}};switch(e){case"overview":throw new Error("Overview health phase cannot be deferred.");case"dead":return{phase:e,dead:{count:0,loc:0,files:[]},...r};case"isolated":return{phase:e,isolated:{count:0,loc:0,files:[]},...r};case"cycles":return{phase:e,realCycleCount:0,...r};case"similar":return{phase:e,similarCount:0,...r};case"duplicate-bodies":return{phase:e,duplicateBodies:{count:0,loc:0,files:[]},...r};case"twin-drift":return{phase:e,twinDrift:{count:0,loc:0,files:[]},...r};case"react-component-duplicates":return{...dr(e),...r};case"react-hook-candidates":return{...dr(e),...r};case"react-large-component-pressure":return{...dr(e),...r};case"vue-component-duplicates":return{...dr(e),...r};case"vue-composable-candidates":return{...dr(e),...r};case"vue-large-view-pressure":return{...dr(e),...r};case"extract-candidates":return{phase:e,extractCount:0,...r};case"wrapper-candidates":return{phase:e,wrappers:{count:0,loc:0,files:[]},...r};case"passthrough-candidates":return{phase:e,passthroughs:{count:0,loc:0,files:[]},...r};case"stale-abstractions":return{phase:e,stale:{count:0,loc:0,files:[],unused:0,singleUse:0},...r};case"drift":return{phase:e,drift:{count:0,unusedImports:0,architectureViolations:0,layerViolations:0,direct:0,signal:0},...r};case"complexity-hotspots":return{phase:e,complexity:{top:[],extremeCount:0},...r};case"git-evidence":return{phase:e,gitEvidence:null,...r};case"suppressions":return{phase:e,suppressions:{total:0,byCategory:{}},...r};case"coverage-contracts":return{phase:e,coverageContracts:{count:0,loc:0,files:[]},...r}}}var gY=jv({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:XJ,defaultMaximum:QJ});function yhe(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
|
|
916
916
|
Codebase Health Score: ${e.score}/100`),console.log(` Risk: ${e.riskScore}/100 (risk-oriented graph facts + change graph)`),console.log(` Hygiene: ${e.hygieneScore}/100 (tidiness candidates)
|
|
917
917
|
`),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${dS(e.overview.indexSizeBytes)}
|
|
918
918
|
`),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let r of e.warnings)console.log(` ${r}`);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.twinDriftGroups>0&&console.log(` Drifted twins: ${n.twinDriftGroups} group(s)`),n.reactComponentDuplicatePairs>0&&console.log(` React components: ${n.reactComponentDuplicatePairs} duplicate pair(s)`),n.reactHookCandidatePairs>0&&console.log(` React hook reuse: ${$m(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: ${$m(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: ${$m(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(`
|
|
919
919
|
Prioritized Actions (highest impact + lowest effort first):`);for(let r=0;r<e.actions.length;r++){let i=e.actions[r],o=i.locRecoverable>0?` (~${i.locRecoverable} LOC involved)`:"";console.log(` ${r+1}. [${i.effort} effort / ${i.impact} impact] ${i.description}${o}`)}}if(e.topComplexity.length>0){console.log(`
|
|
920
|
-
Top Complexity Hotspots:`);for(let r of e.topComplexity)console.log(` ${r.score.toFixed(1).padStart(6)} ${r.symbol}`)}if(
|
|
920
|
+
Top Complexity Hotspots:`);for(let r of e.topComplexity)console.log(` ${r.score.toFixed(1).padStart(6)} ${r.symbol}`)}if(bY(e),yY(e),e.scoreBreakdown.length>0){console.log(`
|
|
921
921
|
Score Breakdown (100 minus the following):`);for(let r of e.scoreBreakdown)console.log(` -${String(r.points).padStart(2)} ${r.axis}: ${r.detail}`)}e.actions.length===0&&console.log(e.warnings&&e.warnings.length>0?`
|
|
922
922
|
No findings from completed analyses. Review warnings before interpreting this result as clean.`:`
|
|
923
|
-
No issues found. Codebase is clean.`)}function $m(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${
|
|
924
|
-
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
|
|
925
|
-
Axes:`),console.log(` Zero-reference candidates: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let r=t.changeAmplification;console.log(` Change amplification: ${r.medianFilesPerCommit} files/commit median, ${r.p90FilesPerCommit} p90 (${r.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 r of t.hiddenCoupling.top.slice(0,3))console.log(` ${r.fileA} <-> ${r.fileB} (${r.together}x together, ${Math.round(r.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let r=t.churnWeightedComplexity[0];r.weighted>0&&console.log(` Churn x complexity: hottest is ${r.symbol} (${r.changes} changes, weighted ${r.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 r=e.validation,i=r.ratio===null?"n/a":`${r.ratio}x`;console.log(` Validation: flagged files fix-density ${r.flaggedFixDensity} vs baseline ${r.baselineFixDensity} (${i})`),console.log(` fix-commit signal: subject-keyword heuristic over ${r.validationBasis.commitsScanned} commits`)}}async function
|
|
926
|
-
Affected consumer files:`),
|
|
927
|
-
//# sourceMappingURL=chunk-
|
|
923
|
+
No issues found. Codebase is clean.`)}function $m(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${hY(t)} score-weighted)`}function hY(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function yY(e){if(e.pressure.length!==0){console.log(`
|
|
924
|
+
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 bY(e){let t=e.axes;if(console.log(`
|
|
925
|
+
Axes:`),console.log(` Zero-reference candidates: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let r=t.changeAmplification;console.log(` Change amplification: ${r.medianFilesPerCommit} files/commit median, ${r.p90FilesPerCommit} p90 (${r.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 r of t.hiddenCoupling.top.slice(0,3))console.log(` ${r.fileA} <-> ${r.fileB} (${r.together}x together, ${Math.round(r.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let r=t.churnWeightedComplexity[0];r.weighted>0&&console.log(` Churn x complexity: hottest is ${r.symbol} (${r.changes} changes, weighted ${r.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 r=e.validation,i=r.ratio===null?"n/a":`${r.ratio}x`;console.log(` Validation: flagged files fix-density ${r.flaggedFixDensity} vs baseline ${r.baselineFixDensity} (${i})`),console.log(` fix-commit signal: subject-keyword heuristic over ${r.validationBasis.commitsScanned} commits`)}}async function bhe(e){let t=tn(i=>{let o=Ln(i,{base:e.base});return o.note?{kind:"complete",result:Zr(i,{base:e.base})}:o.changedFiles.length===0?{kind:"complete",result:Zr(i,{base:e.base})}:{kind:"batched",plan:o}});if(t.kind==="complete")return t.result;let n=Rv(t.plan.changedFiles,VJ),r=await Om(n,SY(n.length),i=>RY(i,e));return Ga(t.plan.changedFiles,r)}var SY=jv({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:qJ,defaultMaximum:KJ});function jv(e){return(t,n=process.env,r=GJ)=>CY(t,n,r,e)}function CY(e,t,n,r){let i=t[r.envKey],o=xY(n,r),s=i?parseInt(i,10):o;return!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e)}function xY(e,t){let n=e(),r=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,r))}function RY(e,t){let n=process.argv[1]??Hm(import.meta.url),r=[];return t.base&&r.push("--base",t.base),fc({cliPath:n,command:zJ,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function She(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}`);let t=e.attributionNotes.filter(n=>n.method==="unattributed");if(t.length>0){let n=[...new Set(t.map(r=>r.file))];for(let r of n){let i=t.filter(o=>o.file===r).length;console.log(`note: ${i} changed line-range(s) in ${r} belong to no indexed symbol`)}}console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),Ft.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
|
|
926
|
+
Affected consumer files:`),Ft.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}var Bv=Symbol("option-value-source"),$v=new Map;function whe(e){$v=new Map(e)}function Mo(e){return(...t)=>{let{args:n,opts:r}=PY(t);tn(i=>e({db:i,args:n,opts:r}))}}function yc(e,t){return Mo(n=>{let r=Mv(n.db,e,hc(n.opts,"full"),{quiet:hc(n.opts,"json")});t({...n,budget:r})})}function Dhe(e){return Mo(t=>si(t,e,{kind:"list"}))}function Ehe(e){return Mo(t=>si(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function khe(e){return Mo(t=>si(t,e,{kind:"grouped",key:e.key}))}function vY(e){return Mo(t=>Um(t,e))}function Phe(e){return vY({commandName:e.commandName,query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>Ft.sectionedReport(e.sections(t,n)),toJson:e.toJson,after:e.after})}function IY(e,t){return yc(e,n=>Um(n,{...t,commandName:t.commandName??e}))}function The(e,t){return IY(e,{commandName:t.commandName??e,query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,r)=>Ft.sectionedReport(t.sections(n,r)),toJson:t.toJson,after:t.after})}function _he(e,t){return yc(e,n=>si(n,{...t,commandName:e},{kind:"list"}))}function Fhe(e,t){return yc(e,n=>si(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Lhe(e,t){return yc(e,n=>si(n,{...t,commandName:e},{kind:"grouped",key:t.key}))}function Nhe(e,t){return String(e[t])}function Ahe(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Mhe(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Hv(e,t){let n=e[t];return typeof n=="number"?n:void 0}function hc(e,t){return!!e[t]}function Ohe(e,t){let n=e[t];return Array.isArray(n)&&n.every(r=>typeof r=="string")?n:[]}function jhe(e,t,n){return Hv(e,t)??n}function Bhe(e,t,n){let r=Hv(e,t),i=r!==void 0&&wY(e,t)!=="default";if(hc(e,"full")){if(i)throw new Error("--full cannot be combined with --limit. Use --full for all findings, or --limit N for a capped report.");return Number.MAX_SAFE_INTEGER}return r??n}function wY(e,t){return e[Bv]?.(t)}function si(e,t,n){Um(e,{commandName:t.commandName,query:t.query,emptyMessage:(r,i)=>r.length===0&&t.emptyMessage?t.emptyMessage(i):void 0,heuristicLabel:t.heuristicLabel,render:(r,i)=>{n.kind==="list"?Ft.list(r,o=>t.format(o,i)):n.kind==="table"?Ft.table(n.headers,r.map(o=>t.format(o,i)),n.dashWidths):Ft.groupedByFile(r,o=>t.format(o,i),n.key?o=>n.key(o,i):void 0)},toJson:t.toJson,before:t.before,after:t.after})}function Um(e,t){let n=t.query(e);if(hc(e.opts,"json")){EY(t.commandName,e.args,e.opts,t.toJson?t.toJson(n,e):n,{analysisBudget:DY(e)});return}let r=t.emptyMessage?.(n,e);if(r){Ft.empty(r);return}t.heuristicLabel&&Av(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function DY(e){return e.budget?.analysisBudget}function EY(e,t,n,r,i={}){let o=e?$v.get(e):void 0;console.log(JSON.stringify({command:e,...o?{evidence:o}:{},...i.analysisBudget?{analysisBudget:i.analysisBudget}:{},args:kY(t),options:n,result:r},null,2))}function kY(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function PY(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:TY(t)}}function TY(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,Bv,{value:r=>t.getOptionValueSource(r),enumerable:!1}),n)}return e}export{Te as a,BY as b,N as c,pX as d,vr as e,wt as f,Me as g,U as h,ff as i,pf as j,gf as k,cI as l,w as m,VY as n,fn as o,$ as p,st as q,o5 as r,s5 as s,q as t,UD as u,LX as v,sp as w,z4 as x,ie as y,I as z,T as A,Q as B,xe as C,B as D,Ii as E,E8 as F,so as G,Lt as H,FS as I,Hne as J,kZ as K,El as L,PZ as M,kg as N,m_ as O,Tl as P,OZ as Q,g_ as R,jZ as S,Tg as T,Ls as U,dt as V,_e as W,Nl as X,Wg as Y,p3 as Z,W_ as _,Al as $,Pi as aa,V3 as ba,g6 as ca,Eh as da,qF as ea,kh as fa,Ql as ga,Ze as ha,QY as ia,gr as ja,RI as ka,Cf as la,ZY as ma,Bo as na,vt as oa,Ar as pa,Mr as qa,Pt as ra,jh as sa,dL as ta,qs as ua,Qh as va,Zs as wa,l7 as xa,or as ya,FO as za,OO as Aa,$7 as Ba,ud as Ca,dd as Da,md as Ea,fd as Fa,pd as Ga,sr as Ha,Mj as Ia,Bj as Ja,$j as Ka,Hj as La,Y7 as Ma,eB as Na,rB as Oa,iB as Pa,oB as Qa,aB as Ra,cB as Sa,lB as Ta,lC as Ua,qr as Va,bB as Wa,uo as Xa,xB as Ya,RB as Za,PB as _a,LB as $a,Rd as ab,Na as bb,Ed as cb,mo as db,v$ as eb,fo as fb,po as gb,Pd as hb,go as ib,ho as jb,Td as kb,g1 as lb,yo as mb,xH as nb,jd as ob,Bd as pb,eU as qb,So as rb,Ln as sb,Px as tb,nG as ub,Io as vb,RG as wb,Eo as xb,ko as yb,To as zb,_o as Ab,bV as Bb,gm as Cb,ym as Db,Sm as Eb,ede as Fb,OV as Gb,jV as Hb,BV as Ib,$V as Jb,xq as Kb,Rq as Lb,Tq as Mb,Gq as Nb,Xq as Ob,pK as Pb,Im as Qb,Dm as Rb,ac as Sb,VK as Tb,Em as Ub,Bt as Vb,bfe as Wb,Sfe as Xb,vfe as Yb,Ife as Zb,cc as _b,wfe as $b,uc as ac,Tm as bc,y2 as cc,X2 as dc,ree as ec,Q2 as fc,cJ as gc,gJ as hc,_y as ic,ia as jc,Ru as kc,Fy as lc,oa as mc,Ay as nc,zy as oc,Vy as pc,Cee as qc,xee as rc,Ree as sc,vee as tc,Iee as uc,zi as vc,rb as wc,Nee as xc,qi as yc,sb as zc,Xn as Ac,ku as Bc,Pu as Cc,ete as Dc,tte as Ec,nte as Fc,rte as Gc,ute as Hc,dte as Ic,mte as Jc,fte as Kc,vte as Lc,Pte as Mc,Tte as Nc,Sa as Oc,eS as Pc,tS as Qc,rr as Rc,nS as Sc,qu as Tc,Qte as Uc,Ku as Vc,Zu as Wc,lS as Xc,lne as Yc,uS as Zc,une as _c,dne as $c,mne as ad,tn as bd,fne as cd,dS as dd,pne as ed,mS as fd,c0 as gd,hne as hd,yne as id,Ft as jd,Fv as kd,zJ as ld,Av as md,Mv as nd,ghe as od,hhe as pd,yhe as qd,bhe as rd,She as sd,whe as td,Mo as ud,yc as vd,Dhe as wd,Ehe as xd,khe as yd,vY as zd,Phe as Ad,IY as Bd,The as Cd,_he as Dd,Fhe as Ed,Lhe as Fd,Nhe as Gd,Ahe as Hd,Mhe as Id,Hv as Jd,hc as Kd,Ohe as Ld,jhe as Md,Bhe as Nd,wY as Od,EY as Pd,PY as Qd,TY as Rd};
|
|
927
|
+
//# sourceMappingURL=chunk-26JI77AY.js.map
|