codebaseiq 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/{chunk-BFBIMTCJ.js → chunk-2XBJRZEM.js} +2 -2
  3. package/dist/{chunk-GDHWOA57.js → chunk-2Z7K66D7.js} +2 -2
  4. package/dist/{chunk-HVFB3PME.js → chunk-3H2H5ODK.js} +2 -2
  5. package/dist/{chunk-LZSQ6X7E.js → chunk-3LQJRS4I.js} +2 -2
  6. package/dist/{chunk-GIDCP7KV.js → chunk-3ON3A2QV.js} +2 -2
  7. package/dist/{chunk-TPO7XC5Z.js → chunk-4GWN76B2.js} +2 -2
  8. package/dist/{chunk-GL6UTNUB.js → chunk-53ELMZRF.js} +2 -2
  9. package/dist/{chunk-6VREELBC.js → chunk-57OPIQFM.js} +2 -2
  10. package/dist/{chunk-JSNTHRLQ.js → chunk-5CR4U5X2.js} +2 -2
  11. package/dist/{chunk-GUFPEFBG.js → chunk-5MPBSFZH.js} +2 -2
  12. package/dist/{chunk-K7JLSGCJ.js → chunk-5TZNHP4T.js} +3 -3
  13. package/dist/{chunk-DVWO7RBC.js → chunk-5YBDBY5L.js} +2 -2
  14. package/dist/{chunk-T5X7DK6C.js → chunk-6EYESTJM.js} +2 -2
  15. package/dist/{chunk-AQI4N64O.js → chunk-6FXXYYQM.js} +2 -2
  16. package/dist/{chunk-VWYGCMV5.js → chunk-AGGR2BKS.js} +2 -2
  17. package/dist/{chunk-FEIZXBLH.js → chunk-ALOEHWJS.js} +2 -2
  18. package/dist/{chunk-D53LWANR.js → chunk-AXQCHG77.js} +2 -2
  19. package/dist/{chunk-7JELP5YE.js → chunk-BFANZRQ5.js} +2 -2
  20. package/dist/{chunk-5IZRKWTZ.js → chunk-BGYRF5YX.js} +2 -2
  21. package/dist/{chunk-5IC2WZAL.js → chunk-BIADXGC3.js} +2 -2
  22. package/dist/{chunk-HENP2O4A.js → chunk-BPKNP3KZ.js} +2 -2
  23. package/dist/{chunk-GP7C5VAE.js → chunk-CB5AVJMM.js} +2 -2
  24. package/dist/{chunk-HQA7EBSK.js → chunk-CJTKGAGH.js} +2 -2
  25. package/dist/{chunk-JLZLLLW5.js → chunk-CLPCFGRT.js} +2 -2
  26. package/dist/{chunk-EXZ7VLRY.js → chunk-CSPDQLLU.js} +2 -2
  27. package/dist/{chunk-AEXQYQD7.js → chunk-CYJS33YX.js} +2 -2
  28. package/dist/{chunk-AURCQHSG.js → chunk-DDRA3QKN.js} +2 -2
  29. package/dist/{chunk-3RSBGWGL.js → chunk-DECN422G.js} +2 -2
  30. package/dist/{chunk-3RR2K7EZ.js → chunk-DJKOXMNG.js} +2 -2
  31. package/dist/{chunk-PFC44E6D.js → chunk-DWBAESVW.js} +2 -2
  32. package/dist/{chunk-FQTIFWLR.js → chunk-EHPOTEQX.js} +2 -2
  33. package/dist/{chunk-NBCQZSGR.js → chunk-ELYMY5S2.js} +2 -2
  34. package/dist/{chunk-FTTV7IRX.js → chunk-EOKVZXNF.js} +42 -42
  35. package/dist/{chunk-HINZQKSY.js → chunk-F5CJO5JN.js} +2 -2
  36. package/dist/{chunk-SMDIEDM4.js → chunk-G7GVV2TV.js} +2 -2
  37. package/dist/{chunk-67VJAYVR.js → chunk-HJTM3C4Y.js} +2 -2
  38. package/dist/{chunk-I22IZYDI.js → chunk-HNXRVGMY.js} +2 -2
  39. package/dist/{chunk-NCJILOAK.js → chunk-I3OK27P7.js} +2 -2
  40. package/dist/{chunk-FWQGH2N2.js → chunk-ILGTMRMZ.js} +2 -2
  41. package/dist/{chunk-DDN2F6GB.js → chunk-JAFDMV5I.js} +2 -2
  42. package/dist/{chunk-LONKINMJ.js → chunk-JNXI6NQ7.js} +2 -2
  43. package/dist/{chunk-6BF3VYEF.js → chunk-JSB43EX6.js} +2 -2
  44. package/dist/chunk-JYRJYXUV.js +2 -0
  45. package/dist/chunk-K4S2VH42.js +82 -0
  46. package/dist/{chunk-75KJGYX7.js → chunk-K6FNTQQW.js} +2 -2
  47. package/dist/{chunk-XQPPURLQ.js → chunk-KEJ2HLRW.js} +2 -2
  48. package/dist/{chunk-D7AZAOZX.js → chunk-KFTHI2R6.js} +2 -2
  49. package/dist/{chunk-J3GLP7Q5.js → chunk-KLX6NSWT.js} +2 -2
  50. package/dist/{chunk-TJBOJUVN.js → chunk-KUKKLWJD.js} +2 -2
  51. package/dist/{chunk-2EDX3JT5.js → chunk-KUKWHP4R.js} +2 -2
  52. package/dist/{chunk-JFIA2JI3.js → chunk-KWRQVLPX.js} +2 -2
  53. package/dist/{chunk-5DSL3NT2.js → chunk-L37EQYAX.js} +2 -2
  54. package/dist/{chunk-ITSJMNUD.js → chunk-LCW3PSGL.js} +2 -2
  55. package/dist/{chunk-2PRONPAS.js → chunk-LSZYMN2A.js} +2 -2
  56. package/dist/{chunk-Q23IMHXS.js → chunk-MC46AL7B.js} +2 -2
  57. package/dist/{chunk-JYI7CV25.js → chunk-MDFT325O.js} +2 -2
  58. package/dist/{chunk-CVHOQONG.js → chunk-N2XDMNVI.js} +2 -2
  59. package/dist/chunk-NNG6M6XD.js +3 -0
  60. package/dist/{chunk-MVRGB4KJ.js → chunk-O2KWU34K.js} +2 -2
  61. package/dist/{chunk-USOAJHY7.js → chunk-OBC7HSSO.js} +2 -2
  62. package/dist/{chunk-RIYJ4L33.js → chunk-OKAF4OQS.js} +2 -2
  63. package/dist/{chunk-GQXXOS55.js → chunk-OP6BUIV6.js} +2 -2
  64. package/dist/{chunk-23C5AD3B.js → chunk-OQ3DK7FW.js} +2 -2
  65. package/dist/chunk-OT5ISJSR.js +2 -0
  66. package/dist/{chunk-C7QWUBR2.js → chunk-OWJWOEDU.js} +2 -2
  67. package/dist/{chunk-RJVAPMHF.js → chunk-PIFYOWS4.js} +2 -2
  68. package/dist/{chunk-CR3OG6SQ.js → chunk-PTR3EOXC.js} +2 -2
  69. package/dist/{chunk-NBZKSTXP.js → chunk-QY7QB7I6.js} +2 -2
  70. package/dist/{chunk-Q3ZCQY2Y.js → chunk-R4OJGTMP.js} +2 -2
  71. package/dist/{chunk-UQE4XFSA.js → chunk-RIO3JXHM.js} +2 -2
  72. package/dist/{chunk-CW6AXOLR.js → chunk-SA7G6GJX.js} +2 -2
  73. package/dist/{chunk-Q4XEU3UH.js → chunk-SB53KPWA.js} +2 -2
  74. package/dist/{chunk-36JC5BG2.js → chunk-SUE7SHZL.js} +2 -2
  75. package/dist/{chunk-ZAFGY22Q.js → chunk-SZ4P7MF7.js} +2 -2
  76. package/dist/{chunk-BBP7HVBJ.js → chunk-T2M5HWBQ.js} +2 -2
  77. package/dist/{chunk-MHWMEZDA.js → chunk-TEMM2FEL.js} +2 -2
  78. package/dist/{chunk-JX6ZWDOS.js → chunk-TLTSESB4.js} +2 -2
  79. package/dist/{chunk-FOZ74V56.js → chunk-UIAUPFBJ.js} +2 -2
  80. package/dist/{chunk-PHNCEUXX.js → chunk-UJIXCI3L.js} +2 -2
  81. package/dist/{chunk-XMJ53WG4.js → chunk-UMEPSVKT.js} +2 -2
  82. package/dist/{chunk-GWYZVVKY.js → chunk-V4NGDIEA.js} +2 -2
  83. package/dist/{chunk-E52K4L2W.js → chunk-VSGOIZMQ.js} +2 -2
  84. package/dist/{chunk-Z6RL7XOE.js → chunk-W7QDASTN.js} +2 -2
  85. package/dist/{chunk-PTQPPPG2.js → chunk-WO6OFKUC.js} +2 -2
  86. package/dist/{chunk-C7OUW52M.js → chunk-XJBK3QDV.js} +2 -2
  87. package/dist/{chunk-FH5WG4LE.js → chunk-XUPFA6GH.js} +2 -2
  88. package/dist/{chunk-DAKIGMIK.js → chunk-YPBKBYPS.js} +2 -2
  89. package/dist/{chunk-ZQ62NNKN.js → chunk-Z66XYVLZ.js} +2 -2
  90. package/dist/{chunk-OFGOOL6U.js → chunk-ZMA5HWXY.js} +2 -2
  91. package/dist/{cli-program-UO7PZD6V.js → cli-program-SCHOHOQE.js} +2 -2
  92. package/dist/cli.js +1 -1
  93. package/dist/{code-viewer-VHLBLIUM.js → code-viewer-AMRXV444.js} +2 -2
  94. package/dist/{code-viewer-KIXEYQNJ.js → code-viewer-EXI5SFFR.js} +2 -2
  95. package/dist/{command-descriptors-F5P2V3NW.js → command-descriptors-H6A4UY72.js} +3 -3
  96. package/dist/{command-descriptors-YCLATF5I.js → command-descriptors-ROIOTCCW.js} +3 -3
  97. package/dist/direct-navigation-3JOYP2MO.js +3 -0
  98. package/dist/direct-navigation-SJMJLBY7.js +2 -0
  99. package/dist/index.js +1 -1
  100. package/dist/invocation-command-descriptors-GMZX3UAD.js +2 -0
  101. package/dist/invocation-command-descriptors-HNMKDEF6.js +3 -0
  102. package/dist/{output-continuation-command-BTETTXEC.js → output-continuation-command-5NWVDQT7.js} +2 -2
  103. package/dist/output-continuation-command-RNEHNYPU.js +3 -0
  104. package/dist/project-reindex-MIW5CYEG.js +3 -0
  105. package/dist/{project-reindex-CRJU3IFG.js → project-reindex-VQ23LWDA.js} +2 -2
  106. package/dist/queries/affected.js +1 -1
  107. package/dist/queries/anchors.js +1 -1
  108. package/dist/queries/bottlenecks.js +1 -1
  109. package/dist/queries/call-graph.js +1 -1
  110. package/dist/queries/change-surface.js +1 -1
  111. package/dist/queries/cleanup-plan.js +1 -1
  112. package/dist/queries/complexity-hotspots.js +1 -1
  113. package/dist/queries/complexity.js +1 -1
  114. package/dist/queries/context.js +1 -1
  115. package/dist/queries/convergence.js +1 -1
  116. package/dist/queries/dataflow.js +1 -1
  117. package/dist/queries/dead.js +1 -1
  118. package/dist/queries/decorative-checkers.js +1 -1
  119. package/dist/queries/dependence-slice.js +1 -1
  120. package/dist/queries/diff-impact.js +1 -1
  121. package/dist/queries/drift.js +1 -1
  122. package/dist/queries/entry-map.js +1 -1
  123. package/dist/queries/evidence.js +1 -1
  124. package/dist/queries/extract-candidates.js +1 -1
  125. package/dist/queries/health.js +1 -1
  126. package/dist/queries/hotspots.js +1 -1
  127. package/dist/queries/imports.js +1 -1
  128. package/dist/queries/incomplete-migration.js +1 -1
  129. package/dist/queries/index.js +1 -1
  130. package/dist/queries/isolated.js +1 -1
  131. package/dist/queries/locality-candidates.js +1 -1
  132. package/dist/queries/members.js +1 -1
  133. package/dist/queries/methods.js +1 -1
  134. package/dist/queries/not-implemented.js +1 -1
  135. package/dist/queries/passthrough-candidates.js +1 -1
  136. package/dist/queries/plan-context.js +1 -1
  137. package/dist/queries/recent-duplicates.js +1 -1
  138. package/dist/queries/redundant-reexports.js +1 -1
  139. package/dist/queries/reference-neighborhood.js +1 -1
  140. package/dist/queries/reference-reachability.js +1 -1
  141. package/dist/queries/refs.js +1 -1
  142. package/dist/queries/self-audit.js +1 -1
  143. package/dist/queries/similar-signatures.js +1 -1
  144. package/dist/queries/similar.js +1 -1
  145. package/dist/queries/slice.js +1 -1
  146. package/dist/queries/source-inspection.js +1 -1
  147. package/dist/queries/stale-abstractions.js +1 -1
  148. package/dist/queries/surface.js +1 -1
  149. package/dist/queries/system-map.js +1 -1
  150. package/dist/queries/trace.js +1 -1
  151. package/dist/queries/twin-ab.js +1 -1
  152. package/dist/queries/unused-imports.js +1 -1
  153. package/dist/queries/unused-params.js +1 -1
  154. package/dist/queries/value-flow.js +1 -1
  155. package/dist/queries/wrapper-candidates.js +1 -1
  156. package/dist/reindex-worker.js +1 -1
  157. package/dist/reindex.js +1 -1
  158. package/dist/runtime.js +1 -1
  159. package/dist/rust-semantic-session-server.js +1 -1
  160. package/dist/rust-semantic-session-worker.js +1 -1
  161. package/dist/rust-semantic-worker.js +1 -1
  162. package/dist/{sentinel-ensure-command-SPW7XQLB.js → sentinel-ensure-command-H66AZ3VE.js} +2 -2
  163. package/dist/sentinel-ensure-command-R4YAUCJB.js +3 -0
  164. package/dist/watch-server.js +1 -1
  165. package/package.json +1 -1
  166. package/dist/chunk-6JMAVFL4.js +0 -3
  167. package/dist/chunk-6WAPPQ5F.js +0 -82
  168. package/dist/chunk-P4NVCOM7.js +0 -2
  169. package/dist/chunk-Z35GOVEH.js +0 -2
  170. package/dist/direct-navigation-4XJTXIDT.js +0 -2
  171. package/dist/direct-navigation-J5MVYYAD.js +0 -3
  172. package/dist/invocation-command-descriptors-RWV4VAI4.js +0 -2
  173. package/dist/invocation-command-descriptors-U76PN7IY.js +0 -3
  174. package/dist/output-continuation-command-BL25S26S.js +0 -3
  175. package/dist/project-reindex-TQFCOA2O.js +0 -3
  176. package/dist/sentinel-ensure-command-OSWGCFFL.js +0 -3
@@ -1,4 +1,4 @@
1
- import{a as at}from"./chunk-ILMHV3KM.js";import{a as mt}from"./chunk-XN3EKMLI.js";import{G as ht,a as pt,b as gt,h as Z,i as W,j as de,k as bt}from"./chunk-LONKINMJ.js";import{U as ot,V as st,g as he,k as nt}from"./chunk-6WAPPQ5F.js";import{b as Ke,c as Ve,d as Ge,q as rt}from"./chunk-EQNMD62X.js";import{D as Ze,E as et,I as tt}from"./chunk-C6WKPKCF.js";import{d as Xe,e as Ye,f as Qe}from"./chunk-DRENNWRG.js";import{b as X,c as Ee,d as it,e as dt,f as ct,i as lt,j as ut,k as ft}from"./chunk-MEUHIDI3.js";import{a as be,l as ze,m as Je}from"./chunk-5FWR5HLG.js";import{i as H,j as J,m as je}from"./chunk-T75DS2E6.js";import{b as qe}from"./chunk-YT4DVWUV.js";import{a as We}from"./chunk-RCIGX23V.js";import{a as ge,b as ie}from"./chunk-6O3KXIDL.js";import{e as He,g as pe}from"./chunk-UQYQBLJX.js";import{join as $e}from"path";import{createHash as gn}from"crypto";import{mkdirSync as Ct,mkdtempSync as bn,renameSync as hn,rmSync as kt,statSync as En,writeFileSync as wt}from"fs";import{tmpdir as yn}from"os";import{extname as Sn,join as ee,resolve as vn,sep as Cn}from"path";var kn=1024*1024,Et=500,wn=64,Rn=/\.(?:cmd|bat)$/i;async function Rt(e,t,n={}){let r=Se(e);if(!r.ok)return $(r.reason,r.detail);let a=JSON.stringify(it),o;try{Ct(t.workDir,{recursive:!0}),o=bn(ee(yn(),"codebaseiq-probe-")),e.argv.includes("{schemaFile}")&&wt(ee(o,"schema.json"),a)}catch(s){return yt(o),$("spawn-failed",`could not prepare the agent sandbox: ${te(xn(s))}`)}try{let s=ee(o,"schema.json"),d=ee(o,"output.json"),i=e.argv.includes("{outputFile}"),c=new Map([["{schemaJson}",a],["{schemaFile}",s],["{outputFile}",d]]),l=Ve(r.path,e.argv.slice(1).map(S=>c.get(S)??S)),b;try{b=await st({command:l.binary,args:l.args,label:`agent probe command ${e.name}`,timeoutMs:e.timeoutMs,maxStdoutBytes:e.maxOutputBytes,maxStderrBytes:kn,cwd:t.workDir,env:Tn(n.env??process.env),input:ct(t.description,t.languages),signal:n.signal})}catch(S){return _n(S,n.signal)}if(b.status!==0){let S=St(b.stdout),g=b.status===null?`signal ${b.signal}`:`code ${b.status}`,m=S.kind==="error"?S.detail:b.stderr.trim()||b.stdout.trim();return $("agent-error",`${e.name} exited with ${g}: ${te(m)}`)}let p=[];if(i){let S=Mn(d,e.maxOutputBytes);if(S==="too-large")return $("output-too-large",`${e.name} wrote more than ${e.maxOutputBytes} bytes.`);S!==null&&p.push(S)}p.push(b.stdout);for(let S of p){let g=St(S);if(g.kind==="error")return $("agent-error",g.detail);if(g.kind==="none")continue;let{probes:m,diagnostics:w}=Ee(g.value);return X(m)?{ok:!0,probes:m,diagnostics:w,raw:S.trim()}:$("invalid-probes",On(w))}return $("no-json",`${e.name} printed no JSON object: ${te(b.stdout.trim())}`)}finally{yt(o)}}function yt(e){if(e!==void 0)try{kt(e,{recursive:!0,force:!0,maxRetries:3})}catch{}}function xn(e){return e instanceof Error?e.message:String(e)}function $(e,t){return{ok:!1,reason:e,detail:t}}function Pn(e){let t=ut({agent:{commands:[e]}}).filter(n=>n.level==="error");return t.length>0?t.map(n=>`${n.path}: ${n.message}`).join(" "):ft.has(e.argv[0])?"argv[0] must be the executable, not a placeholder.":[e.timeoutMs,e.maxOutputBytes].every(n=>Number.isFinite(n)&&n>0)?null:"timeoutMs and maxOutputBytes must be positive numbers."}function Se(e){let t=Pn(e);if(t)return{ok:!1,reason:"misconfigured",detail:t};let n=e.argv[0],r=`argv[0] "${n}" is a .cmd/.bat shim, which cannot be started without a shell. Point argv[0] at the real executable or at a node script (.js, .mjs, .cjs).`,a=n.includes("/")||n.includes(Cn),o;if(a){o=An(vn(n));let s=ye(o);if(s==="missing")return{ok:!1,reason:"spawn-failed",detail:`argv[0] "${n}" was not found.`};if(s==="other")return{ok:!1,reason:"misconfigured",detail:`argv[0] "${n}" is not an executable file.`}}else o=Ge(n);return o===null?Ke(n)?{ok:!1,reason:"misconfigured",detail:r}:{ok:!1,reason:"spawn-failed",detail:`argv[0] "${n}" was not found on PATH.`}:process.platform==="win32"&&Rn.test(o)?{ok:!1,reason:"misconfigured",detail:r}:{ok:!0,path:o}}function An(e,t=process.platform){return t!=="win32"||Sn(e)!==""||ye(e)!=="missing"?e:[".exe",".com"].map(n=>`${e}${n}`).find(n=>ye(n)==="file")??e}function ye(e){try{return En(e).isFile()?"file":"other"}catch{return"missing"}}function Tn(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&!/^CODEBASEIQ_/i.test(n)&&(t[n]=r);return t}function _n(e,t){if(!(e instanceof ot))throw e;switch(e.kind){case"spawn":return $("spawn-failed",e.message);case"timeout":return $("timeout",e.message);case"stdout-limit":case"stderr-limit":return $("output-too-large",e.message);case"aborted":throw t?H(t,e.message):e}}function Mn(e,t){try{return pe(e,{maxBytes:t,inputKind:"agent output file"})}catch(n){return n instanceof He&&n.reason==="too-large"?"too-large":null}}function St(e){let t=vt(e);if(!t)return{kind:"none"};if(t.type!=="result")return{kind:"object",value:t};if(t.is_error===!0){let r=typeof t.result=="string"&&t.result?t.result:t.subtype;return{kind:"error",detail:te(`The agent reported an error: ${String(r??"no message")}`)}}if(Pt(t.structured_output))return{kind:"object",value:t.structured_output};let n=typeof t.result=="string"?vt(t.result):null;return n?{kind:"object",value:n}:{kind:"none"}}function vt(e){let t=e.trim();return xt(t)??Bn(t)}function xt(e){try{let t=JSON.parse(e);return Pt(t)?t:null}catch{return null}}function Bn(e){let t=/\{\s*["}]/g,n=null,r=0;for(let a=0;a<wn;){t.lastIndex=r;let o=t.exec(e);if(!o)break;let s=Nn(e,o.index),d=s===-1?null:xt(e.slice(o.index,s+1));d?(n=d,r=s+1):(r=o.index+1,a++)}return n}function Nn(e,t){let n=0,r=!1,a=!1;for(let o=t;o<e.length;o++){let s=e[o];if(r)a?a=!1:s==="\\"?a=!0:s==='"'&&(r=!1);else if(s==='"')r=!0;else if(s==="{")n++;else if(s==="}"&&--n===0)return o}return-1}function Pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function On(e){return e.length===0?"The agent returned no usable probes.":te(`The agent returned no usable probes: ${e.slice(0,3).map(t=>`${t.path||"root"}: ${t.message}`).join("; ")}`)}function te(e){return e.length>Et?`${e.slice(0,Et)}...`:e}var Fn=64*1024,Ln=3600*1e3;function At(e,t,n=Date.now){let r=(a,o)=>ee(e,`${gn("sha256").update(JSON.stringify([a,3,o])).digest("hex")}.json`);return{get(a,o){try{let s=JSON.parse(pe(r(a,o),{maxBytes:Fn,inputKind:"agent probe cache entry"}));if(typeof s.storedAt!="number"||n()-s.storedAt>=t*Ln)return;let{probes:d}=Ee(s.probes);return X(d)?d:void 0}catch{return}},set(a,o,s){let d=r(a,o),i=`${d}.${process.pid}.tmp`;try{Ct(e,{recursive:!0}),wt(i,JSON.stringify({storedAt:n(),probes:s})),hn(i,d)}catch{try{kt(i,{force:!0})}catch{}}}}}import{BlockList as In,isIP as $n}from"net";var Ce=64*1024*1024,Dn=2,Tt="embedding request aborted",Un="codebaseiq embedding canary: parse a retry delay from a config file",M=class extends Error{constructor(n,r,a){super(r);this.kind=n;this.status=a;this.name="EmbeddingClientError"}kind;status},ne=new In;for(let[e,t]of[["127.0.0.0",8],["10.0.0.0",8],["172.16.0.0",12],["192.168.0.0",16],["100.64.0.0",10],["169.254.0.0",16]])ne.addSubnet(e,t,"ipv4");ne.addAddress("::1","ipv6");ne.addSubnet("fe80::",10,"ipv6");ne.addSubnet("fc00::",7,"ipv6");var Hn=[".local",".lan",".home.arpa",".internal"];function _t(e){let t;try{t=new URL(e).hostname}catch{return!1}let n=(t.startsWith("[")?t.slice(1,-1):t).replace(/\.$/,""),r=$n(n);return r!==0?ne.check(n,r===4?"ipv4":"ipv6"):n==="localhost"||Hn.some(a=>n.endsWith(a))}function Nt(e,t={}){let n=t.fetchImpl??fetch,r=t.env??process.env,a=e.baseUrl.replace(/\/+$/,"");function o(){let l=e.apiKeyEnv?r[e.apiKeyEnv]:void 0;return l||void 0}function s(){let l;try{l=new URL(e.baseUrl)}catch{throw new M("invalid-endpoint",`embedding endpoint "${e.name}" has an invalid baseUrl`)}if(l.protocol!=="http:"&&l.protocol!=="https:")throw new M("invalid-endpoint",`embedding endpoint "${e.name}" must use http or https`);if(l.username!==""||l.password!=="")throw new M("invalid-endpoint",`embedding endpoint "${e.name}" must not embed credentials in baseUrl; use apiKeyEnv`);if(!e.allowRemote&&!_t(e.baseUrl))throw new M("remote-not-allowed",`embedding endpoint "${e.name}" is not on a private network; set allowRemote to use it`);if(l.protocol==="http:"&&o()!==void 0&&!_t(e.baseUrl))throw new M("insecure-token-transport",`embedding endpoint "${e.name}" would send its API key over plain http to a non-private host; use https`)}function d(l){let b={};l&&(b["content-type"]="application/json");let p=o();return p&&(b.authorization=`Bearer ${p}`),b}async function i(l,b,p,S){let g={model:e.model,input:l,encoding_format:"float",...e.dimensions!==void 0?{dimensions:e.dimensions}:{}},{status:m,text:w}=await Mt(n,`${a}/embeddings`,{method:"POST",headers:d(!0),body:JSON.stringify(g)},b,!0,S);if(m<200||m>=300)throw new M("http",`embeddings request failed with HTTP ${m}`,m);return Vn(w,l.length,p)}async function c(l,b,p){try{return await i(l,e.requestTimeoutMs,b,p)}catch(S){if(!Wn(S))throw S;return i(l,e.requestTimeoutMs,b,p)}}return{async checkHealth({signal:l}={}){try{s()}catch(p){return ve(p)}try{await Mt(n,`${a}/models`,{method:"GET",headers:d(!1)},e.healthTimeoutMs,!1,l)}catch(p){return l?.aborted?ve(p,l):{ok:!1,reason:"unreachable",detail:ke(p)}}let b=ge();try{let[p]=await i([e.documentPrefix+Un],e.warmTimeoutMs,{dims:e.dimensions},l);return{ok:!0,model:e.model,dimensions:p.length,latencyMs:Math.round(ge()-b),canary:p}}catch(p){return ve(p,l)}},async embed(l,b,{signal:p}={}){if(s(),l.length===0)return[];let S=b==="query"?e.queryPrefix:e.documentPrefix,g=Math.max(1,Math.floor(e.batchSize)),m=[];for(let x=0;x<l.length;x+=g)m.push(l.slice(x,x+g).map(A=>S+A));let w={dims:e.dimensions};return(await at(m,Dn,x=>c(x,w,p))).flat()}}}function Wn(e){return e instanceof M&&(e.kind==="timeout"||e.kind==="http"&&(e.status??0)>=500)}function ve(e,t){let n=ke(e);if(t?.aborted)return{ok:!1,reason:"aborted",detail:n};if(!(e instanceof M))return{ok:!1,reason:"bad-response",detail:n};switch(e.kind){case"remote-not-allowed":case"insecure-token-transport":case"invalid-endpoint":return{ok:!1,reason:e.kind,detail:n};case"network":return{ok:!1,reason:"unreachable",detail:n};case"timeout":return{ok:!1,reason:"model-loading",detail:n};case"http":return e.status===503?{ok:!1,reason:"model-loading",detail:n}:e.status===401||e.status===403?{ok:!1,reason:"unauthorized",detail:n}:{ok:!1,reason:"bad-response",detail:n};default:return{ok:!1,reason:"bad-response",detail:n}}}function ke(e){return e instanceof Error?e.message:String(e)}async function Mt(e,t,n,r,a,o){J(o,Tt);let s=new AbortController,d=setTimeout(()=>{s.abort(new M("timeout",`no response within ${r}ms`))},r),i=()=>s.abort(o?.reason);o?.addEventListener("abort",i,{once:!0});try{let c=await Ot(e(t,{...n,signal:s.signal,redirect:"error"}),s.signal);return{status:c.status,text:a?await Kn(c,s.signal):""}}catch(c){throw o?.aborted&&s.signal.reason===o.reason?H(o,Tt):c instanceof M?c:s.signal.aborted&&s.signal.reason instanceof M?s.signal.reason:new M("network",`could not reach the embeddings endpoint: ${jn(c)}`)}finally{clearTimeout(d),o?.removeEventListener("abort",i),s.abort()}}function jn(e){let t=e instanceof Error?e.cause:void 0;return typeof t?.code=="string"?t.code:ke(e)}async function Kn(e,t){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>Ce)throw Bt();if(!e.body)return"";let r=e.body.getReader(),a=[],o=0;for(;;){let{done:s,value:d}=await Ot(r.read(),t);if(s)break;if(o+=d.byteLength,o>Ce)throw r.cancel().catch(()=>{}),Bt();a.push(d)}return new TextDecoder().decode(Buffer.concat(a))}function Bt(){return new M("too-large",`embeddings response exceeded the ${Ce} byte limit`)}function Ot(e,t){return new Promise((n,r)=>{let a=()=>r(t.reason);if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",a))})}function Vn(e,t,n){let r;try{r=JSON.parse(e)}catch{throw j("response is not valid JSON")}let a=typeof r=="object"&&r!==null?r.data:void 0;if(!Array.isArray(a)||a.length!==t)throw j(`expected ${t} embeddings, received ${Array.isArray(a)?a.length:"none"}`);let o=new Array(t).fill(void 0),s=new Set;return a.forEach((d,i)=>{let c=typeof d=="object"&&d!==null?d:{},l=c.index===void 0?i:c.index;if(typeof l!="number"||!Number.isInteger(l)||l<0||l>=t||s.has(l))throw j("embedding indexes are not a permutation of the inputs");s.add(l),o[l]=c.embedding}),o.map(d=>Gn(d,n))}function Gn(e,t){if(!Array.isArray(e)||e.length===0)throw j("embedding is not a non-empty float array");if(t.dims!==void 0&&e.length!==t.dims)throw j(`embedding has ${e.length} dimensions, expected ${t.dims}`);let n=0;for(let o of e){if(typeof o!="number"||!Number.isFinite(o))throw j("embedding contains a non-finite value");n+=o*o}let r=Math.sqrt(n);if(!Number.isFinite(r)||r===0)throw j("embedding has zero or unrepresentable magnitude");t.dims=e.length;let a=new Float32Array(e.length);for(let o=0;o<e.length;o+=1)a[o]=e[o]/r;return a}function j(e){return new M("bad-response",`embeddings response rejected: ${e}`)}var xe=["name","container","doc","signature","path"],qn=1e3,zn=150,Jn=400,Xn=3,we=/@deprecated\b|#\[deprecated\b|\bdeprecated\s*[:(]/i,Ft=/^\s*(?:\/\/|\/\*|\*|#|@)/,Yn=new Set(gt()),Qn=/(?:^|\/)(?:__generated__|generated)\/|\.(?:generated|gen|g)\.[a-z0-9]+$|\.pb2?\.[a-z0-9]+$|_pb2?\.[a-z0-9]+$/i,Re=/@generated\b|\bcode generated\b.*\bdo not edit\b/i,Zn=40,er=/^(?:\/\/|--|#(?![[!\w]))/,tr=/^\s*export\s+(?:default\s+)?(?:(?:async\s+)?function|(?:abstract\s+)?class|interface|type|enum|namespace|module|const|let|var)\s+([\p{L}\p{N}_$]+)/u,nr=/^\s*export\s*\{([^}\n]*)/,rr=/[\p{L}\p{N}_$]+/gu,or=2,sr=qe("builder-candidate-corpus",{clearGroups:["whole-project","definition-catalog"]});function Y(e){return sr.get(e,()=>dr(e))}function D(e,t=2,n=Number.POSITIVE_INFINITY){let r=[],a=[],o=new Set;for(let s of W(e)){if(r.length>=n)break;if(Z.has(s.toLocaleLowerCase()))continue;let d=de(s),i=d[0];if(!(i.length<t||Z.has(i))){r.push(i),a.push(d);for(let c of d)o.add(c)}}return{words:r,variants:a,set:o}}function Pe(e){return W(e).map(bt)}function ar(e){let t=0,n=0,r=0,a=-1;for(let i=0;i<e.length&&a<0;i+=1){let c=e[i];c==="["?t+=1:c==="]"?t=Math.max(0,t-1):c==="{"?n+=1:c==="}"?n=Math.max(0,n-1):c==="<"?r+=1:c===">"&&e[i-1]!=="="&&e[i-1]!=="-"?r=Math.max(0,r-1):c==="("&&t===0&&n===0&&r===0&&(a=i)}if(a<0)return{params:null,returns:null};let o=0,s=-1;for(let i=a;i<e.length;i+=1){let c=e[i];if(c==="(")o+=1;else if(c===")"&&(o-=1,o===0)){s=i;break}}if(s<0)return{params:e.slice(a+1).trim(),returns:null};let d=e.slice(s+1).trim().replace(/^(?:=>|->|:)\s*/,"").replace(/\s+where\b.*$/,"").replace(/\s*(?:=>|=|\{|:)\s*$/,"").trim();return{params:e.slice(a+1,s).trim(),returns:d||null}}function ir(e){if(!e)return"";let t=/^\s*```(?:\w+)?\s*\n?[\s\S]*?\n?```/.exec(e);return(t?e.slice(t[0].length):e.includes("|")?e.slice(0,e.indexOf("|")):"").replace(/\s+/g," ").trim().slice(0,qn)}function dr(e){let t=new Map,n=new Set;for(let s of tt(e)){if(s.symbol.startsWith("local ")||!s.isFunctionLike&&!s.isTypeLike||e.isIgnored(s.relativePath)||he(s.relativePath)==="test")continue;let d=`${s.symbol}\0${s.relativePath}`;if(n.has(d))continue;n.add(d);let i=t.get(s.relativePath);i?i.push(s):t.set(s.relativePath,[s])}let r=[];for(let s of[...t.keys()].sort()){let d=Je(e,s);if(Cr(s,d))continue;let i=t.get(s),c=fr(e,s,d,i);for(let l of i){let b=pr(l,c);b&&r.push({definition:l,candidate:b})}}r.sort((s,d)=>s.candidate.file.localeCompare(d.candidate.file)||s.candidate.startLine-d.candidate.startLine||s.candidate.name.localeCompare(d.candidate.name));let a=ht(e,new Set,r.map(({definition:s})=>s.symbolId)),o=r.map(({definition:s,candidate:d})=>{let i=[...a.get(s.symbolId)??[]].filter(([c,l])=>c!==d.file&&l.occurrences>0&&he(c)!=="test").map(([c])=>c).sort();return{...d,referencedFrom:i,consumable:d.exported||i.length>0}});return lr(o,r.map(({definition:s})=>cr(s)))}function cr(e){let{symbolId:t,documentId:n,startLine:r,endLine:a,symbol:o,relativePath:s}=e;return{symbolId:t,documentId:n,startLine:r,endLine:a,symbol:o,relativePath:s}}function lr(e,t){let n=new Map,r=new Map,a=new Map,o=new Set;return e.forEach((s,d)=>{let i=new Set;for(let c of xe)for(let l of s.fields[c].set)i.add(l);for(let c of i)It(n,c,d);for(let c of s.fields.name.set)r.set(c,(r.get(c)??0)+1);It(a,s.name,d);for(let c of s.calleeLeaves)o.add(c)}),{candidates:e,locations:t,byToken:n,nameDocFreq:r,byName:a,calledLeaves:o}}var Lt=new WeakMap;function $t(e,t,n,r){let a=Lt.get(t);a||(a=new Map,Lt.set(t,a));let o=a.get(n);return o||(o=ur(e,t.locations[n],t.candidates[n].name),a.set(n,o)),o.get(r)??[]}function ur(e,t,n){let r=new Map;for(let o of rt(e,[t.symbolId])){if(e.isIgnored(o.relative_path))continue;let s=[o.chunk_start,o.chunk_end],d=r.get(o.relative_path);d?d.push(s):r.set(o.relative_path,[s])}let a=new Map;for(let[o,s]of r){let d=o===t.relativePath?{excludeStartLine:t.startLine,excludeEndLine:t.endLine}:{},i=nt(e,o,n,d);a.set(o,s.flatMap(([c,l])=>{let b=i.filter(p=>p>=c&&p<=l);return b.length>0?b.map(p=>[p,p]):[[c,l]]}))}return a}function It(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function fr(e,t,n,r){let a=null;return{lines:n,units:mr(e,t),endLines:r.map(o=>o.endLine).sort((o,s)=>o-s),exportedNames:()=>a??=Sr(n)}}function mr(e,t){let n=new Map,r=ze(e,t);if(!r)return n;for(let a of mt(e,t,r)?.units??[]){let o=n.get(a.name);o?o.push(a):n.set(a.name,[a])}return n}function pr(e,t){let{units:n}=t,r=e.isTypeLike?null:gr(n.get(e.leaf),e.startLine),a=!e.isTypeLike&&(r!==null||Qe(e.symbol)||Yn.has(e.kind??-1));if(!e.isTypeLike&&!a)return null;let o=Ze(et(e.documentation)),s=kr(a&&(!o||!o.includes("("))&&r?r.signature:o??r?.signature??"").slice(0,Jn),d=a&&s?ar(s):{params:null,returns:null},i=ir(e.documentation),c=br(e,r),l=e.leaf;return{symbol:e.symbol,name:l,kind:a?e.parentTypeName?"method":"function":hr(e,s),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,container:c,doc:i,signature:s||null,paramsText:d.params,returnsText:d.returns,nameWords:Pe(l),fields:{name:D(l),container:D(c??""),doc:D(i,3,zn),signature:D(s),path:D(e.relativePath.replace(/\.[^./]+$/,""))},calleeLeaves:r?.calleeLeaves??[],hasBody:r!==null,exported:r?.exported===!0||vr(t.exportedNames(),e),deprecated:Er(t,e,i)}}function gr(e,t){let n=null;for(let r of e??[]){let a=Math.abs(r.startLine-t);a<=Xn&&(!n||a<Math.abs(n.startLine-t))&&(n=r)}return n}function br(e,t){return e.parentTypeName?e.parentTypeName:e.enclosingSymbol&&Ye(e.enclosingSymbol)!=="namespace"?Xe(e.enclosingSymbol)||null:t?.container.at(-1)??null}function hr(e,t){let r=(/^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(class|struct|interface|trait|protocol)\b/.exec(t)?.[1]??pt(e.kind??0)).toLowerCase();return r==="class"||r==="struct"?"class":r==="interface"||r==="trait"||r==="protocol"?"interface":"type"}function Er(e,t,n){if(we.test(n))return!0;let{lines:r}=e,a=r[t.startLine];if(a!==void 0&&Ft.test(a)&&we.test(a))return!0;let o=yr(e.endLines,t.startLine),s=!1;for(let d=t.startLine-1;d>o;d-=1){let i=r[d]?.trim()??"";if(i===""){if(s)continue;return!1}if(!s&&!Ft.test(i))return!1;if(we.test(i))return!0;s?s=!i.includes("/*"):s=i.endsWith("*/")&&!i.includes("/*")}return!1}function yr(e,t){let n=0,r=e.length;for(;n<r;){let a=n+r>>>1;e[a]<t?n=a+1:r=a}return n>0?e[n-1]:-1}function Sr(e){let t=new Map,n=new Set;return e.forEach((r,a)=>{if(!r.includes("export"))return;let o=tr.exec(r)?.[1];if(o){let s=t.get(o);s?s.push(a):t.set(o,[a])}for(let s of nr.exec(r)?.[1]?.match(rr)??[])n.add(s)}),{declared:t,listed:n}}function vr(e,t){if(e.listed.has(t.leaf))return!0;let n=t.startLine-or;return e.declared.get(t.leaf)?.some(r=>r>=n&&r<=t.startLine)??!1}function Cr(e,t){if(Qn.test(e.replace(/\\/g,"/")))return!0;let n=!1;for(let[r,a]of t.slice(0,Zn).entries()){let o=a.trim();if(n){if(Re.test(o))return!0;n=!o.includes("*/")}else{if(o===""||r===0&&o.startsWith("#!"))continue;if(o.startsWith("/*")){if(Re.test(o))return!0;n=!o.includes("*/",2)}else if(er.test(o)){if(Re.test(o))return!0}else return!1}}return!1}function kr(e){return e.replace(/\s+/g," ").trim()}var wr={name:1,container:.8,doc:.6,signature:.5,path:.3},Rr=200,xr=3,Pr=5,Ar=new Set(["add","apply","build","calculate","call","check","compute","config","context","convert","create","data","default","delete","do","ensure","error","fetch","find","format","get","handle","has","info","init","is","item","load","make","new","normalize","option","param","parse","process","read","remove","resolve","result","run","set","state","type","update","use","validate","value","with","wrap","write"]);function Ut(e,t,n={}){let r=Tr(e,t,n.scope),a=[];for(let o of Mr(e,r)){if(!Wt(r,e.candidates[o]))continue;let s=jt(r,e,o);(s.exactName||s.match>0)&&a.push(s)}return a.sort((o,s)=>Number(s.exactName)-Number(o.exactName)||s.match-o.match||s.nameCoverage-o.nameCoverage||o.index-s.index),{plan:r,corpusUnits:e.candidates.filter(o=>Q(r.scope,o)).length,shortlist:a.slice(0,Rr).map(o=>Kt(r,e,o)),unresolvedProbes:r.calls.filter(o=>o.status!=="matched").map(o=>({probe:o.probe,status:o.status}))}}function Ht(e,t,n){return Wt(t,e.candidates[n])?Kt(t,e,jt(t,e,n)):null}function re(e){return e?e.replace(/\\/g,"/").toLowerCase():null}function Q(e,t){return!e||t.file.toLowerCase().includes(e)}function Wt(e,t){return Q(e.scope,t)?e.kinds.size===0||e.kinds.has(t.kind)?!0:(t.kind==="function"||t.kind==="method")&&(e.kinds.has("function")||e.kinds.has("method")):!1}function Tr(e,t,n){let r=new Set,a=i=>{for(let c of W(i))for(let l of de(c))r.add(l)},o=[];for(let i of t.terms){let c=[],l=[];for(let p of i){let S=Ae(p);S.length!==0&&(c.push(p),l.push(S),a(p))}if(l.length===0)continue;let b=Math.max(...l.map(p=>_r(e,p)));o.push({labels:c,synonyms:l,weight:Math.log((e.candidates.length+1)/(b+1))+1})}let s=t.names.map(Pe).filter(i=>i.length>0);for(let i of t.names)a(i);for(let i of t.calls)a(i);for(let i of[...t.params,...t.returns])a(i);let d=t.calls.map(i=>Nr(e,i));return{groups:o,totalWeight:o.reduce((i,c)=>i+c.weight,0),names:s,vocab:r,calls:d,callTargets:new Set(d.flatMap(i=>i.targets)),params:{label:t.params.join("/"),words:t.params.flatMap(Ae)},returns:{label:t.returns.join("/"),words:t.returns.flatMap(Ae)},kinds:new Set(t.kinds),scope:re(n)}}function Ae(e){return D(e).variants}function _r(e,t){return Math.min(...t.map(n=>Math.max(0,...n.map(r=>e.nameDocFreq.get(r)??0))))}function Mr(e,t){let n=new Set,r=o=>o.flatMap(s=>e.byToken.get(s)??[]),a=o=>{let s=o.map(r).sort((d,i)=>d.length-i.length)[0];for(let d of s??[])n.add(d)};for(let o of t.groups)for(let s of o.synonyms)a(s);for(let o of t.names)a(o.filter(s=>s.length>=2&&!Z.has(s)).map(s=>[s]));return n}var Br=/[.#:/]/;function Nr(e,t){let n=t.replace(/`/g,""),r=Br.test(n),a=r?n.split(/[.#:/]+/).filter(Boolean).at(-1)??n:n,o=e.byName.get(a)??[],s=r?o.filter(i=>Fr(e.candidates[i]).has(n)):o;if(s.length>0)return new Set(s.map(c=>Or(e.candidates[c]))).size>Pr?{probe:t,leaf:a,status:"ambiguous",targets:[]}:{probe:t,leaf:a,status:"matched",targets:s};let d=!r&&e.calledLeaves.has(n);return{probe:t,leaf:a,status:d?"matched":"unmatched",targets:[]}}function Or(e){return`${e.file}\0${e.container??""}`}function Fr(e){let t=new Set,n=[e.name];if(e.container){for(let r of[".","#","::"])t.add(`${e.container}${r}${e.name}`);n.push(`${e.container}.${e.name}`)}for(let r of[e.file,e.file.replace(/\.[^./]+$/,"")])for(let a of[":","#","/"])for(let o of n)t.add(`${r}${a}${o}`);return t}function jt(e,t,n){let r=t.candidates[n],a=e.names.some(l=>Lr(l,r.nameWords)),o=0,s=0,d=0,i=[];for(let l of e.groups){let b={label:l.labels[0],field:null};for(let p of xe){let S=l.synonyms.findIndex(g=>Ir(r.fields[p],g));if(!(S<0)){b={label:l.labels[S],field:p};break}}i.push(b),b.field&&(o+=l.weight*wr[b.field]),b.field==="name"&&(s+=l.weight,d+=1)}let c=e.totalWeight;return{index:n,match:c>0?o/c:0,nameCoverage:c>0?s/c:0,nameGroups:d,exactName:a,hits:i}}function Lr(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Ir(e,t){if(t.length===1)return t[0].some(n=>e.set.has(n));for(let n=0;n+t.length<=e.words.length;n+=1)if(t.every((r,a)=>e.variants[n+a].some(o=>r.includes(o))))return!0;return!1}function Kt(e,t,n){let r=t.candidates[n.index],a=e.calls.filter(i=>i.status==="matched"),o=a.filter(i=>r.calleeLeaves.includes(i.leaf)).map(i=>i.probe),{fit:s,note:d}=Dr(e,r);return{...n,candidate:r,callContainment:r.hasBody&&a.length>0?o.length/a.length:null,callsFound:o,fit:s,fitNote:d,specializedWords:$r(e,t,r),isCallTarget:e.callTargets.has(n.index)}}function $r(e,t,n){let r=n.fields.name;return r.words.filter((a,o)=>(t.nameDocFreq.get(a)??0)<=xr&&!Ar.has(a)&&!r.variants[o].some(s=>e.vocab.has(s)))}function Dr(e,t){if(t.kind!=="function"&&t.kind!=="method")return{fit:"unknown",note:null};let n=[Ur(e,t),Hr(e,t)].filter(a=>a!==null),r=n.find(a=>a.verdict==="conflicts")??n[0];return r?{fit:r.verdict,note:r.note}:{fit:"unknown",note:null}}function Ur(e,t){if(e.returns.words.length===0)return null;let n=t.returnsText;return n?Vt(D(n),e.returns.words)?{verdict:"fits",note:`returns ${Dt(n)}`}:{verdict:"conflicts",note:`returns ${Dt(n)}, probe expects ${e.returns.label}`}:null}function Hr(e,t){return e.params.words.length===0||t.paramsText===null?null:t.paramsText===""?{verdict:"conflicts",note:`takes no parameters, probe expects ${e.params.label}`}:Vt(D(t.paramsText),e.params.words)?{verdict:"fits",note:`parameters include ${e.params.label}`}:null}function Vt(e,t){return t.some(n=>n.some(r=>e.set.has(r)))}function Dt(e){return e.length>40?`${e.slice(0,39)}\u2026`:e}import{createHash as Yr}from"crypto";var Wr=.6,jr=.35,Gt=.5,Kr=.75,Vr=.5,Me="blocked: file-internal (not exported, no references from other files)",Be="blocked: marked @deprecated",oe=["reuse","rework","compose"];function zt(e,t,n){let{plan:r}=n,a=new Map(n.shortlist.map(i=>[i.index,i])),o=i=>{if(a.has(i))return;let c=Ht(t,r,i);c&&a.set(i,c)};for(let i of r.callTargets)o(i);let s=new Map;for(let i of[...a.values()].filter(c=>qr(r,c)))for(let c of i.candidate.calleeLeaves)for(let l of Jr(e,t,i.candidate,c)){if(l===i.index)continue;let b=s.get(l);b?b.push(i):s.set(l,[i])}for(let i of s.keys())o(i);let d=[];for(let i of a.values()){let c=Gr(r,i,s.get(i.index)??[]);c&&d.push(c)}return d.sort(Xr)}function Gr(e,t,n){let r=Yt(t),a=zr(e,t,n),o=t.exactName||t.nameCoverage>=Kr,s=t.candidate.consumable&&!t.candidate.deprecated;return a.length>0&&!o&&s?Te(t,"compose",[..._e(t),...a]):Jt(t,r)?Te(t,"reuse",_e(t)):(t.exactName||t.match>=jr)&&r.length>0?Te(t,"rework",[..._e(t),...r.map(d=>d.text)]):null}function Te(e,t,n){let r=e.exactName||(e.callContainment??0)>=Vr&&e.fit==="fits";return{candidate:e.candidate,bucket:t,tier:r?"direct":"signal",score:Le(e.exactName?Math.max(e.match,.9):e.match),why:n}}function Jt(e,t){return(e.exactName||e.match>=Wr)&&t.length===0}function qr(e,t){return Jt(t,Yt(t))&&!t.isCallTarget&&!Xt(e,t)}function Xt(e,t){return e.groups.length>=2&&t.nameGroups===1&&t.specializedWords.length===0&&t.hits.some(n=>n.field===null)}function zr(e,t,n){let r=[];t.isCallTarget&&r.push(`name matches call probe ${t.candidate.name}`),Xt(e,t)&&r.push(`part of the task: name covers 1 of ${e.groups.length} concepts`);let a=n.filter(o=>qt(o)>qt(t));if(a.length>0){let o=[...new Set(a.map(s=>s.candidate.name))].slice(0,3);r.push(`referenced inside ${o.join(", ")}`)}return r}function qt(e){return e.exactName?Math.max(e.match,.9):e.match}function Jr(e,t,n,r){return(t.byName.get(r)??[]).filter(a=>{let o=t.candidates[a];return o.file!==n.file&&!o.referencedFrom.includes(n.file)?!1:$t(e,t,a,n.file).some(([s,d])=>s>=n.startLine&&d<=n.endLine)})}function Yt(e){let{candidate:t}=e,n=[];e.fit==="conflicts"&&n.push({kind:"signature",text:`blocked: ${e.fitNote??"signature conflicts with the probes"}`}),t.consumable||n.push({kind:"file-internal",text:Me}),e.specializedWords.length>0&&n.push({kind:"specialized",text:`blocked: specialized name (${e.specializedWords.join(", ")} not in the probes)`}),t.deprecated&&n.push({kind:"deprecated",text:Be});let r=[...new Set(e.hits.flatMap(o=>o.field&&o.field!=="name"?[o.field]:[]))],a=e.exactName||e.nameCoverage>=Gt||(e.callContainment??0)>=Gt;return r.length>0&&!a&&n.push({kind:"doc-only",text:`blocked: concept appears only in ${r.join("/")}, not in the name or callees`}),n}function _e(e){let t=[];e.exactName&&t.push(`name equals probe name ${e.candidate.name}`);let n=new Map;for(let a of e.hits){if(!a.field)continue;let o=n.get(a.field)??[];o.push(a.label),n.set(a.field,o)}let r=n.get("name");r&&!e.exactName&&t.push(`name matches ${r.join("+")}`);for(let[a,o]of n)a!=="name"&&t.push(`${a} mentions ${o.join("+")}`);return e.callsFound.length>0&&t.push(`calls ${e.callsFound.join(", ")}`),e.candidate.consumable&&t.push(Ne(e.candidate)),e.fit==="fits"&&e.fitNote&&t.push(`signature fits: ${e.fitNote}`),t}function Ne(e){let t=e.referencedFrom.length,n=`referenced from ${t} ${t===1?"file":"files"}`;return e.exported?t>0?`exported, ${n}`:"exported, no references from other files":t>0?`not exported, ${n}`:"file-internal"}function Oe(e,t){return{symbolId:e.symbol,name:e.kind==="method"&&e.container?`${e.container}.${e.name}`:e.name,file:e.file,line:e.startLine+1,signature:e.signature,...t}}function Fe(e,t,n){let r=new Map;return e.filter(a=>{if(n&&a.bucket!==n)return!1;let o=r.get(a.bucket)??0;return r.set(a.bucket,o+1),o<t})}function Xr(e,t){return oe.indexOf(e.bucket)-oe.indexOf(t.bucket)||+(t.tier==="direct")-+(e.tier==="direct")||t.score-e.score||e.candidate.file.localeCompare(t.candidate.file)||e.candidate.startLine-t.candidate.startLine||e.candidate.name.localeCompare(t.candidate.name)}function Le(e){return Math.round(e*1e3)/1e3}var tn=5,nn=1200,Qr=.05,Zr=.12,eo=15,to=3,no=.5,ro=200,oo=300,Qt=1e-9;function rn(e,t,n={}){let r=Y(e),a=Ut(r,t,{scope:n.scope}),o=zt(e,r,a);return{candidates:Fe(o,n.limit??tn,n.bucket).map(s=>Oe(s.candidate,{bucket:s.bucket,tier:s.tier,score:s.score,scoreBasis:"probe-match",why:s.why})),unresolvedProbes:a.unresolvedProbes,coverage:{corpusUnits:a.corpusUnits}}}var Zt=new WeakMap;function on(e,t=nn){return sn(Y(e),t).cards}function sn(e,t){let n=Zt.get(e);n||(n=new Map,Zt.set(e,n));let r=n.get(t);if(!r){let a=e.candidates.map((s,d)=>{let i=ao(s,t);return{cardHash:so(i),text:i,candidateIndex:d}}),o=new Map;for(let s of a){let d=o.get(s.cardHash);d?d.push(s.candidateIndex):o.set(s.cardHash,[s.candidateIndex])}r={cards:a,indexesByHash:o},n.set(t,r)}return r}function so(e){return Yr("sha256").update(`card-format-${1}
1
+ import{a as at}from"./chunk-ILMHV3KM.js";import{a as mt}from"./chunk-XN3EKMLI.js";import{G as ht,a as pt,b as gt,h as Z,i as W,j as de,k as bt}from"./chunk-JNXI6NQ7.js";import{U as ot,V as st,g as he,k as nt}from"./chunk-K4S2VH42.js";import{b as Ke,c as Ve,d as Ge,q as rt}from"./chunk-EQNMD62X.js";import{D as Ze,E as et,I as tt}from"./chunk-C6WKPKCF.js";import{d as Xe,e as Ye,f as Qe}from"./chunk-DRENNWRG.js";import{b as X,c as Ee,d as it,e as dt,f as ct,i as lt,j as ut,k as ft}from"./chunk-MEUHIDI3.js";import{a as be,l as ze,m as Je}from"./chunk-5FWR5HLG.js";import{i as H,j as J,m as je}from"./chunk-T75DS2E6.js";import{b as qe}from"./chunk-YT4DVWUV.js";import{a as We}from"./chunk-RCIGX23V.js";import{a as ge,b as ie}from"./chunk-6O3KXIDL.js";import{e as He,g as pe}from"./chunk-UQYQBLJX.js";import{join as $e}from"path";import{createHash as gn}from"crypto";import{mkdirSync as Ct,mkdtempSync as bn,renameSync as hn,rmSync as kt,statSync as En,writeFileSync as wt}from"fs";import{tmpdir as yn}from"os";import{extname as Sn,join as ee,resolve as vn,sep as Cn}from"path";var kn=1024*1024,Et=500,wn=64,Rn=/\.(?:cmd|bat)$/i;async function Rt(e,t,n={}){let r=Se(e);if(!r.ok)return $(r.reason,r.detail);let a=JSON.stringify(it),o;try{Ct(t.workDir,{recursive:!0}),o=bn(ee(yn(),"codebaseiq-probe-")),e.argv.includes("{schemaFile}")&&wt(ee(o,"schema.json"),a)}catch(s){return yt(o),$("spawn-failed",`could not prepare the agent sandbox: ${te(xn(s))}`)}try{let s=ee(o,"schema.json"),d=ee(o,"output.json"),i=e.argv.includes("{outputFile}"),c=new Map([["{schemaJson}",a],["{schemaFile}",s],["{outputFile}",d]]),l=Ve(r.path,e.argv.slice(1).map(S=>c.get(S)??S)),b;try{b=await st({command:l.binary,args:l.args,label:`agent probe command ${e.name}`,timeoutMs:e.timeoutMs,maxStdoutBytes:e.maxOutputBytes,maxStderrBytes:kn,cwd:t.workDir,env:Tn(n.env??process.env),input:ct(t.description,t.languages),signal:n.signal})}catch(S){return _n(S,n.signal)}if(b.status!==0){let S=St(b.stdout),g=b.status===null?`signal ${b.signal}`:`code ${b.status}`,m=S.kind==="error"?S.detail:b.stderr.trim()||b.stdout.trim();return $("agent-error",`${e.name} exited with ${g}: ${te(m)}`)}let p=[];if(i){let S=Mn(d,e.maxOutputBytes);if(S==="too-large")return $("output-too-large",`${e.name} wrote more than ${e.maxOutputBytes} bytes.`);S!==null&&p.push(S)}p.push(b.stdout);for(let S of p){let g=St(S);if(g.kind==="error")return $("agent-error",g.detail);if(g.kind==="none")continue;let{probes:m,diagnostics:w}=Ee(g.value);return X(m)?{ok:!0,probes:m,diagnostics:w,raw:S.trim()}:$("invalid-probes",On(w))}return $("no-json",`${e.name} printed no JSON object: ${te(b.stdout.trim())}`)}finally{yt(o)}}function yt(e){if(e!==void 0)try{kt(e,{recursive:!0,force:!0,maxRetries:3})}catch{}}function xn(e){return e instanceof Error?e.message:String(e)}function $(e,t){return{ok:!1,reason:e,detail:t}}function Pn(e){let t=ut({agent:{commands:[e]}}).filter(n=>n.level==="error");return t.length>0?t.map(n=>`${n.path}: ${n.message}`).join(" "):ft.has(e.argv[0])?"argv[0] must be the executable, not a placeholder.":[e.timeoutMs,e.maxOutputBytes].every(n=>Number.isFinite(n)&&n>0)?null:"timeoutMs and maxOutputBytes must be positive numbers."}function Se(e){let t=Pn(e);if(t)return{ok:!1,reason:"misconfigured",detail:t};let n=e.argv[0],r=`argv[0] "${n}" is a .cmd/.bat shim, which cannot be started without a shell. Point argv[0] at the real executable or at a node script (.js, .mjs, .cjs).`,a=n.includes("/")||n.includes(Cn),o;if(a){o=An(vn(n));let s=ye(o);if(s==="missing")return{ok:!1,reason:"spawn-failed",detail:`argv[0] "${n}" was not found.`};if(s==="other")return{ok:!1,reason:"misconfigured",detail:`argv[0] "${n}" is not an executable file.`}}else o=Ge(n);return o===null?Ke(n)?{ok:!1,reason:"misconfigured",detail:r}:{ok:!1,reason:"spawn-failed",detail:`argv[0] "${n}" was not found on PATH.`}:process.platform==="win32"&&Rn.test(o)?{ok:!1,reason:"misconfigured",detail:r}:{ok:!0,path:o}}function An(e,t=process.platform){return t!=="win32"||Sn(e)!==""||ye(e)!=="missing"?e:[".exe",".com"].map(n=>`${e}${n}`).find(n=>ye(n)==="file")??e}function ye(e){try{return En(e).isFile()?"file":"other"}catch{return"missing"}}function Tn(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&!/^CODEBASEIQ_/i.test(n)&&(t[n]=r);return t}function _n(e,t){if(!(e instanceof ot))throw e;switch(e.kind){case"spawn":return $("spawn-failed",e.message);case"timeout":return $("timeout",e.message);case"stdout-limit":case"stderr-limit":return $("output-too-large",e.message);case"aborted":throw t?H(t,e.message):e}}function Mn(e,t){try{return pe(e,{maxBytes:t,inputKind:"agent output file"})}catch(n){return n instanceof He&&n.reason==="too-large"?"too-large":null}}function St(e){let t=vt(e);if(!t)return{kind:"none"};if(t.type!=="result")return{kind:"object",value:t};if(t.is_error===!0){let r=typeof t.result=="string"&&t.result?t.result:t.subtype;return{kind:"error",detail:te(`The agent reported an error: ${String(r??"no message")}`)}}if(Pt(t.structured_output))return{kind:"object",value:t.structured_output};let n=typeof t.result=="string"?vt(t.result):null;return n?{kind:"object",value:n}:{kind:"none"}}function vt(e){let t=e.trim();return xt(t)??Bn(t)}function xt(e){try{let t=JSON.parse(e);return Pt(t)?t:null}catch{return null}}function Bn(e){let t=/\{\s*["}]/g,n=null,r=0;for(let a=0;a<wn;){t.lastIndex=r;let o=t.exec(e);if(!o)break;let s=Nn(e,o.index),d=s===-1?null:xt(e.slice(o.index,s+1));d?(n=d,r=s+1):(r=o.index+1,a++)}return n}function Nn(e,t){let n=0,r=!1,a=!1;for(let o=t;o<e.length;o++){let s=e[o];if(r)a?a=!1:s==="\\"?a=!0:s==='"'&&(r=!1);else if(s==='"')r=!0;else if(s==="{")n++;else if(s==="}"&&--n===0)return o}return-1}function Pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function On(e){return e.length===0?"The agent returned no usable probes.":te(`The agent returned no usable probes: ${e.slice(0,3).map(t=>`${t.path||"root"}: ${t.message}`).join("; ")}`)}function te(e){return e.length>Et?`${e.slice(0,Et)}...`:e}var Fn=64*1024,Ln=3600*1e3;function At(e,t,n=Date.now){let r=(a,o)=>ee(e,`${gn("sha256").update(JSON.stringify([a,3,o])).digest("hex")}.json`);return{get(a,o){try{let s=JSON.parse(pe(r(a,o),{maxBytes:Fn,inputKind:"agent probe cache entry"}));if(typeof s.storedAt!="number"||n()-s.storedAt>=t*Ln)return;let{probes:d}=Ee(s.probes);return X(d)?d:void 0}catch{return}},set(a,o,s){let d=r(a,o),i=`${d}.${process.pid}.tmp`;try{Ct(e,{recursive:!0}),wt(i,JSON.stringify({storedAt:n(),probes:s})),hn(i,d)}catch{try{kt(i,{force:!0})}catch{}}}}}import{BlockList as In,isIP as $n}from"net";var Ce=64*1024*1024,Dn=2,Tt="embedding request aborted",Un="codebaseiq embedding canary: parse a retry delay from a config file",M=class extends Error{constructor(n,r,a){super(r);this.kind=n;this.status=a;this.name="EmbeddingClientError"}kind;status},ne=new In;for(let[e,t]of[["127.0.0.0",8],["10.0.0.0",8],["172.16.0.0",12],["192.168.0.0",16],["100.64.0.0",10],["169.254.0.0",16]])ne.addSubnet(e,t,"ipv4");ne.addAddress("::1","ipv6");ne.addSubnet("fe80::",10,"ipv6");ne.addSubnet("fc00::",7,"ipv6");var Hn=[".local",".lan",".home.arpa",".internal"];function _t(e){let t;try{t=new URL(e).hostname}catch{return!1}let n=(t.startsWith("[")?t.slice(1,-1):t).replace(/\.$/,""),r=$n(n);return r!==0?ne.check(n,r===4?"ipv4":"ipv6"):n==="localhost"||Hn.some(a=>n.endsWith(a))}function Nt(e,t={}){let n=t.fetchImpl??fetch,r=t.env??process.env,a=e.baseUrl.replace(/\/+$/,"");function o(){let l=e.apiKeyEnv?r[e.apiKeyEnv]:void 0;return l||void 0}function s(){let l;try{l=new URL(e.baseUrl)}catch{throw new M("invalid-endpoint",`embedding endpoint "${e.name}" has an invalid baseUrl`)}if(l.protocol!=="http:"&&l.protocol!=="https:")throw new M("invalid-endpoint",`embedding endpoint "${e.name}" must use http or https`);if(l.username!==""||l.password!=="")throw new M("invalid-endpoint",`embedding endpoint "${e.name}" must not embed credentials in baseUrl; use apiKeyEnv`);if(!e.allowRemote&&!_t(e.baseUrl))throw new M("remote-not-allowed",`embedding endpoint "${e.name}" is not on a private network; set allowRemote to use it`);if(l.protocol==="http:"&&o()!==void 0&&!_t(e.baseUrl))throw new M("insecure-token-transport",`embedding endpoint "${e.name}" would send its API key over plain http to a non-private host; use https`)}function d(l){let b={};l&&(b["content-type"]="application/json");let p=o();return p&&(b.authorization=`Bearer ${p}`),b}async function i(l,b,p,S){let g={model:e.model,input:l,encoding_format:"float",...e.dimensions!==void 0?{dimensions:e.dimensions}:{}},{status:m,text:w}=await Mt(n,`${a}/embeddings`,{method:"POST",headers:d(!0),body:JSON.stringify(g)},b,!0,S);if(m<200||m>=300)throw new M("http",`embeddings request failed with HTTP ${m}`,m);return Vn(w,l.length,p)}async function c(l,b,p){try{return await i(l,e.requestTimeoutMs,b,p)}catch(S){if(!Wn(S))throw S;return i(l,e.requestTimeoutMs,b,p)}}return{async checkHealth({signal:l}={}){try{s()}catch(p){return ve(p)}try{await Mt(n,`${a}/models`,{method:"GET",headers:d(!1)},e.healthTimeoutMs,!1,l)}catch(p){return l?.aborted?ve(p,l):{ok:!1,reason:"unreachable",detail:ke(p)}}let b=ge();try{let[p]=await i([e.documentPrefix+Un],e.warmTimeoutMs,{dims:e.dimensions},l);return{ok:!0,model:e.model,dimensions:p.length,latencyMs:Math.round(ge()-b),canary:p}}catch(p){return ve(p,l)}},async embed(l,b,{signal:p}={}){if(s(),l.length===0)return[];let S=b==="query"?e.queryPrefix:e.documentPrefix,g=Math.max(1,Math.floor(e.batchSize)),m=[];for(let x=0;x<l.length;x+=g)m.push(l.slice(x,x+g).map(A=>S+A));let w={dims:e.dimensions};return(await at(m,Dn,x=>c(x,w,p))).flat()}}}function Wn(e){return e instanceof M&&(e.kind==="timeout"||e.kind==="http"&&(e.status??0)>=500)}function ve(e,t){let n=ke(e);if(t?.aborted)return{ok:!1,reason:"aborted",detail:n};if(!(e instanceof M))return{ok:!1,reason:"bad-response",detail:n};switch(e.kind){case"remote-not-allowed":case"insecure-token-transport":case"invalid-endpoint":return{ok:!1,reason:e.kind,detail:n};case"network":return{ok:!1,reason:"unreachable",detail:n};case"timeout":return{ok:!1,reason:"model-loading",detail:n};case"http":return e.status===503?{ok:!1,reason:"model-loading",detail:n}:e.status===401||e.status===403?{ok:!1,reason:"unauthorized",detail:n}:{ok:!1,reason:"bad-response",detail:n};default:return{ok:!1,reason:"bad-response",detail:n}}}function ke(e){return e instanceof Error?e.message:String(e)}async function Mt(e,t,n,r,a,o){J(o,Tt);let s=new AbortController,d=setTimeout(()=>{s.abort(new M("timeout",`no response within ${r}ms`))},r),i=()=>s.abort(o?.reason);o?.addEventListener("abort",i,{once:!0});try{let c=await Ot(e(t,{...n,signal:s.signal,redirect:"error"}),s.signal);return{status:c.status,text:a?await Kn(c,s.signal):""}}catch(c){throw o?.aborted&&s.signal.reason===o.reason?H(o,Tt):c instanceof M?c:s.signal.aborted&&s.signal.reason instanceof M?s.signal.reason:new M("network",`could not reach the embeddings endpoint: ${jn(c)}`)}finally{clearTimeout(d),o?.removeEventListener("abort",i),s.abort()}}function jn(e){let t=e instanceof Error?e.cause:void 0;return typeof t?.code=="string"?t.code:ke(e)}async function Kn(e,t){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>Ce)throw Bt();if(!e.body)return"";let r=e.body.getReader(),a=[],o=0;for(;;){let{done:s,value:d}=await Ot(r.read(),t);if(s)break;if(o+=d.byteLength,o>Ce)throw r.cancel().catch(()=>{}),Bt();a.push(d)}return new TextDecoder().decode(Buffer.concat(a))}function Bt(){return new M("too-large",`embeddings response exceeded the ${Ce} byte limit`)}function Ot(e,t){return new Promise((n,r)=>{let a=()=>r(t.reason);if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",a))})}function Vn(e,t,n){let r;try{r=JSON.parse(e)}catch{throw j("response is not valid JSON")}let a=typeof r=="object"&&r!==null?r.data:void 0;if(!Array.isArray(a)||a.length!==t)throw j(`expected ${t} embeddings, received ${Array.isArray(a)?a.length:"none"}`);let o=new Array(t).fill(void 0),s=new Set;return a.forEach((d,i)=>{let c=typeof d=="object"&&d!==null?d:{},l=c.index===void 0?i:c.index;if(typeof l!="number"||!Number.isInteger(l)||l<0||l>=t||s.has(l))throw j("embedding indexes are not a permutation of the inputs");s.add(l),o[l]=c.embedding}),o.map(d=>Gn(d,n))}function Gn(e,t){if(!Array.isArray(e)||e.length===0)throw j("embedding is not a non-empty float array");if(t.dims!==void 0&&e.length!==t.dims)throw j(`embedding has ${e.length} dimensions, expected ${t.dims}`);let n=0;for(let o of e){if(typeof o!="number"||!Number.isFinite(o))throw j("embedding contains a non-finite value");n+=o*o}let r=Math.sqrt(n);if(!Number.isFinite(r)||r===0)throw j("embedding has zero or unrepresentable magnitude");t.dims=e.length;let a=new Float32Array(e.length);for(let o=0;o<e.length;o+=1)a[o]=e[o]/r;return a}function j(e){return new M("bad-response",`embeddings response rejected: ${e}`)}var xe=["name","container","doc","signature","path"],qn=1e3,zn=150,Jn=400,Xn=3,we=/@deprecated\b|#\[deprecated\b|\bdeprecated\s*[:(]/i,Ft=/^\s*(?:\/\/|\/\*|\*|#|@)/,Yn=new Set(gt()),Qn=/(?:^|\/)(?:__generated__|generated)\/|\.(?:generated|gen|g)\.[a-z0-9]+$|\.pb2?\.[a-z0-9]+$|_pb2?\.[a-z0-9]+$/i,Re=/@generated\b|\bcode generated\b.*\bdo not edit\b/i,Zn=40,er=/^(?:\/\/|--|#(?![[!\w]))/,tr=/^\s*export\s+(?:default\s+)?(?:(?:async\s+)?function|(?:abstract\s+)?class|interface|type|enum|namespace|module|const|let|var)\s+([\p{L}\p{N}_$]+)/u,nr=/^\s*export\s*\{([^}\n]*)/,rr=/[\p{L}\p{N}_$]+/gu,or=2,sr=qe("builder-candidate-corpus",{clearGroups:["whole-project","definition-catalog"]});function Y(e){return sr.get(e,()=>dr(e))}function D(e,t=2,n=Number.POSITIVE_INFINITY){let r=[],a=[],o=new Set;for(let s of W(e)){if(r.length>=n)break;if(Z.has(s.toLocaleLowerCase()))continue;let d=de(s),i=d[0];if(!(i.length<t||Z.has(i))){r.push(i),a.push(d);for(let c of d)o.add(c)}}return{words:r,variants:a,set:o}}function Pe(e){return W(e).map(bt)}function ar(e){let t=0,n=0,r=0,a=-1;for(let i=0;i<e.length&&a<0;i+=1){let c=e[i];c==="["?t+=1:c==="]"?t=Math.max(0,t-1):c==="{"?n+=1:c==="}"?n=Math.max(0,n-1):c==="<"?r+=1:c===">"&&e[i-1]!=="="&&e[i-1]!=="-"?r=Math.max(0,r-1):c==="("&&t===0&&n===0&&r===0&&(a=i)}if(a<0)return{params:null,returns:null};let o=0,s=-1;for(let i=a;i<e.length;i+=1){let c=e[i];if(c==="(")o+=1;else if(c===")"&&(o-=1,o===0)){s=i;break}}if(s<0)return{params:e.slice(a+1).trim(),returns:null};let d=e.slice(s+1).trim().replace(/^(?:=>|->|:)\s*/,"").replace(/\s+where\b.*$/,"").replace(/\s*(?:=>|=|\{|:)\s*$/,"").trim();return{params:e.slice(a+1,s).trim(),returns:d||null}}function ir(e){if(!e)return"";let t=/^\s*```(?:\w+)?\s*\n?[\s\S]*?\n?```/.exec(e);return(t?e.slice(t[0].length):e.includes("|")?e.slice(0,e.indexOf("|")):"").replace(/\s+/g," ").trim().slice(0,qn)}function dr(e){let t=new Map,n=new Set;for(let s of tt(e)){if(s.symbol.startsWith("local ")||!s.isFunctionLike&&!s.isTypeLike||e.isIgnored(s.relativePath)||he(s.relativePath)==="test")continue;let d=`${s.symbol}\0${s.relativePath}`;if(n.has(d))continue;n.add(d);let i=t.get(s.relativePath);i?i.push(s):t.set(s.relativePath,[s])}let r=[];for(let s of[...t.keys()].sort()){let d=Je(e,s);if(Cr(s,d))continue;let i=t.get(s),c=fr(e,s,d,i);for(let l of i){let b=pr(l,c);b&&r.push({definition:l,candidate:b})}}r.sort((s,d)=>s.candidate.file.localeCompare(d.candidate.file)||s.candidate.startLine-d.candidate.startLine||s.candidate.name.localeCompare(d.candidate.name));let a=ht(e,new Set,r.map(({definition:s})=>s.symbolId)),o=r.map(({definition:s,candidate:d})=>{let i=[...a.get(s.symbolId)??[]].filter(([c,l])=>c!==d.file&&l.occurrences>0&&he(c)!=="test").map(([c])=>c).sort();return{...d,referencedFrom:i,consumable:d.exported||i.length>0}});return lr(o,r.map(({definition:s})=>cr(s)))}function cr(e){let{symbolId:t,documentId:n,startLine:r,endLine:a,symbol:o,relativePath:s}=e;return{symbolId:t,documentId:n,startLine:r,endLine:a,symbol:o,relativePath:s}}function lr(e,t){let n=new Map,r=new Map,a=new Map,o=new Set;return e.forEach((s,d)=>{let i=new Set;for(let c of xe)for(let l of s.fields[c].set)i.add(l);for(let c of i)It(n,c,d);for(let c of s.fields.name.set)r.set(c,(r.get(c)??0)+1);It(a,s.name,d);for(let c of s.calleeLeaves)o.add(c)}),{candidates:e,locations:t,byToken:n,nameDocFreq:r,byName:a,calledLeaves:o}}var Lt=new WeakMap;function $t(e,t,n,r){let a=Lt.get(t);a||(a=new Map,Lt.set(t,a));let o=a.get(n);return o||(o=ur(e,t.locations[n],t.candidates[n].name),a.set(n,o)),o.get(r)??[]}function ur(e,t,n){let r=new Map;for(let o of rt(e,[t.symbolId])){if(e.isIgnored(o.relative_path))continue;let s=[o.chunk_start,o.chunk_end],d=r.get(o.relative_path);d?d.push(s):r.set(o.relative_path,[s])}let a=new Map;for(let[o,s]of r){let d=o===t.relativePath?{excludeStartLine:t.startLine,excludeEndLine:t.endLine}:{},i=nt(e,o,n,d);a.set(o,s.flatMap(([c,l])=>{let b=i.filter(p=>p>=c&&p<=l);return b.length>0?b.map(p=>[p,p]):[[c,l]]}))}return a}function It(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function fr(e,t,n,r){let a=null;return{lines:n,units:mr(e,t),endLines:r.map(o=>o.endLine).sort((o,s)=>o-s),exportedNames:()=>a??=Sr(n)}}function mr(e,t){let n=new Map,r=ze(e,t);if(!r)return n;for(let a of mt(e,t,r)?.units??[]){let o=n.get(a.name);o?o.push(a):n.set(a.name,[a])}return n}function pr(e,t){let{units:n}=t,r=e.isTypeLike?null:gr(n.get(e.leaf),e.startLine),a=!e.isTypeLike&&(r!==null||Qe(e.symbol)||Yn.has(e.kind??-1));if(!e.isTypeLike&&!a)return null;let o=Ze(et(e.documentation)),s=kr(a&&(!o||!o.includes("("))&&r?r.signature:o??r?.signature??"").slice(0,Jn),d=a&&s?ar(s):{params:null,returns:null},i=ir(e.documentation),c=br(e,r),l=e.leaf;return{symbol:e.symbol,name:l,kind:a?e.parentTypeName?"method":"function":hr(e,s),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,container:c,doc:i,signature:s||null,paramsText:d.params,returnsText:d.returns,nameWords:Pe(l),fields:{name:D(l),container:D(c??""),doc:D(i,3,zn),signature:D(s),path:D(e.relativePath.replace(/\.[^./]+$/,""))},calleeLeaves:r?.calleeLeaves??[],hasBody:r!==null,exported:r?.exported===!0||vr(t.exportedNames(),e),deprecated:Er(t,e,i)}}function gr(e,t){let n=null;for(let r of e??[]){let a=Math.abs(r.startLine-t);a<=Xn&&(!n||a<Math.abs(n.startLine-t))&&(n=r)}return n}function br(e,t){return e.parentTypeName?e.parentTypeName:e.enclosingSymbol&&Ye(e.enclosingSymbol)!=="namespace"?Xe(e.enclosingSymbol)||null:t?.container.at(-1)??null}function hr(e,t){let r=(/^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(class|struct|interface|trait|protocol)\b/.exec(t)?.[1]??pt(e.kind??0)).toLowerCase();return r==="class"||r==="struct"?"class":r==="interface"||r==="trait"||r==="protocol"?"interface":"type"}function Er(e,t,n){if(we.test(n))return!0;let{lines:r}=e,a=r[t.startLine];if(a!==void 0&&Ft.test(a)&&we.test(a))return!0;let o=yr(e.endLines,t.startLine),s=!1;for(let d=t.startLine-1;d>o;d-=1){let i=r[d]?.trim()??"";if(i===""){if(s)continue;return!1}if(!s&&!Ft.test(i))return!1;if(we.test(i))return!0;s?s=!i.includes("/*"):s=i.endsWith("*/")&&!i.includes("/*")}return!1}function yr(e,t){let n=0,r=e.length;for(;n<r;){let a=n+r>>>1;e[a]<t?n=a+1:r=a}return n>0?e[n-1]:-1}function Sr(e){let t=new Map,n=new Set;return e.forEach((r,a)=>{if(!r.includes("export"))return;let o=tr.exec(r)?.[1];if(o){let s=t.get(o);s?s.push(a):t.set(o,[a])}for(let s of nr.exec(r)?.[1]?.match(rr)??[])n.add(s)}),{declared:t,listed:n}}function vr(e,t){if(e.listed.has(t.leaf))return!0;let n=t.startLine-or;return e.declared.get(t.leaf)?.some(r=>r>=n&&r<=t.startLine)??!1}function Cr(e,t){if(Qn.test(e.replace(/\\/g,"/")))return!0;let n=!1;for(let[r,a]of t.slice(0,Zn).entries()){let o=a.trim();if(n){if(Re.test(o))return!0;n=!o.includes("*/")}else{if(o===""||r===0&&o.startsWith("#!"))continue;if(o.startsWith("/*")){if(Re.test(o))return!0;n=!o.includes("*/",2)}else if(er.test(o)){if(Re.test(o))return!0}else return!1}}return!1}function kr(e){return e.replace(/\s+/g," ").trim()}var wr={name:1,container:.8,doc:.6,signature:.5,path:.3},Rr=200,xr=3,Pr=5,Ar=new Set(["add","apply","build","calculate","call","check","compute","config","context","convert","create","data","default","delete","do","ensure","error","fetch","find","format","get","handle","has","info","init","is","item","load","make","new","normalize","option","param","parse","process","read","remove","resolve","result","run","set","state","type","update","use","validate","value","with","wrap","write"]);function Ut(e,t,n={}){let r=Tr(e,t,n.scope),a=[];for(let o of Mr(e,r)){if(!Wt(r,e.candidates[o]))continue;let s=jt(r,e,o);(s.exactName||s.match>0)&&a.push(s)}return a.sort((o,s)=>Number(s.exactName)-Number(o.exactName)||s.match-o.match||s.nameCoverage-o.nameCoverage||o.index-s.index),{plan:r,corpusUnits:e.candidates.filter(o=>Q(r.scope,o)).length,shortlist:a.slice(0,Rr).map(o=>Kt(r,e,o)),unresolvedProbes:r.calls.filter(o=>o.status!=="matched").map(o=>({probe:o.probe,status:o.status}))}}function Ht(e,t,n){return Wt(t,e.candidates[n])?Kt(t,e,jt(t,e,n)):null}function re(e){return e?e.replace(/\\/g,"/").toLowerCase():null}function Q(e,t){return!e||t.file.toLowerCase().includes(e)}function Wt(e,t){return Q(e.scope,t)?e.kinds.size===0||e.kinds.has(t.kind)?!0:(t.kind==="function"||t.kind==="method")&&(e.kinds.has("function")||e.kinds.has("method")):!1}function Tr(e,t,n){let r=new Set,a=i=>{for(let c of W(i))for(let l of de(c))r.add(l)},o=[];for(let i of t.terms){let c=[],l=[];for(let p of i){let S=Ae(p);S.length!==0&&(c.push(p),l.push(S),a(p))}if(l.length===0)continue;let b=Math.max(...l.map(p=>_r(e,p)));o.push({labels:c,synonyms:l,weight:Math.log((e.candidates.length+1)/(b+1))+1})}let s=t.names.map(Pe).filter(i=>i.length>0);for(let i of t.names)a(i);for(let i of t.calls)a(i);for(let i of[...t.params,...t.returns])a(i);let d=t.calls.map(i=>Nr(e,i));return{groups:o,totalWeight:o.reduce((i,c)=>i+c.weight,0),names:s,vocab:r,calls:d,callTargets:new Set(d.flatMap(i=>i.targets)),params:{label:t.params.join("/"),words:t.params.flatMap(Ae)},returns:{label:t.returns.join("/"),words:t.returns.flatMap(Ae)},kinds:new Set(t.kinds),scope:re(n)}}function Ae(e){return D(e).variants}function _r(e,t){return Math.min(...t.map(n=>Math.max(0,...n.map(r=>e.nameDocFreq.get(r)??0))))}function Mr(e,t){let n=new Set,r=o=>o.flatMap(s=>e.byToken.get(s)??[]),a=o=>{let s=o.map(r).sort((d,i)=>d.length-i.length)[0];for(let d of s??[])n.add(d)};for(let o of t.groups)for(let s of o.synonyms)a(s);for(let o of t.names)a(o.filter(s=>s.length>=2&&!Z.has(s)).map(s=>[s]));return n}var Br=/[.#:/]/;function Nr(e,t){let n=t.replace(/`/g,""),r=Br.test(n),a=r?n.split(/[.#:/]+/).filter(Boolean).at(-1)??n:n,o=e.byName.get(a)??[],s=r?o.filter(i=>Fr(e.candidates[i]).has(n)):o;if(s.length>0)return new Set(s.map(c=>Or(e.candidates[c]))).size>Pr?{probe:t,leaf:a,status:"ambiguous",targets:[]}:{probe:t,leaf:a,status:"matched",targets:s};let d=!r&&e.calledLeaves.has(n);return{probe:t,leaf:a,status:d?"matched":"unmatched",targets:[]}}function Or(e){return`${e.file}\0${e.container??""}`}function Fr(e){let t=new Set,n=[e.name];if(e.container){for(let r of[".","#","::"])t.add(`${e.container}${r}${e.name}`);n.push(`${e.container}.${e.name}`)}for(let r of[e.file,e.file.replace(/\.[^./]+$/,"")])for(let a of[":","#","/"])for(let o of n)t.add(`${r}${a}${o}`);return t}function jt(e,t,n){let r=t.candidates[n],a=e.names.some(l=>Lr(l,r.nameWords)),o=0,s=0,d=0,i=[];for(let l of e.groups){let b={label:l.labels[0],field:null};for(let p of xe){let S=l.synonyms.findIndex(g=>Ir(r.fields[p],g));if(!(S<0)){b={label:l.labels[S],field:p};break}}i.push(b),b.field&&(o+=l.weight*wr[b.field]),b.field==="name"&&(s+=l.weight,d+=1)}let c=e.totalWeight;return{index:n,match:c>0?o/c:0,nameCoverage:c>0?s/c:0,nameGroups:d,exactName:a,hits:i}}function Lr(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Ir(e,t){if(t.length===1)return t[0].some(n=>e.set.has(n));for(let n=0;n+t.length<=e.words.length;n+=1)if(t.every((r,a)=>e.variants[n+a].some(o=>r.includes(o))))return!0;return!1}function Kt(e,t,n){let r=t.candidates[n.index],a=e.calls.filter(i=>i.status==="matched"),o=a.filter(i=>r.calleeLeaves.includes(i.leaf)).map(i=>i.probe),{fit:s,note:d}=Dr(e,r);return{...n,candidate:r,callContainment:r.hasBody&&a.length>0?o.length/a.length:null,callsFound:o,fit:s,fitNote:d,specializedWords:$r(e,t,r),isCallTarget:e.callTargets.has(n.index)}}function $r(e,t,n){let r=n.fields.name;return r.words.filter((a,o)=>(t.nameDocFreq.get(a)??0)<=xr&&!Ar.has(a)&&!r.variants[o].some(s=>e.vocab.has(s)))}function Dr(e,t){if(t.kind!=="function"&&t.kind!=="method")return{fit:"unknown",note:null};let n=[Ur(e,t),Hr(e,t)].filter(a=>a!==null),r=n.find(a=>a.verdict==="conflicts")??n[0];return r?{fit:r.verdict,note:r.note}:{fit:"unknown",note:null}}function Ur(e,t){if(e.returns.words.length===0)return null;let n=t.returnsText;return n?Vt(D(n),e.returns.words)?{verdict:"fits",note:`returns ${Dt(n)}`}:{verdict:"conflicts",note:`returns ${Dt(n)}, probe expects ${e.returns.label}`}:null}function Hr(e,t){return e.params.words.length===0||t.paramsText===null?null:t.paramsText===""?{verdict:"conflicts",note:`takes no parameters, probe expects ${e.params.label}`}:Vt(D(t.paramsText),e.params.words)?{verdict:"fits",note:`parameters include ${e.params.label}`}:null}function Vt(e,t){return t.some(n=>n.some(r=>e.set.has(r)))}function Dt(e){return e.length>40?`${e.slice(0,39)}\u2026`:e}import{createHash as Yr}from"crypto";var Wr=.6,jr=.35,Gt=.5,Kr=.75,Vr=.5,Me="blocked: file-internal (not exported, no references from other files)",Be="blocked: marked @deprecated",oe=["reuse","rework","compose"];function zt(e,t,n){let{plan:r}=n,a=new Map(n.shortlist.map(i=>[i.index,i])),o=i=>{if(a.has(i))return;let c=Ht(t,r,i);c&&a.set(i,c)};for(let i of r.callTargets)o(i);let s=new Map;for(let i of[...a.values()].filter(c=>qr(r,c)))for(let c of i.candidate.calleeLeaves)for(let l of Jr(e,t,i.candidate,c)){if(l===i.index)continue;let b=s.get(l);b?b.push(i):s.set(l,[i])}for(let i of s.keys())o(i);let d=[];for(let i of a.values()){let c=Gr(r,i,s.get(i.index)??[]);c&&d.push(c)}return d.sort(Xr)}function Gr(e,t,n){let r=Yt(t),a=zr(e,t,n),o=t.exactName||t.nameCoverage>=Kr,s=t.candidate.consumable&&!t.candidate.deprecated;return a.length>0&&!o&&s?Te(t,"compose",[..._e(t),...a]):Jt(t,r)?Te(t,"reuse",_e(t)):(t.exactName||t.match>=jr)&&r.length>0?Te(t,"rework",[..._e(t),...r.map(d=>d.text)]):null}function Te(e,t,n){let r=e.exactName||(e.callContainment??0)>=Vr&&e.fit==="fits";return{candidate:e.candidate,bucket:t,tier:r?"direct":"signal",score:Le(e.exactName?Math.max(e.match,.9):e.match),why:n}}function Jt(e,t){return(e.exactName||e.match>=Wr)&&t.length===0}function qr(e,t){return Jt(t,Yt(t))&&!t.isCallTarget&&!Xt(e,t)}function Xt(e,t){return e.groups.length>=2&&t.nameGroups===1&&t.specializedWords.length===0&&t.hits.some(n=>n.field===null)}function zr(e,t,n){let r=[];t.isCallTarget&&r.push(`name matches call probe ${t.candidate.name}`),Xt(e,t)&&r.push(`part of the task: name covers 1 of ${e.groups.length} concepts`);let a=n.filter(o=>qt(o)>qt(t));if(a.length>0){let o=[...new Set(a.map(s=>s.candidate.name))].slice(0,3);r.push(`referenced inside ${o.join(", ")}`)}return r}function qt(e){return e.exactName?Math.max(e.match,.9):e.match}function Jr(e,t,n,r){return(t.byName.get(r)??[]).filter(a=>{let o=t.candidates[a];return o.file!==n.file&&!o.referencedFrom.includes(n.file)?!1:$t(e,t,a,n.file).some(([s,d])=>s>=n.startLine&&d<=n.endLine)})}function Yt(e){let{candidate:t}=e,n=[];e.fit==="conflicts"&&n.push({kind:"signature",text:`blocked: ${e.fitNote??"signature conflicts with the probes"}`}),t.consumable||n.push({kind:"file-internal",text:Me}),e.specializedWords.length>0&&n.push({kind:"specialized",text:`blocked: specialized name (${e.specializedWords.join(", ")} not in the probes)`}),t.deprecated&&n.push({kind:"deprecated",text:Be});let r=[...new Set(e.hits.flatMap(o=>o.field&&o.field!=="name"?[o.field]:[]))],a=e.exactName||e.nameCoverage>=Gt||(e.callContainment??0)>=Gt;return r.length>0&&!a&&n.push({kind:"doc-only",text:`blocked: concept appears only in ${r.join("/")}, not in the name or callees`}),n}function _e(e){let t=[];e.exactName&&t.push(`name equals probe name ${e.candidate.name}`);let n=new Map;for(let a of e.hits){if(!a.field)continue;let o=n.get(a.field)??[];o.push(a.label),n.set(a.field,o)}let r=n.get("name");r&&!e.exactName&&t.push(`name matches ${r.join("+")}`);for(let[a,o]of n)a!=="name"&&t.push(`${a} mentions ${o.join("+")}`);return e.callsFound.length>0&&t.push(`calls ${e.callsFound.join(", ")}`),e.candidate.consumable&&t.push(Ne(e.candidate)),e.fit==="fits"&&e.fitNote&&t.push(`signature fits: ${e.fitNote}`),t}function Ne(e){let t=e.referencedFrom.length,n=`referenced from ${t} ${t===1?"file":"files"}`;return e.exported?t>0?`exported, ${n}`:"exported, no references from other files":t>0?`not exported, ${n}`:"file-internal"}function Oe(e,t){return{symbolId:e.symbol,name:e.kind==="method"&&e.container?`${e.container}.${e.name}`:e.name,file:e.file,line:e.startLine+1,signature:e.signature,...t}}function Fe(e,t,n){let r=new Map;return e.filter(a=>{if(n&&a.bucket!==n)return!1;let o=r.get(a.bucket)??0;return r.set(a.bucket,o+1),o<t})}function Xr(e,t){return oe.indexOf(e.bucket)-oe.indexOf(t.bucket)||+(t.tier==="direct")-+(e.tier==="direct")||t.score-e.score||e.candidate.file.localeCompare(t.candidate.file)||e.candidate.startLine-t.candidate.startLine||e.candidate.name.localeCompare(t.candidate.name)}function Le(e){return Math.round(e*1e3)/1e3}var tn=5,nn=1200,Qr=.05,Zr=.12,eo=15,to=3,no=.5,ro=200,oo=300,Qt=1e-9;function rn(e,t,n={}){let r=Y(e),a=Ut(r,t,{scope:n.scope}),o=zt(e,r,a);return{candidates:Fe(o,n.limit??tn,n.bucket).map(s=>Oe(s.candidate,{bucket:s.bucket,tier:s.tier,score:s.score,scoreBasis:"probe-match",why:s.why})),unresolvedProbes:a.unresolvedProbes,coverage:{corpusUnits:a.corpusUnits}}}var Zt=new WeakMap;function on(e,t=nn){return sn(Y(e),t).cards}function sn(e,t){let n=Zt.get(e);n||(n=new Map,Zt.set(e,n));let r=n.get(t);if(!r){let a=e.candidates.map((s,d)=>{let i=ao(s,t);return{cardHash:so(i),text:i,candidateIndex:d}}),o=new Map;for(let s of a){let d=o.get(s.cardHash);d?d.push(s.candidateIndex):o.set(s.cardHash,[s.candidateIndex])}r={cards:a,indexesByHash:o},n.set(t,r)}return r}function so(e){return Yr("sha256").update(`card-format-${1}
2
2
  ${e}`).digest("hex")}function ao(e,t){let n=o=>W(o).map(s=>s.toLocaleLowerCase()).join(" "),r=`name: ${n(e.name)} | kind: ${e.kind} | in: ${e.container??""}`,a=[`signature: ${(e.signature??"").slice(0,ro)}`,`doc: ${e.doc.slice(0,oo)}`,`path: ${n(e.file.replace(/\.[^./]+$/,""))}`].join(" | ");return`${r}
3
3
  ${a}`.slice(0,t)}function an(e,t,n={}){let{topBandMargin:r=Qr,maxCardChars:a=nn}=n,o=Y(e),{indexesByHash:s}=sn(o,a),d=re(n.scope),i=new Map;for(let b of t)for(let p of s.get(b.cardHash)??[])Q(d,o.candidates[p])&&i.set(p,Math.max(i.get(p)??Number.NEGATIVE_INFINITY,b.score));if(i.size===0)return[];let c=Math.max(...i.values()),l=[];for(let[b,p]of i){let S=o.candidates[b],g=c-p,m=io(S),w=S.endLine-S.startLine+1<=eo&&S.referencedFrom.length>=to,P=g<=Zr+Qt,x=null;if(g<=r+Qt?x=m.length===0?"reuse":"rework":w&&m.length===0&&(P||p>=no)?x="compose":P&&m.length>0&&(x="rework"),!x)continue;let A=[`cosine ${p.toFixed(3)} (best ${c.toFixed(3)})`];S.consumable&&A.push(Ne(S)),x==="compose"&&A.push(`small utility: ${S.endLine-S.startLine+1} lines, referenced from ${S.referencedFrom.length} files`),A.push(...m),l.push(Oe(S,{bucket:x,tier:"signal",score:Le(p),scoreBasis:"cosine",why:A}))}return l.sort((b,p)=>oe.indexOf(b.bucket)-oe.indexOf(p.bucket)||p.score-b.score||b.file.localeCompare(p.file)||b.line-p.line||b.name.localeCompare(p.name)),Fe(l,n.limit??tn,n.bucket)}function io(e){let t=[];return e.consumable||t.push(Me),e.deprecated&&t.push(Be),t}import{mkdirSync as co}from"fs";import{dirname as lo,join as uo}from"path";import fo from"better-sqlite3";var mo="embeddings",po=1,go=720*60*60*1e3,bo=.995,ho=3600*1e3;function Eo(e){return be(JSON.stringify({model:e.model,dims:e.dims,documentPrefix:e.documentPrefix,cardFormatVersion:e.cardFormatVersion})).slice(0,16)}function ln(e,t){return be(`${e}\0${t}`).slice(0,16)}function ce(e,t){process.env.CODEBASEIQ_DEBUG&&console.error(`embedding-store: ${e}: ${t instanceof Error?t.message:String(t)}`)}function Ie(e,t,n={}){let r=n.now??ie,a=n.storeKey??Eo(t),o=uo(e,mo,`${a}.db`),s=t.dims,d=yo(o,t),i=null;function c(g,m){ce(`disabled (${g})`,m),i=null;try{d?.db.close()}catch(w){ce("close failed while disabling",w)}d=null}function l(g){return g.readDataVersion.get()}function b(g){return i&&i.dataVersion===l(g)||(i=p(g)),i}function p(g){return g.db.transaction(()=>{let m=l(g),w=g.countRows.get().count,P=new Float32Array(w*s),x=[],A=new Map;for(let N of g.readAll.iterate())new Uint8Array(P.buffer,x.length*s*4,s*4).set(N.vector),A.set(N.card_hash,x.length),x.push(N.card_hash);return{dataVersion:m,hashes:x,index:A,data:P}})()}function S(g,m){let w=0;for(let P of m)g.readUsed.get(P)!==void 0&&(w+=1);return w}return{get available(){return d!==null},key:a,path:o,verifyCanary(g){if(!d)return"first";try{let m=d.readCanary.get();return m?Co(vo(m.value),g)>=bo?"match":"drift":(d.writeCanary.run(cn(g)),"first")}catch(m){return c("canary",m),"first"}},missing(g){let m=[...new Set(g)];if(!d)return m;try{let w=[],P=[],x=r()-ho;for(let A of m){let N=d.readUsed.get(A);N?N.last_used_at<x&&P.push(A):w.push(A)}if(P.length>0){let A=d,N=r();A.db.transaction(()=>{for(let O of P)A.touch.run(N,O)})()}return w}catch(w){return c("missing",w),m}},put(g){for(let m of g)if(m.vector.length!==s)throw new RangeError(`vector for ${m.cardHash} has ${m.vector.length} dimensions, store holds ${s}`);if(!(!d||g.length===0))try{let m=d,w=r();m.db.transaction(()=>{for(let P of g)m.upsert.run(P.cardHash,w,w,cn(P.vector))})(),i=null}catch(m){c("put",m)}},topK(g,m,w){if(g.length!==s)throw new RangeError(`query vector has ${g.length} dimensions, store holds ${s}`);if(!d||m<=0)return[];let P;try{P=b(d)}catch(B){return c("topK",B),[]}let{hashes:x,index:A,data:N}=P,O=[],ae=B=>{let I=x[B],K=0,fe=B*s;for(let G=0;G<s;G+=1)K+=N[fe+G]*g[G];if(O.length===m&&!dn(K,I,O[m-1]))return;let V=O.length;for(;V>0&&dn(K,I,O[V-1]);)V-=1;O.splice(V,0,{cardHash:I,score:K}),O.length>m&&O.pop()};if(w)for(let B of w){let I=A.get(B);I!==void 0&&ae(I)}else for(let B=0;B<x.length;B+=1)ae(B);return O},coverage(g){let m=new Set(g);if(m.size===0)return 1;if(!d)return 0;try{return S(d,m)/m.size}catch(w){return c("coverage",w),0}},prune(g={}){if(!d)return 0;try{let m=d,w=g.unusedForMs??go,P=m.db.transaction(()=>{let x=m.deleteUnusedBefore.run(r()-w).changes;if(g.maxRows!==void 0){let A=m.countRows.get().count;A>g.maxRows&&(x+=m.deleteOldest.run(A-g.maxRows).changes)}return x})();return P>0&&(i=null),P}catch(m){return c("prune",m),0}},async withRefreshLock(g){if(!d)return{acquired:!1};let m=await je(`${o}.refresh.lock`);if(!m)return{acquired:!1};try{return{acquired:!0,value:await g()}}finally{m.release()}},close(){i=null;try{d?.db.close()}catch(g){ce("close failed",g)}d=null}}}function dn(e,t,n){return e>n.score||e===n.score&&t<n.cardHash}function yo(e,t){let n;try{return co(lo(e),{recursive:!0}),n=new fo(We(e)),n.pragma("busy_timeout = 5000"),n.pragma("journal_mode = WAL"),n.pragma("synchronous = NORMAL"),n.exec(`
4
4
  CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value) WITHOUT ROWID;
@@ -11,4 +11,4 @@ ${a}`.slice(0,t)}function an(e,t,n={}){let{topBandMargin:r=Qr,maxCardChars:a=nn}
11
11
  `),So(n,t),{db:n,readDataVersion:n.prepare("PRAGMA data_version").pluck(),readCanary:n.prepare("SELECT value FROM meta WHERE key = 'canary'"),writeCanary:n.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES ('canary', ?)"),readUsed:n.prepare("SELECT last_used_at FROM vectors WHERE card_hash = ?"),touch:n.prepare("UPDATE vectors SET last_used_at = ? WHERE card_hash = ?"),upsert:n.prepare("INSERT OR REPLACE INTO vectors (card_hash, embedded_at, last_used_at, vector) VALUES (?, ?, ?, ?)"),countRows:n.prepare("SELECT COUNT(*) AS count FROM vectors"),readAll:n.prepare("SELECT card_hash, vector FROM vectors"),deleteUnusedBefore:n.prepare("DELETE FROM vectors WHERE last_used_at < ?"),deleteOldest:n.prepare(`DELETE FROM vectors WHERE card_hash IN (
12
12
  SELECT card_hash FROM vectors ORDER BY last_used_at ASC, embedded_at ASC, card_hash ASC LIMIT ?
13
13
  )`)}}catch(r){ce("disabled (open failed)",r);try{n?.close()}catch{}return null}}function So(e,t){let n={schema_version:String(po),model:t.model,dims:String(t.dims),document_prefix:t.documentPrefix,card_format_version:String(t.cardFormatVersion)};e.transaction(()=>{let r=new Map(e.prepare("SELECT key, value FROM meta").all().map(s=>[s.key,s.value]));if(Object.entries(n).every(([s,d])=>r.get(s)===d))return;e.exec("DELETE FROM vectors; DELETE FROM meta;");let o=e.prepare("INSERT INTO meta (key, value) VALUES (?, ?)");for(let[s,d]of Object.entries(n))o.run(s,d)}).immediate()}function cn(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function vo(e){return new Float32Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))}function Co(e,t){if(e.length!==t.length)return 0;let n=0,r=0,a=0;for(let o=0;o<e.length;o+=1)n+=e[o]*t[o],r+=e[o]*e[o],a+=t[o]*t[o];return r===0||a===0?0:n/Math.sqrt(r*a)}var ko="builder";function $s(e){return $e(e,ko)}var wo=.8,un="inside an agent session: pass probes (--term/--name/--calls) instead of a description",Ro=3e4,xo=6e4,Po=2,Ao=50,To=12,De=2e3,_o=5,se="builder query aborted",Mo=2147483647;function Bo(e){return e>=De?`vector search returns at most ${De} hits; lower-ranked units are not listed`:void 0}function Ds(e){let{settings:t,storeRoot:n,languages:r}=e,a=e.env??process.env,o=e.now??ie,s=new Map,d;function i(u){let f=e.openDb();try{return u(f)}finally{e.closeDb?.(f)}}function c(){return Object.entries(a).some(([u,f])=>f!==void 0&&(u==="CLAUDECODE"||u.startsWith("CODEX_")))}function l(u){let f=s.get(u.name);return f||(f={client:Nt(u,{fetchImpl:e.fetchImpl,env:a})},s.set(u.name,f)),f}function b(u,f,h){u.health=void 0,u.failure={state:f,detail:h,openUntil:o()+xo}}async function p(u,f,h=!1){let E=l(u),v=o();if(!h&&E.failure&&v<E.failure.openUntil){let k=Math.ceil((E.failure.openUntil-v)/1e3);return{ok:!1,state:E.failure.state,detail:`${E.failure.detail} (not retried for another ${k}s)`}}let C=!h&&E.health!==void 0&&v-E.health.checkedAt<Ro,y;if(C)y=E.health.value;else{let k=await E.client.checkHealth({signal:f});if(!k.ok){J(f,se);let T=No(k.reason);return b(E,T,k.detail),{ok:!1,state:T,detail:k.detail}}y=k,E.health={value:k,checkedAt:o()},E.failure=void 0}let R=S(E,u,y,!C);return R.ok?{ok:!0,endpoint:u,store:R.held.store,client:E.client,...R.held.forked?{note:`model weights differ from the shared ${u.model} store; using a store forked for ${u.name}`}:{}}:R}function S(u,f,h,E){let v=u.held;if(v&&v.dims===h.dimensions&&(!E||v.store.verifyCanary(h.canary)!=="drift"))return{ok:!0,held:v};v?.store.close(),u.held=void 0;let C={model:f.model,dims:h.dimensions,documentPrefix:f.documentPrefix,cardFormatVersion:1},y=Ie(n,C);if(!y.available)return y.close(),{ok:!1,state:"degraded",detail:`the vector store ${y.path} could not be opened`};if(y.verifyCanary(h.canary)!=="drift")return u.held={store:y,dims:h.dimensions,forked:!1},{ok:!0,held:u.held};let R=y.key;y.close();let k=Ie(n,C,{storeKey:ln(R,f.name)});return!k.available||k.verifyCanary(h.canary)==="drift"?(k.close(),{ok:!1,state:"degraded",detail:`model weights for ${f.model} keep changing between runs`}):(u.held={store:k,dims:h.dimensions,forked:!0},{ok:!0,held:u.held})}function g(u){return i(f=>{let h=on(f,t.maxCardChars),E=new Map;for(let y of h)E.has(y.cardHash)||E.set(y.cardHash,y.text);let v=re(u),C=null;if(v){let{candidates:y}=Y(f);C=new Set(h.filter(R=>Q(v,y[R.candidateIndex])).map(R=>R.cardHash))}return{hashes:h.map(y=>y.cardHash),textByHash:E,scopedHashes:C}})}function m(u,f){let h=new Set(u.missing(f.hashes)),E=f.hashes.filter(v=>!h.has(v)).length;return{embeddedUnits:E,fraction:f.hashes.length===0?1:E/f.hashes.length}}async function w(u,f,h,E){let{endpoint:v,store:C,client:y}=u,R=C.missing(f.hashes);if(R.length===0)return{embedded:0,budgetExhausted:!1};let k=AbortSignal.timeout(Math.min(E,Mo)),T=h?AbortSignal.any([h,k]):k,F=Math.max(1,Math.floor(v.batchSize))*Po,_={embedded:0,budgetExhausted:!1};return(await C.withRefreshLock(async()=>{for(let q=0;q<R.length;q+=F){let z=R.slice(q,q+F);try{let U=await y.embed(z.map(L=>f.textByHash.get(L)),"document",{signal:T});C.put(z.map((L,me)=>({cardHash:L,vector:U[me]}))),_.embedded+=z.length}catch(U){if(h?.aborted)throw H(h,se);if(k.aborted){_.budgetExhausted=!0;return}b(l(v),"degraded",ue(U)),_.note=`embedding stopped: ${ue(U)}`;return}}})).acquired?_.embedded>0&&C.prune():_.note="another process is already embedding this repository",_}async function P(u,f,h,E){let v=await p(u,E);if(!v.ok)return{kind:"failed",reason:`${v.state}: ${v.detail}`};let C=g(f.scope),y=await w(v,C,E,t.indexBudgetMs),{embeddedUnits:R,fraction:k}=m(v.store,C),T;try{let[L]=await v.client.embed([h],"query",{signal:E}),me=Math.min(De,Math.max(Ao,(f.limit??_o)*To));T=v.store.topK(L,me,C.scopedHashes??new Set(C.hashes))}catch(L){if(E?.aborted)throw H(E,se);return b(l(u),"degraded",ue(L)),{kind:"failed",reason:`degraded: ${ue(L)}`}}let F=i(L=>an(L,T,{topBandMargin:t.topBandMargin,maxCardChars:t.maxCardChars,limit:f.limit,scope:f.scope,bucket:f.bucket})),_=C.hashes.length,Ue=R<_?`partial embeddings: ${R} of ${_} units (${le(k)})`:void 0,q=y.budgetExhausted?`index budget of ${t.indexBudgetMs} ms used up`:void 0,z=[v.note,Ue,q,y.note,Bo(T.length)].filter(L=>L!==void 0),U={provider:`embeddings:${u.name}`,probes:null,unresolvedProbes:[],candidates:F,coverage:{corpusUnits:_,embeddedUnits:R,...z.length>0?{note:z.join("; ")}:{}}};return k>=t.minCoverage?{kind:"answer",answer:U}:{kind:"degraded",answer:U,fraction:k,reason:`degraded: embedded ${R} of ${_} units (${le(k)}), below the ${le(t.minCoverage)} minimum`}}function x(){return d??=At($e(n,"agent-probes"),t.cacheTtlHours,o),d}async function A(u,f,h,E){if(c())return{kind:"failed",reason:un};let v=x(),C=v.get(u.argv,h);if(!C){let y=await Rt(u,{description:h,languages:r,workDir:$e(n,"agent-sandbox")},{signal:E,env:a});if(!y.ok)return{kind:"failed",reason:`${y.reason}: ${y.detail}`};C=y.probes,v.set(u.argv,h,C)}return{kind:"answer",answer:{provider:`agent:${u.name}`,...N(f,C)}}}function N(u,f){let h=i(E=>rn(E,f,{limit:u.limit,scope:u.scope,bucket:u.bucket}));return{probes:f,unresolvedProbes:h.unresolvedProbes,candidates:h.candidates,coverage:h.coverage}}function O(u){return u==="agent"?t.agents.map(f=>({kind:"agent",name:f.name})):u==="embeddings"?t.endpoints.map(f=>({kind:"embeddings",name:f.name})):t.chain}async function ae(u,f,h,E){if(u.kind==="agent"){let C=t.agents.find(y=>y.name===u.name);return C?A(C,f,h,E):{kind:"failed",reason:"not configured"}}let v=t.endpoints.find(C=>C.name===u.name);return v?P(v,f,h,E):{kind:"failed",reason:"not configured"}}function B(u,f){return{...u,fallbacksTried:f,evidence:"heuristic"}}function I(u,f){return B({provider:"none",probes:null,unresolvedProbes:[],candidates:[],coverage:{corpusUnits:0,note:f}},u)}async function K(u,f={}){let{signal:h}=f;J(h,se);let E=u.mode??t.mode;if(u.probes&&X(u.probes)&&E!=="embeddings")return B({provider:"agent:caller",...N(u,u.probes)},[]);let v=dt(u.description?.trim()??"").trim();if(v===""){let k=E==="embeddings"&&u.probes&&X(u.probes)?"embeddings mode ranks a description; probes are not embedded":"no description or probes were given";return I([{provider:"request",reason:k}],"nothing to look up")}let C=O(E);if(C.length===0)return I([{provider:E,reason:"no providers are configured for this mode"}],"no provider ran");let y=[],R=[];for(let k of C){J(h,se);let T=await ae(k,u,v,h);if(T.kind==="answer")return B(T.answer,y);let F={provider:lt(k),reason:T.reason};y.push(F),T.kind==="degraded"&&R.push({entry:F,answer:T.answer,fraction:T.fraction})}if(R.length>0){let k=R.reduce((T,F)=>F.fraction>T.fraction?F:T);return B(k.answer,y.filter(T=>T!==k.entry))}return I(y,"no provider answered")}function fe(u){let f=`agent:${u.name}`;if(c())return{provider:f,state:"skipped",detail:un};let h=Se(u);return h.ok?{provider:f,state:"ok",detail:`runs ${u.argv[0]} with a ${Math.round(u.timeoutMs/1e3)}s timeout`}:{provider:f,state:h.reason==="misconfigured"?"misconfigured":"unreachable",detail:h.detail}}async function V(u,f){let h=`embeddings:${u.name}`,E=await p(u,f,!0);if(!E.ok)return{provider:h,state:E.state,detail:E.detail};let v=g(void 0),{embeddedUnits:C,fraction:y}=m(E.store,v),R=`${u.model} reachable; embedded ${C} of ${v.hashes.length} units (${le(y)})`;return{provider:h,state:y>=t.minCoverage?"ok":"degraded",detail:E.note?`${R}; ${E.note}`:R,coverage:y}}async function G(u={}){let f=[];for(let h of t.endpoints)f.push(await V(h,u.signal));for(let h of t.agents)f.push(fe(h));return f}async function fn(u={}){let{endpoint:f,signal:h,endsAt:E,budgetMs:v=t.indexBudgetMs}=u,C=f===void 0?t.endpoints:t.endpoints.filter(R=>R.name===f);if(C.length===0)throw new Error(f===void 0?"No embeddings endpoint is configured.":`No embeddings endpoint is named ${f}.`);let y=[];for(let R of C){let k=await p(R,h);if(!k.ok){y.push(`embeddings:${R.name} ${k.state}: ${k.detail}`);continue}let T=g(void 0),F=E===void 0?v:Math.max(1,Math.floor((E-o())*wo)),_=await w(k,T,h,F);return{provider:`embeddings:${R.name}`,embedded:_.embedded,coverage:m(k.store,T).fraction,budgetExhausted:_.budgetExhausted,..._.note?{note:_.note}:{}}}throw new Error(`No embeddings endpoint could be refreshed: ${y.join("; ")}`)}function mn(){for(let u of s.values())u.held?.store.close(),u.held=void 0}return{query:K,providerStatus:G,refreshEmbeddings:fn,close:mn}}function No(e){switch(e){case"unreachable":return"unreachable";case"remote-not-allowed":case"insecure-token-transport":case"invalid-endpoint":case"unauthorized":return"misconfigured";default:return"degraded"}}function le(e){return`${Math.round(e*100)}%`}function ue(e){return e instanceof Error?e.message:String(e)}export{$s as a,Ds as b};
14
- //# sourceMappingURL=chunk-RJVAPMHF.js.map
14
+ //# sourceMappingURL=chunk-PIFYOWS4.js.map
@@ -1,2 +1,2 @@
1
- import{c as C}from"./chunk-HENP2O4A.js";import{a as k}from"./chunk-6VREELBC.js";import{f as w,m as P,n as Q}from"./chunk-J3GLP7Q5.js";import{o as T}from"./chunk-J7AMBVWF.js";import{d as x}from"./chunk-GVAF222T.js";import{f as g}from"./chunk-F74LZWCE.js";import{z as b}from"./chunk-ICUL7XRT.js";function Y(e,n={}){let{samples:o=50,scope:s,maxDisagreements:u=5}=n,c=new C(e),l=F(c.productionCallableDefinitions({scope:s,minLoc:2,requireFunctionLikeSymbol:!0}),o),a=U(e,l);if(l.length===0||!a)return{available:!1,sampleSize:l.length,oracleCoverage:0,scores:[],topDisagreements:[]};let t={references:M(),callees:M()},r=[],m=0,d=a==="semantic"?P(e,l):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},y=a==="semantic"?Q(e,l):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},O=a==="source"?N(e,c,l):null;for(let i of l){let p=S(i,a==="semantic"?(d.rows.get(i.symbolId)??[]).map(f=>f.file):[...O?.referencesBySymbolId.get(i.symbolId)??[]]),E=S(i,a==="semantic"?(y.rows.get(i.symbolId)??[]).map(f=>f.file):[...O?.calleesBySymbolId.get(i.symbolId)??[]]),A=a!=="semantic"||!d.incompleteSymbolIds.has(i.symbolId)&&!d.unavailableSymbolIds.has(i.symbolId),D=a!=="semantic"||!y.incompleteSymbolIds.has(i.symbolId)&&!y.unavailableSymbolIds.has(i.symbolId);A&&D&&(m+=1);let R=S(i,T(e,i,{semanticEvidence:k}).map(f=>f.file)),B=S(i,(c.calleeMap([i],{semantic:!1}).get(i.symbolId)??[]).map(f=>f.file)),K=h(a,"references"),z=h(a,"callees");A?j(t.references,i,"references",R,p,K,r):t.references.skippedOracleUnavailable+=1,D?j(t.callees,i,"callees",B,E,z,r):t.callees.skippedOracleUnavailable+=1}return r.sort((i,p)=>p.cheapOnly.length+p.oracleOnly.length-(i.cheapOnly.length+i.oracleOnly.length)),{available:!0,sampleSize:l.length,oracleCoverage:l.length>0?v(m/l.length):0,oracleKind:a,scores:["references","callees"].map(i=>q(i,t[i],a)),topDisagreements:r.slice(0,u)}}function M(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0,skippedOracleUnavailable:0}}function F(e,n){let o=[...e].sort((c,l)=>c.symbolId-l.symbolId);if(o.length<=n)return o;let s=o.length/n,u=[];for(let c=0;c<n;c++)u.push(o[Math.floor(c*s)]);return u}function U(e,n){let o=n[0];if(!o)return null;if(I(e,o))return"source";try{if(w(e).capability("semantic-references",o.relativePath).available)return"semantic"}catch{}return n.some(s=>I(e,s))?"source":null}function S(e,n){let o=new Set;for(let s of n)s!==e.relativePath&&o.add(s);return o}function j(e,n,o,s,u,c,l){if(!c&&u.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=s.size,e.oracleTotal+=u.size;let a=[],t=[];for(let r of s)u.has(r)?e.agreed+=1:a.push(r);for(let r of u)s.has(r)||t.push(r);(a.length>0||t.length>0)&&l.push({symbol:x(n.symbol),question:o,cheapOnly:a,oracleOnly:t})}var _={references:!0,callees:!1};function q(e,n,o){let s=n.oracleTotal>0?n.agreed/n.oracleTotal:1,u=n.cheapTotal-n.agreed,c=h(o,e);return{question:e,comparedSymbols:n.comparedSymbols,precision:c&&n.cheapTotal>0?v(n.agreed/n.cheapTotal):null,recall:v(s),unverified:u,skippedOraclePartial:n.skippedOraclePartial,skippedOracleUnavailable:n.skippedOracleUnavailable}}function h(e,n){return e==="semantic"?_[n]:!1}function I(e,n){return b(n.relativePath)==="clojure"&&g(e,n.relativePath)!==null}function N(e,n,o){let s=new Map,u=new Map,c=o.filter(t=>I(e,t)),l=new Map;for(let t of c){let r=l.get(t.leaf)??[];r.push(t),l.set(t.leaf,r)}for(let t of n.sourceFiles()){if(b(t)!=="clojure")continue;let r=g(e,t);if(r)for(let m of r.fileIdentifiers)for(let d of l.get(m)??[])L(s,d.symbolId,t)}let a=new Map;for(let t of n.scopedDefinitions()){if(b(t.relativePath)!=="clojure")continue;let r=a.get(t.leaf)??[];r.push(t),a.set(t.leaf,r)}for(let t of c){let r=g(e,t.relativePath);if(r){for(let m of r.callSites)if(!(m.line<t.startLine||m.line>t.endLine))for(let d of a.get(m.calleeLeaf)??[])L(u,t.symbolId,d.relativePath)}}return{referencesBySymbolId:s,calleesBySymbolId:u}}function L(e,n,o){let s=e.get(n);if(s){s.add(o);return}e.set(n,new Set([o]))}function v(e){return Math.round(e*1e3)/1e3}export{Y as a};
2
- //# sourceMappingURL=chunk-CR3OG6SQ.js.map
1
+ import{c as C}from"./chunk-BPKNP3KZ.js";import{a as k}from"./chunk-57OPIQFM.js";import{f as w,m as P,n as Q}from"./chunk-KLX6NSWT.js";import{o as T}from"./chunk-J7AMBVWF.js";import{d as x}from"./chunk-GVAF222T.js";import{f as g}from"./chunk-F74LZWCE.js";import{z as b}from"./chunk-ICUL7XRT.js";function Y(e,n={}){let{samples:o=50,scope:s,maxDisagreements:u=5}=n,c=new C(e),l=F(c.productionCallableDefinitions({scope:s,minLoc:2,requireFunctionLikeSymbol:!0}),o),a=U(e,l);if(l.length===0||!a)return{available:!1,sampleSize:l.length,oracleCoverage:0,scores:[],topDisagreements:[]};let t={references:M(),callees:M()},r=[],m=0,d=a==="semantic"?P(e,l):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},y=a==="semantic"?Q(e,l):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},O=a==="source"?N(e,c,l):null;for(let i of l){let p=S(i,a==="semantic"?(d.rows.get(i.symbolId)??[]).map(f=>f.file):[...O?.referencesBySymbolId.get(i.symbolId)??[]]),E=S(i,a==="semantic"?(y.rows.get(i.symbolId)??[]).map(f=>f.file):[...O?.calleesBySymbolId.get(i.symbolId)??[]]),A=a!=="semantic"||!d.incompleteSymbolIds.has(i.symbolId)&&!d.unavailableSymbolIds.has(i.symbolId),D=a!=="semantic"||!y.incompleteSymbolIds.has(i.symbolId)&&!y.unavailableSymbolIds.has(i.symbolId);A&&D&&(m+=1);let R=S(i,T(e,i,{semanticEvidence:k}).map(f=>f.file)),B=S(i,(c.calleeMap([i],{semantic:!1}).get(i.symbolId)??[]).map(f=>f.file)),K=h(a,"references"),z=h(a,"callees");A?j(t.references,i,"references",R,p,K,r):t.references.skippedOracleUnavailable+=1,D?j(t.callees,i,"callees",B,E,z,r):t.callees.skippedOracleUnavailable+=1}return r.sort((i,p)=>p.cheapOnly.length+p.oracleOnly.length-(i.cheapOnly.length+i.oracleOnly.length)),{available:!0,sampleSize:l.length,oracleCoverage:l.length>0?v(m/l.length):0,oracleKind:a,scores:["references","callees"].map(i=>q(i,t[i],a)),topDisagreements:r.slice(0,u)}}function M(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0,skippedOracleUnavailable:0}}function F(e,n){let o=[...e].sort((c,l)=>c.symbolId-l.symbolId);if(o.length<=n)return o;let s=o.length/n,u=[];for(let c=0;c<n;c++)u.push(o[Math.floor(c*s)]);return u}function U(e,n){let o=n[0];if(!o)return null;if(I(e,o))return"source";try{if(w(e).capability("semantic-references",o.relativePath).available)return"semantic"}catch{}return n.some(s=>I(e,s))?"source":null}function S(e,n){let o=new Set;for(let s of n)s!==e.relativePath&&o.add(s);return o}function j(e,n,o,s,u,c,l){if(!c&&u.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=s.size,e.oracleTotal+=u.size;let a=[],t=[];for(let r of s)u.has(r)?e.agreed+=1:a.push(r);for(let r of u)s.has(r)||t.push(r);(a.length>0||t.length>0)&&l.push({symbol:x(n.symbol),question:o,cheapOnly:a,oracleOnly:t})}var _={references:!0,callees:!1};function q(e,n,o){let s=n.oracleTotal>0?n.agreed/n.oracleTotal:1,u=n.cheapTotal-n.agreed,c=h(o,e);return{question:e,comparedSymbols:n.comparedSymbols,precision:c&&n.cheapTotal>0?v(n.agreed/n.cheapTotal):null,recall:v(s),unverified:u,skippedOraclePartial:n.skippedOraclePartial,skippedOracleUnavailable:n.skippedOracleUnavailable}}function h(e,n){return e==="semantic"?_[n]:!1}function I(e,n){return b(n.relativePath)==="clojure"&&g(e,n.relativePath)!==null}function N(e,n,o){let s=new Map,u=new Map,c=o.filter(t=>I(e,t)),l=new Map;for(let t of c){let r=l.get(t.leaf)??[];r.push(t),l.set(t.leaf,r)}for(let t of n.sourceFiles()){if(b(t)!=="clojure")continue;let r=g(e,t);if(r)for(let m of r.fileIdentifiers)for(let d of l.get(m)??[])L(s,d.symbolId,t)}let a=new Map;for(let t of n.scopedDefinitions()){if(b(t.relativePath)!=="clojure")continue;let r=a.get(t.leaf)??[];r.push(t),a.set(t.leaf,r)}for(let t of c){let r=g(e,t.relativePath);if(r){for(let m of r.callSites)if(!(m.line<t.startLine||m.line>t.endLine))for(let d of a.get(m.calleeLeaf)??[])L(u,t.symbolId,d.relativePath)}}return{referencesBySymbolId:s,calleesBySymbolId:u}}function L(e,n,o){let s=e.get(n);if(s){s.add(o);return}e.set(n,new Set([o]))}function v(e){return Math.round(e*1e3)/1e3}export{Y as a};
2
+ //# sourceMappingURL=chunk-PTR3EOXC.js.map
@@ -1,2 +1,2 @@
1
- import{k as x}from"./chunk-J3GLP7Q5.js";import{a as y,e as b}from"./chunk-GVAF222T.js";import{z as v}from"./chunk-ICUL7XRT.js";import{g,l as D,m as F,t as E,v as I}from"./chunk-7GAK2F3H.js";import{a as _,d as p}from"./chunk-3LCDIREB.js";import{spawnSync as P}from"child_process";import{createHash as U}from"crypto";import{existsSync as k}from"fs";import{dirname as L,join as T}from"path";import{fileURLToPath as j}from"url";var R=g("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),M=E({kind:"consumer-file-usage",invalidation:I("consumer-file-usage"),serialize:Q,deserialize:W});function Le(e,n){return{forDefinitions(r,i){return B(e,n,r,i)}}}function Me(e){let n=new Map;for(let[r,i]of e)n.set(r,new Set(i.files.map(t=>t.file)));return n}function Ne(e,n,r){return w(e,n,r).partition}function B(e,n,r,i){let t=h(r.length),s=_()?F(e):null,a=s?V(r,i,s):void 0,o=a?{workIdentity:a,workOutcome:"computed"}:{};return p("consumer-evidence.product",()=>{let l=p("consumer-evidence.provenance",()=>z(e,n,r,i),()=>({...o,definitions:r.length,semantic:i.semantic,sourceFallback:i.sourceFallback!==!1})),u=new Map;t={...t,...l.counters};let c=q(r,l.sources);return p("consumer-evidence.classify",()=>{let f=Y(e,r,l.sources,c);for(let d of r){let m=f.get(d.symbolId)??$();t.realFiles+=m.partition.realConsumers.length,t.reexportOnlyFiles+=m.partition.barrelConsumers,t.importOnlyFiles+=m.partition.importOnlyConsumers,u.set(d.symbolId,{definition:d,files:m.files,semanticIncomplete:l.incompleteSymbolIds.has(d.symbolId),semanticUnavailable:l.unavailableSymbolIds.has(d.symbolId),...m.partition})}},()=>({...o,...c,realFiles:t.realFiles,reexportOnlyFiles:t.reexportOnlyFiles,importOnlyFiles:t.importOnlyFiles})),u},()=>({...o,...t}))}function V(e,n,r){let i=U("sha256").update("consumer-evidence-v3-calibrated-semantic\0").update(r).update("\0").update(n.semantic?"semantic\0":"indexed\0").update(n.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let t of e.map(s=>s.symbol).sort())i.update("\0").update(t);return i.digest("hex").slice(0,24)}function h(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function z(e,n,r,i){let t=h(r.length),s=new Map,a=new Set,o=new Set;if(S(s,t,"indexed",n.crossFileCallerMap(r,{semantic:!1})),i.semantic){let l=x(e,r);S(s,t,"semantic",l.callers);for(let u of l.incompleteSymbolIds)a.add(u);for(let u of l.unavailableSymbolIds)o.add(u)}return i.sourceFallback!==!1&&S(s,t,"source-fallback",n.sourceFallbackCallerFiles(r)),t.totalFiles=[...s.values()].reduce((l,u)=>l+u.size,0),{sources:s,counters:t,incompleteSymbolIds:a,unavailableSymbolIds:o}}function q(e,n){return{definitions:e.length,consumerFiles:[...n.values()].reduce((r,i)=>r+i.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function S(e,n,r,i){let t=0;for(let[s,a]of i){let o=e.get(s);o||(o=new Map,e.set(s,o));for(let l of a){t++;let u=o.get(l)??new Set;u.add(r),o.set(l,u)}}r==="indexed"?n.indexedFiles+=t:r==="semantic"?n.semanticFiles+=t:n.fallbackFiles+=t}function Y(e,n,r,i){let t=re(e,n,r,i);return t||H(e,n,r)}function H(e,n,r){let i=new Map;for(let t of n){let s=r.get(t.symbolId)??new Map;i.set(t.symbolId,w(e,t,[...s.keys()],s))}return i}function w(e,n,r,i=new Map){let t=[],s=0,a=0,o=b(n.symbol),l=[];for(let u of r){let c;X(e,u,n.relativePath,o)?(s++,c="reexport-only"):J(e,u,o)?(a++,c="import-only"):(t.push(u),c="real"),l.push({file:u,sources:[...i.get(u)??[]],classification:c})}return{partition:{realConsumers:t,barrelConsumers:s,importOnlyConsumers:a},files:l}}function $(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function J(e,n,r){if(!r)return!1;let i=v(n);if(!i)return!1;let t=R.get(e,n,()=>A(e,n,i));return t.importedLeaves.has(r)&&!t.usedLeaves.has(r)}function A(e,n,r){let i=y(e).forFile(n,{text:!0,ast:!0}),t=i.text;if(!t)return G();let s=D(e,n,t),a=M.read(e,n,s);if(a)return a;let o=K(i.ast,r);return M.write(e,n,s,o),o}function K(e,n){let r=new Set,i=new Set;if(!e)return{importedLeaves:r,usedLeaves:i};let t=n==="rust"?new Set(["use_declaration"]):n==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),s=(a,o)=>{let l=o||t.has(a.type);(a.type==="identifier"||a.type==="type_identifier"||a.type==="property_identifier"||a.type==="field_identifier")&&(l?r.add(a.text):i.add(a.text));for(let u of a.children)s(u,l)};return s(e.rootNode,!1),{importedLeaves:r,usedLeaves:i}}function G(){return{importedLeaves:new Set,usedLeaves:new Set}}function Q(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function W(e){try{let n=JSON.parse(e);return!Array.isArray(n.importedLeaves)||!Array.isArray(n.usedLeaves)?null:{importedLeaves:new Set(n.importedLeaves.filter(r=>typeof r=="string")),usedLeaves:new Set(n.usedLeaves.filter(r=>typeof r=="string"))}}catch{return null}}function X(e,n,r,i){if(!i)return!1;let t=y(e).forFile(n,{lines:!0,reexports:!0}),s=t.lines??[];if(s.length===0)return!1;let a=t.reexports??[];return O(s,a,i)}function O(e,n,r){if(e.length===0||n.length===0)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t=new RegExp(`\\b${i}\\b`),s=0;for(let a=0;a<e.length;a++){if(!t.test(e[a]??""))continue;if(s++,!n.find(l=>l.startLine<=a&&a<=l.endLine))return!1}return s>0}var Z="CODEBASEIQ_NATIVE_CONSUMER_CLASSIFY",ee="CODEBASEIQ_NATIVE_KERNELS_BIN",ne="CODEBASEIQ_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",N=1e3,ie=5e3,te=64*1024*1024,C;function re(e,n,r,i){let t=process.env[Z]?.toLowerCase();if(t!=="1"&&t!=="true")return i.nativeReason=t==="0"||t==="false"?"disabled":"opt-in-required",null;if(i.consumerFiles<fe())return i.nativeReason="below-threshold",null;let s=me();if(!s)return i.nativeReason="binary-missing",null;i.nativeAttempted=!0;let a=se(e,n,r),o=P(s,["consumer-classify"],{input:JSON.stringify(a),encoding:"utf8",timeout:ie,maxBuffer:te,windowsHide:!0});if(o.status!==0||o.error)return i.nativeReason=o.error?`spawn-error:${o.error.message}`:`exit-${o.status??"null"}`,null;try{let l=JSON.parse(o.stdout),u=ae(l,n);return u?(i.nativeUsed=!0,i.nativeReason="used",u):(i.nativeReason="invalid-response",null)}catch{return i.nativeReason="invalid-json",null}}function se(e,n,r){let i=new Map,t=[];for(let o of n){let l=b(o.symbol),c=[...(r.get(o.symbolId)??new Map).entries()].map(([f,d])=>{let m=i.get(f)??new Set;return l&&m.add(l),i.set(f,m),{file:f,sources:[...d]}});t.push({symbol_id:o.symbolId,leaf:l,consumer_files:c})}let s={},a={};for(let[o,l]of i){let u=v(o);if(u){let f=R.get(e,o,()=>A(e,o,u));s[o]={imported_leaves:[...f.importedLeaves],used_leaves:[...f.usedLeaves]}}let c=oe(e,o,l);c.length>0&&(a[o]=c)}return{definitions:t,file_usages:s,reexport_only_leaves:a}}function oe(e,n,r){if(r.size===0)return[];let i=y(e).forFile(n,{lines:!0,reexports:!0}),t=i.lines??[],s=i.reexports??[];return t.length===0||s.length===0?[]:[...r].filter(a=>O(t,s,a))}function ae(e,n){if(!Array.isArray(e.entries)||e.entries.length!==n.length)return null;let r=new Set(n.map(t=>t.symbolId)),i=new Map;for(let t of e.entries){let s=le(t);if(!s||!r.has(s.symbol_id))return null;i.set(s.symbol_id,{partition:{realConsumers:s.real_consumers,barrelConsumers:s.barrel_consumers,importOnlyConsumers:s.import_only_consumers},files:s.files})}for(let t of r)if(!i.has(t))return null;return i}function le(e){if(!e||typeof e!="object")return null;let n=e;if(typeof n.symbol_id!="number"||!Array.isArray(n.real_consumers)||typeof n.barrel_consumers!="number"||typeof n.import_only_consumers!="number"||!Array.isArray(n.files)||!n.real_consumers.every(i=>typeof i=="string"))return null;let r=[];for(let i of n.files){if(!i||typeof i!="object")return null;let t=i;if(typeof t.file!="string"||!Array.isArray(t.sources)||!t.sources.every(ue)||!ce(t.classification))return null;r.push({file:t.file,sources:t.sources,classification:t.classification})}return{symbol_id:n.symbol_id,real_consumers:n.real_consumers,barrel_consumers:n.barrel_consumers,import_only_consumers:n.import_only_consumers,files:r}}function ue(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function ce(e){return e==="real"||e==="reexport-only"||e==="import-only"}function fe(){let e=process.env[ne];if(!e)return N;let n=Number(e);return Number.isFinite(n)&&n>=0?n:N}function me(){if(C!==void 0)return C;let e=process.env[ee],n=process.platform==="win32"?"codebaseiq-kernels.exe":"codebaseiq-kernels";return C=[...e?[e]:[],...de().map(i=>T(i,"target","release",n))].find(i=>k(i))??null,C}function de(){let e=new Set,n=L(j(import.meta.url));for(let r=0;r<5;r++)e.add(n),n=L(n);return[...e]}export{Le as a,Me as b,Ne as c,J as d};
2
- //# sourceMappingURL=chunk-NBZKSTXP.js.map
1
+ import{k as x}from"./chunk-KLX6NSWT.js";import{a as y,e as b}from"./chunk-GVAF222T.js";import{z as v}from"./chunk-ICUL7XRT.js";import{g,l as D,m as F,t as E,v as I}from"./chunk-7GAK2F3H.js";import{a as _,d as p}from"./chunk-3LCDIREB.js";import{spawnSync as P}from"child_process";import{createHash as U}from"crypto";import{existsSync as k}from"fs";import{dirname as L,join as T}from"path";import{fileURLToPath as j}from"url";var R=g("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),M=E({kind:"consumer-file-usage",invalidation:I("consumer-file-usage"),serialize:Q,deserialize:W});function Le(e,n){return{forDefinitions(r,i){return B(e,n,r,i)}}}function Me(e){let n=new Map;for(let[r,i]of e)n.set(r,new Set(i.files.map(t=>t.file)));return n}function Ne(e,n,r){return w(e,n,r).partition}function B(e,n,r,i){let t=h(r.length),s=_()?F(e):null,a=s?V(r,i,s):void 0,o=a?{workIdentity:a,workOutcome:"computed"}:{};return p("consumer-evidence.product",()=>{let l=p("consumer-evidence.provenance",()=>z(e,n,r,i),()=>({...o,definitions:r.length,semantic:i.semantic,sourceFallback:i.sourceFallback!==!1})),u=new Map;t={...t,...l.counters};let c=q(r,l.sources);return p("consumer-evidence.classify",()=>{let f=Y(e,r,l.sources,c);for(let d of r){let m=f.get(d.symbolId)??$();t.realFiles+=m.partition.realConsumers.length,t.reexportOnlyFiles+=m.partition.barrelConsumers,t.importOnlyFiles+=m.partition.importOnlyConsumers,u.set(d.symbolId,{definition:d,files:m.files,semanticIncomplete:l.incompleteSymbolIds.has(d.symbolId),semanticUnavailable:l.unavailableSymbolIds.has(d.symbolId),...m.partition})}},()=>({...o,...c,realFiles:t.realFiles,reexportOnlyFiles:t.reexportOnlyFiles,importOnlyFiles:t.importOnlyFiles})),u},()=>({...o,...t}))}function V(e,n,r){let i=U("sha256").update("consumer-evidence-v3-calibrated-semantic\0").update(r).update("\0").update(n.semantic?"semantic\0":"indexed\0").update(n.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let t of e.map(s=>s.symbol).sort())i.update("\0").update(t);return i.digest("hex").slice(0,24)}function h(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function z(e,n,r,i){let t=h(r.length),s=new Map,a=new Set,o=new Set;if(S(s,t,"indexed",n.crossFileCallerMap(r,{semantic:!1})),i.semantic){let l=x(e,r);S(s,t,"semantic",l.callers);for(let u of l.incompleteSymbolIds)a.add(u);for(let u of l.unavailableSymbolIds)o.add(u)}return i.sourceFallback!==!1&&S(s,t,"source-fallback",n.sourceFallbackCallerFiles(r)),t.totalFiles=[...s.values()].reduce((l,u)=>l+u.size,0),{sources:s,counters:t,incompleteSymbolIds:a,unavailableSymbolIds:o}}function q(e,n){return{definitions:e.length,consumerFiles:[...n.values()].reduce((r,i)=>r+i.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function S(e,n,r,i){let t=0;for(let[s,a]of i){let o=e.get(s);o||(o=new Map,e.set(s,o));for(let l of a){t++;let u=o.get(l)??new Set;u.add(r),o.set(l,u)}}r==="indexed"?n.indexedFiles+=t:r==="semantic"?n.semanticFiles+=t:n.fallbackFiles+=t}function Y(e,n,r,i){let t=re(e,n,r,i);return t||H(e,n,r)}function H(e,n,r){let i=new Map;for(let t of n){let s=r.get(t.symbolId)??new Map;i.set(t.symbolId,w(e,t,[...s.keys()],s))}return i}function w(e,n,r,i=new Map){let t=[],s=0,a=0,o=b(n.symbol),l=[];for(let u of r){let c;X(e,u,n.relativePath,o)?(s++,c="reexport-only"):J(e,u,o)?(a++,c="import-only"):(t.push(u),c="real"),l.push({file:u,sources:[...i.get(u)??[]],classification:c})}return{partition:{realConsumers:t,barrelConsumers:s,importOnlyConsumers:a},files:l}}function $(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function J(e,n,r){if(!r)return!1;let i=v(n);if(!i)return!1;let t=R.get(e,n,()=>A(e,n,i));return t.importedLeaves.has(r)&&!t.usedLeaves.has(r)}function A(e,n,r){let i=y(e).forFile(n,{text:!0,ast:!0}),t=i.text;if(!t)return G();let s=D(e,n,t),a=M.read(e,n,s);if(a)return a;let o=K(i.ast,r);return M.write(e,n,s,o),o}function K(e,n){let r=new Set,i=new Set;if(!e)return{importedLeaves:r,usedLeaves:i};let t=n==="rust"?new Set(["use_declaration"]):n==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),s=(a,o)=>{let l=o||t.has(a.type);(a.type==="identifier"||a.type==="type_identifier"||a.type==="property_identifier"||a.type==="field_identifier")&&(l?r.add(a.text):i.add(a.text));for(let u of a.children)s(u,l)};return s(e.rootNode,!1),{importedLeaves:r,usedLeaves:i}}function G(){return{importedLeaves:new Set,usedLeaves:new Set}}function Q(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function W(e){try{let n=JSON.parse(e);return!Array.isArray(n.importedLeaves)||!Array.isArray(n.usedLeaves)?null:{importedLeaves:new Set(n.importedLeaves.filter(r=>typeof r=="string")),usedLeaves:new Set(n.usedLeaves.filter(r=>typeof r=="string"))}}catch{return null}}function X(e,n,r,i){if(!i)return!1;let t=y(e).forFile(n,{lines:!0,reexports:!0}),s=t.lines??[];if(s.length===0)return!1;let a=t.reexports??[];return O(s,a,i)}function O(e,n,r){if(e.length===0||n.length===0)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t=new RegExp(`\\b${i}\\b`),s=0;for(let a=0;a<e.length;a++){if(!t.test(e[a]??""))continue;if(s++,!n.find(l=>l.startLine<=a&&a<=l.endLine))return!1}return s>0}var Z="CODEBASEIQ_NATIVE_CONSUMER_CLASSIFY",ee="CODEBASEIQ_NATIVE_KERNELS_BIN",ne="CODEBASEIQ_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",N=1e3,ie=5e3,te=64*1024*1024,C;function re(e,n,r,i){let t=process.env[Z]?.toLowerCase();if(t!=="1"&&t!=="true")return i.nativeReason=t==="0"||t==="false"?"disabled":"opt-in-required",null;if(i.consumerFiles<fe())return i.nativeReason="below-threshold",null;let s=me();if(!s)return i.nativeReason="binary-missing",null;i.nativeAttempted=!0;let a=se(e,n,r),o=P(s,["consumer-classify"],{input:JSON.stringify(a),encoding:"utf8",timeout:ie,maxBuffer:te,windowsHide:!0});if(o.status!==0||o.error)return i.nativeReason=o.error?`spawn-error:${o.error.message}`:`exit-${o.status??"null"}`,null;try{let l=JSON.parse(o.stdout),u=ae(l,n);return u?(i.nativeUsed=!0,i.nativeReason="used",u):(i.nativeReason="invalid-response",null)}catch{return i.nativeReason="invalid-json",null}}function se(e,n,r){let i=new Map,t=[];for(let o of n){let l=b(o.symbol),c=[...(r.get(o.symbolId)??new Map).entries()].map(([f,d])=>{let m=i.get(f)??new Set;return l&&m.add(l),i.set(f,m),{file:f,sources:[...d]}});t.push({symbol_id:o.symbolId,leaf:l,consumer_files:c})}let s={},a={};for(let[o,l]of i){let u=v(o);if(u){let f=R.get(e,o,()=>A(e,o,u));s[o]={imported_leaves:[...f.importedLeaves],used_leaves:[...f.usedLeaves]}}let c=oe(e,o,l);c.length>0&&(a[o]=c)}return{definitions:t,file_usages:s,reexport_only_leaves:a}}function oe(e,n,r){if(r.size===0)return[];let i=y(e).forFile(n,{lines:!0,reexports:!0}),t=i.lines??[],s=i.reexports??[];return t.length===0||s.length===0?[]:[...r].filter(a=>O(t,s,a))}function ae(e,n){if(!Array.isArray(e.entries)||e.entries.length!==n.length)return null;let r=new Set(n.map(t=>t.symbolId)),i=new Map;for(let t of e.entries){let s=le(t);if(!s||!r.has(s.symbol_id))return null;i.set(s.symbol_id,{partition:{realConsumers:s.real_consumers,barrelConsumers:s.barrel_consumers,importOnlyConsumers:s.import_only_consumers},files:s.files})}for(let t of r)if(!i.has(t))return null;return i}function le(e){if(!e||typeof e!="object")return null;let n=e;if(typeof n.symbol_id!="number"||!Array.isArray(n.real_consumers)||typeof n.barrel_consumers!="number"||typeof n.import_only_consumers!="number"||!Array.isArray(n.files)||!n.real_consumers.every(i=>typeof i=="string"))return null;let r=[];for(let i of n.files){if(!i||typeof i!="object")return null;let t=i;if(typeof t.file!="string"||!Array.isArray(t.sources)||!t.sources.every(ue)||!ce(t.classification))return null;r.push({file:t.file,sources:t.sources,classification:t.classification})}return{symbol_id:n.symbol_id,real_consumers:n.real_consumers,barrel_consumers:n.barrel_consumers,import_only_consumers:n.import_only_consumers,files:r}}function ue(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function ce(e){return e==="real"||e==="reexport-only"||e==="import-only"}function fe(){let e=process.env[ne];if(!e)return N;let n=Number(e);return Number.isFinite(n)&&n>=0?n:N}function me(){if(C!==void 0)return C;let e=process.env[ee],n=process.platform==="win32"?"codebaseiq-kernels.exe":"codebaseiq-kernels";return C=[...e?[e]:[],...de().map(i=>T(i,"target","release",n))].find(i=>k(i))??null,C}function de(){let e=new Set,n=L(j(import.meta.url));for(let r=0;r<5;r++)e.add(n),n=L(n);return[...e]}export{Le as a,Me as b,Ne as c,J as d};
2
+ //# sourceMappingURL=chunk-QY7QB7I6.js.map
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{t as Y}from"./chunk-5IC2WZAL.js";import{f as H}from"./chunk-FTTV7IRX.js";import{d as L,e as W}from"./chunk-D62CTZX6.js";import{R as $,S as w,Wa as F,X as G,Xa as J,fb as M,m as B,o as m,p as N,q as z,t as v}from"./chunk-5T44HG5Y.js";import{d as A,f as O,j as C,r as R}from"./chunk-DUKHVPU5.js";import{existsSync as k,lstatSync as b,readdirSync as K,realpathSync as U,rmSync as S,statSync as Q}from"fs";import{join as l,resolve as P,sep as V}from"path";var ne=3600*1e3,oe=2*1024*1024*1024,x=300*1e3,se="gc-state.json",ae="gc.lock",ie="projects-gc-state.json",ce="projects-gc.lock",le=1440*60*1e3;function de(t){let e=t.leases.filter(o=>o.managed&&!o.live&&!o.busy),n=X(t.leases,t.locks),r={};for(let o of t.generations)n.has(o.generationId)||(r[o.generationId]=o.unreferencedAt??t.nowMs);let a=t.generations.filter(o=>!n.has(o.generationId)).sort((o,d)=>r[o.generationId]-r[d.generationId]||o.generationId.localeCompare(d.generationId)),s=new Set;for(let o of a)t.nowMs-r[o.generationId]>=t.policy.generationTtlMs&&s.add(o.generationId);let c=t.generations.filter(o=>!s.has(o.generationId)).reduce((o,d)=>o+d.size,0);for(let o of a){if(c<=t.policy.budgetBytes)break;s.has(o.generationId)||(s.add(o.generationId),c-=o.size)}for(let o of s)delete r[o];return{deleteWorktrees:e,deleteGenerations:t.generations.filter(o=>s.has(o.generationId)),deleteLocks:t.locks.filter(o=>!o.live),deleteTemporaries:t.temporaries.filter(o=>!o.live),protectedGenerationIds:[...n].sort(),unreferencedSince:r}}function X(t,e){let n=new Set(t.filter(r=>r.managed&&(r.live||r.busy)).flatMap(r=>[r.lease.baseGenerationId,r.lease.activeGenerationId]).filter(r=>r!==void 0));for(let r of e)r.live&&n.add(r.generationId);return n}function Le(t,e,n={}){if(!z())return{kind:"disabled"};let r=A(t);if(!r)return{kind:"unavailable"};let a=l(m(),"repositories",r.repositoryId),s=(n.now??Date.now)(),c=k(a)?Z(t,a,r.repositoryId,e,s,n):{kind:"unavailable"};return fe(t,r.repositoryId,e,s,n),ue(s,n),c}function ue(t,e){let n=l(m(),"projects"),r={examined:0,reclaimed:0};if(!k(n))return r;let a=l(n,ie),s=re(a);if(!e.force&&s!==void 0&&t-s<x)return r;let c=w(l(n,ce));if(!c)return r;try{for(let o of I(n)){let d=l(n,o),i;try{i=b(d)}catch{continue}if(!(!i.isDirectory()||i.isSymbolicLink())&&(r.examined+=1,!!pe(d,t)))try{S(d,{recursive:!0,force:!0}),r.reclaimed+=1}catch{}}G(a,{version:1,lastSweepAt:new Date(t).toISOString()},{spacing:2,trailingNewline:!0})}finally{c.release()}return r}function pe(t,e){let n=l(t,B),r;try{let c=JSON.parse(R(n,"cache-ownership"));if(typeof c.canonicalProjectRoot!="string"||c.canonicalProjectRoot.length===0)return!1;r=c.canonicalProjectRoot}catch{return!1}if(k(r))return!1;try{if(e-b(t).mtimeMs<le)return!1}catch{return!1}let a=W(L(t).statePath);if(a&&C(a.pid))return!1;let s=w(l(t,"cache-lifecycle.lock"));return s===null?!1:(s.release(),!0)}function Z(t,e,n,r,a,s){let c=l(e,"gc-state.json"),o=te(c);if(!s.force&&o&&a-Date.parse(o.lastSweepAt)<x)return{kind:"throttled",sweptAt:o.lastSweepAt};let d=$(e,{now:()=>a});if(!d)return{kind:"busy"};try{let i=ee(t,e,n,o?.unreferencedSince??{}),u=de({nowMs:a,...i,policy:{generationTtlMs:s.policy?.generationTtlMs??ne,budgetBytes:s.policy?.budgetBytes??oe}}),p=0,y=0;for(let f of u.deleteWorktrees){if(!T(f.lease))continue;if(!k(f.lease.localCacheDir)){S(f.leasePath,{force:!0}),y+=1;continue}if(!he(f.lease))continue;let _=w(l(f.lease.localCacheDir,"cache-lifecycle.lock"));if(_)try{if(E(f.lease,!0))continue;try{Y({projectRoot:f.lease.projectRoot,cacheDir:f.lease.localCacheDir,cliVersion:r})}catch{continue}if(E(f.lease,!0))continue;S(f.lease.localCacheDir,{recursive:!0,force:!0}),S(f.leasePath,{force:!0}),y+=1}finally{_.release()}}for(let f of u.deleteLocks)S(f.path,{force:!0});for(let f of u.deleteTemporaries)S(f.path,{recursive:!0,force:!0});for(let f of u.deleteGenerations)S(f.path,{recursive:!0,force:!0}),p+=f.size;H(l(e,"evidence.db"));let g={kind:"swept",sweptAt:new Date(a).toISOString(),deletedWorktrees:y,deletedGenerations:u.deleteGenerations.length,deletedBytes:p,protectedGenerations:u.protectedGenerationIds.length},h={version:1,lastSweepAt:g.sweptAt,unreferencedSince:u.unreferencedSince,lastResult:g};return G(c,h,{spacing:2,trailingNewline:!0}),g}catch(i){return{kind:"failed",error:i instanceof Error?i.message:String(i)}}finally{d.release()}}function fe(t,e,n,r,a){let s=l(m(),"repositories");if(!k(s))return;let c=l(s,se),o=re(c);if(!a.force&&o!==void 0&&r-o<x)return;let d=w(l(s,ae));if(d)try{for(let i of I(s)){if(i===e||!/^[a-f0-9]{24}$/.test(i))continue;let u=l(s,i),p;try{p=b(u)}catch{continue}if(!p.isDirectory()||p.isSymbolicLink())continue;let y=ge(u)??t;Z(y,u,i,n,r,a)}G(c,{version:1,lastSweepAt:new Date(r).toISOString()},{spacing:2,trailingNewline:!0})}finally{d.release()}}function Ee(t,e,n){let r=F(t,n.dbPath,e);if(r)return{state:"bypassed",reason:r,localCacheDir:n.cacheDir,generations:0,generationBytes:0,protectedGenerations:0,unreferencedGenerations:0,unreferencedBytes:0,temporaryGenerations:0,sharedEvidence:{exists:!1,bytes:0}};let a=A(t);if(!a)return{state:"unavailable",reason:"Git worktree identity is unavailable",localCacheDir:n.cacheDir,generations:0,generationBytes:0,protectedGenerations:0,unreferencedGenerations:0,unreferencedBytes:0,temporaryGenerations:0,sharedEvidence:{exists:!1,bytes:0}};let s=l(m(),"repositories",a.repositoryId),c=j(l(s,"worktrees",`${a.worktreeId}.json`)),o=te(l(s,"gc-state.json")),d=ee(t,s,a.repositoryId,o?.unreferencedSince??{}),i=X(d.leases,d.locks),u=d.generations.filter(h=>!i.has(h.generationId)),p=d.generations.reduce((h,f)=>h+f.size,0),y=J(t,e),g=0;return y&&(g=ye(y)),{state:"managed",repositoryId:a.repositoryId,worktreeId:a.worktreeId,localCacheDir:n.cacheDir,...c?{baseGenerationId:c.baseGenerationId,activeGenerationId:c.activeGenerationId,lastAction:c.lastAction,reason:c.lastReason,lastSeenAt:c.lastSeenAt}:{},generations:d.generations.length,generationBytes:p,protectedGenerations:d.generations.filter(h=>i.has(h.generationId)).length,unreferencedGenerations:u.length,unreferencedBytes:u.reduce((h,f)=>h+f.size,0),temporaryGenerations:d.temporaries.length,sharedEvidence:{path:y,exists:g>0,bytes:g},cleanup:o?.lastResult}}function ye(t){return[t,`${t}-wal`,`${t}-shm`].reduce((e,n)=>{try{return e+Q(n).size}catch{return e}},0)}function ee(t,e,n,r){let a=new Set(O(t).map(i=>P(i.path))),s=[];for(let i of I(l(e,"worktrees"))){if(!i.endsWith(".json"))continue;let u=l(e,"worktrees",i),p=j(u);if(!p)continue;let y=P(p.projectRoot);s.push({leasePath:u,lease:p,managed:p.repositoryId===n&&T(p),live:a.has(y)||k(y),busy:E(p)})}let c=[];for(let i of I(l(e,"locks"))){let u=/^([a-f0-9]{64})\.lock$/.exec(i);if(!u)continue;let p=l(e,"locks",i),y=D(p),g=y!==void 0&&C(y),h=u[1];c.push({generationId:h,path:p,live:g})}let o=[],d=[];for(let i of I(l(e,"generations"))){let u=/^\.tmp-(\d+)-/.exec(i);if(u){let g=l(e,"generations",i),h=Number(u[1]);try{d.push({path:g,size:q(g),live:Number.isSafeInteger(h)&&C(h)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(i))continue;let p=l(e,"generations",i),y;try{y=b(p)}catch{continue}!y.isDirectory()||y.isSymbolicLink()||o.push({generationId:i,path:p,size:q(p),...r[i]===void 0?{}:{unreferencedAt:r[i]}})}return{leases:s,generations:o,locks:c,temporaries:d}}function T(t){if(t.ownershipChecksum!==M(t)||v(t.localCacheDir)!==v(N(t.projectRoot)))return!1;let e=v(l(m(),"projects"));return v(t.localCacheDir).startsWith(`${e}${V}`)}function he(t){if(!T(t))return!1;let e=P(m()),n=P(l(e,"projects")),r=P(t.localCacheDir);try{let a=b(e),s=b(n),c=b(r);if(!a.isDirectory()||a.isSymbolicLink()||!s.isDirectory()||s.isSymbolicLink()||!c.isDirectory()||c.isSymbolicLink())return!1;let o=U(n);return U(r).startsWith(`${o}${V}`)}catch{return!1}}function ge(t){for(let e of I(l(t,"worktrees"))){if(!e.endsWith(".json"))continue;let n=j(l(t,"worktrees",e));if(n)return n.projectRoot}}function E(t,e=!1){for(let r of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let a=D(l(t.localCacheDir,r));if(a!==void 0&&C(a))return!0}let n=D(L(t.localCacheDir).lockPath);return n!==void 0&&C(n)}function j(t){try{let e=JSON.parse(R(t,"worktree cache lease"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function D(t){try{let e=JSON.parse(R(t,"watch lock record"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function te(t){try{let e=JSON.parse(R(t,"repository cache GC state"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function re(t){try{let e=JSON.parse(R(t,"global repository cache GC state"));if(e.version!==1||typeof e.lastSweepAt!="string")return;let n=Date.parse(e.lastSweepAt);return Number.isFinite(n)?n:void 0}catch{return}}function I(t){try{return K(t)}catch{return[]}}function q(t){let e=0,n=[t];for(;n.length>0;){let r=n.pop();for(let a of K(r,{withFileTypes:!0})){let s=l(r,a.name);a.isDirectory()?n.push(s):a.isFile()&&(e+=Q(s).size)}}return e}export{Le as a,Ee as b};
3
- //# sourceMappingURL=chunk-Q3ZCQY2Y.js.map
2
+ import{t as Y}from"./chunk-BIADXGC3.js";import{f as H}from"./chunk-EOKVZXNF.js";import{d as L,e as W}from"./chunk-D62CTZX6.js";import{R as $,S as w,Wa as F,X as G,Xa as J,fb as M,m as B,o as m,p as N,q as z,t as v}from"./chunk-5T44HG5Y.js";import{d as A,f as O,j as C,r as R}from"./chunk-DUKHVPU5.js";import{existsSync as k,lstatSync as b,readdirSync as K,realpathSync as U,rmSync as S,statSync as Q}from"fs";import{join as l,resolve as P,sep as V}from"path";var ne=3600*1e3,oe=2*1024*1024*1024,x=300*1e3,se="gc-state.json",ae="gc.lock",ie="projects-gc-state.json",ce="projects-gc.lock",le=1440*60*1e3;function de(t){let e=t.leases.filter(o=>o.managed&&!o.live&&!o.busy),n=X(t.leases,t.locks),r={};for(let o of t.generations)n.has(o.generationId)||(r[o.generationId]=o.unreferencedAt??t.nowMs);let a=t.generations.filter(o=>!n.has(o.generationId)).sort((o,d)=>r[o.generationId]-r[d.generationId]||o.generationId.localeCompare(d.generationId)),s=new Set;for(let o of a)t.nowMs-r[o.generationId]>=t.policy.generationTtlMs&&s.add(o.generationId);let c=t.generations.filter(o=>!s.has(o.generationId)).reduce((o,d)=>o+d.size,0);for(let o of a){if(c<=t.policy.budgetBytes)break;s.has(o.generationId)||(s.add(o.generationId),c-=o.size)}for(let o of s)delete r[o];return{deleteWorktrees:e,deleteGenerations:t.generations.filter(o=>s.has(o.generationId)),deleteLocks:t.locks.filter(o=>!o.live),deleteTemporaries:t.temporaries.filter(o=>!o.live),protectedGenerationIds:[...n].sort(),unreferencedSince:r}}function X(t,e){let n=new Set(t.filter(r=>r.managed&&(r.live||r.busy)).flatMap(r=>[r.lease.baseGenerationId,r.lease.activeGenerationId]).filter(r=>r!==void 0));for(let r of e)r.live&&n.add(r.generationId);return n}function Le(t,e,n={}){if(!z())return{kind:"disabled"};let r=A(t);if(!r)return{kind:"unavailable"};let a=l(m(),"repositories",r.repositoryId),s=(n.now??Date.now)(),c=k(a)?Z(t,a,r.repositoryId,e,s,n):{kind:"unavailable"};return fe(t,r.repositoryId,e,s,n),ue(s,n),c}function ue(t,e){let n=l(m(),"projects"),r={examined:0,reclaimed:0};if(!k(n))return r;let a=l(n,ie),s=re(a);if(!e.force&&s!==void 0&&t-s<x)return r;let c=w(l(n,ce));if(!c)return r;try{for(let o of I(n)){let d=l(n,o),i;try{i=b(d)}catch{continue}if(!(!i.isDirectory()||i.isSymbolicLink())&&(r.examined+=1,!!pe(d,t)))try{S(d,{recursive:!0,force:!0}),r.reclaimed+=1}catch{}}G(a,{version:1,lastSweepAt:new Date(t).toISOString()},{spacing:2,trailingNewline:!0})}finally{c.release()}return r}function pe(t,e){let n=l(t,B),r;try{let c=JSON.parse(R(n,"cache-ownership"));if(typeof c.canonicalProjectRoot!="string"||c.canonicalProjectRoot.length===0)return!1;r=c.canonicalProjectRoot}catch{return!1}if(k(r))return!1;try{if(e-b(t).mtimeMs<le)return!1}catch{return!1}let a=W(L(t).statePath);if(a&&C(a.pid))return!1;let s=w(l(t,"cache-lifecycle.lock"));return s===null?!1:(s.release(),!0)}function Z(t,e,n,r,a,s){let c=l(e,"gc-state.json"),o=te(c);if(!s.force&&o&&a-Date.parse(o.lastSweepAt)<x)return{kind:"throttled",sweptAt:o.lastSweepAt};let d=$(e,{now:()=>a});if(!d)return{kind:"busy"};try{let i=ee(t,e,n,o?.unreferencedSince??{}),u=de({nowMs:a,...i,policy:{generationTtlMs:s.policy?.generationTtlMs??ne,budgetBytes:s.policy?.budgetBytes??oe}}),p=0,y=0;for(let f of u.deleteWorktrees){if(!T(f.lease))continue;if(!k(f.lease.localCacheDir)){S(f.leasePath,{force:!0}),y+=1;continue}if(!he(f.lease))continue;let _=w(l(f.lease.localCacheDir,"cache-lifecycle.lock"));if(_)try{if(E(f.lease,!0))continue;try{Y({projectRoot:f.lease.projectRoot,cacheDir:f.lease.localCacheDir,cliVersion:r})}catch{continue}if(E(f.lease,!0))continue;S(f.lease.localCacheDir,{recursive:!0,force:!0}),S(f.leasePath,{force:!0}),y+=1}finally{_.release()}}for(let f of u.deleteLocks)S(f.path,{force:!0});for(let f of u.deleteTemporaries)S(f.path,{recursive:!0,force:!0});for(let f of u.deleteGenerations)S(f.path,{recursive:!0,force:!0}),p+=f.size;H(l(e,"evidence.db"));let g={kind:"swept",sweptAt:new Date(a).toISOString(),deletedWorktrees:y,deletedGenerations:u.deleteGenerations.length,deletedBytes:p,protectedGenerations:u.protectedGenerationIds.length},h={version:1,lastSweepAt:g.sweptAt,unreferencedSince:u.unreferencedSince,lastResult:g};return G(c,h,{spacing:2,trailingNewline:!0}),g}catch(i){return{kind:"failed",error:i instanceof Error?i.message:String(i)}}finally{d.release()}}function fe(t,e,n,r,a){let s=l(m(),"repositories");if(!k(s))return;let c=l(s,se),o=re(c);if(!a.force&&o!==void 0&&r-o<x)return;let d=w(l(s,ae));if(d)try{for(let i of I(s)){if(i===e||!/^[a-f0-9]{24}$/.test(i))continue;let u=l(s,i),p;try{p=b(u)}catch{continue}if(!p.isDirectory()||p.isSymbolicLink())continue;let y=ge(u)??t;Z(y,u,i,n,r,a)}G(c,{version:1,lastSweepAt:new Date(r).toISOString()},{spacing:2,trailingNewline:!0})}finally{d.release()}}function Ee(t,e,n){let r=F(t,n.dbPath,e);if(r)return{state:"bypassed",reason:r,localCacheDir:n.cacheDir,generations:0,generationBytes:0,protectedGenerations:0,unreferencedGenerations:0,unreferencedBytes:0,temporaryGenerations:0,sharedEvidence:{exists:!1,bytes:0}};let a=A(t);if(!a)return{state:"unavailable",reason:"Git worktree identity is unavailable",localCacheDir:n.cacheDir,generations:0,generationBytes:0,protectedGenerations:0,unreferencedGenerations:0,unreferencedBytes:0,temporaryGenerations:0,sharedEvidence:{exists:!1,bytes:0}};let s=l(m(),"repositories",a.repositoryId),c=j(l(s,"worktrees",`${a.worktreeId}.json`)),o=te(l(s,"gc-state.json")),d=ee(t,s,a.repositoryId,o?.unreferencedSince??{}),i=X(d.leases,d.locks),u=d.generations.filter(h=>!i.has(h.generationId)),p=d.generations.reduce((h,f)=>h+f.size,0),y=J(t,e),g=0;return y&&(g=ye(y)),{state:"managed",repositoryId:a.repositoryId,worktreeId:a.worktreeId,localCacheDir:n.cacheDir,...c?{baseGenerationId:c.baseGenerationId,activeGenerationId:c.activeGenerationId,lastAction:c.lastAction,reason:c.lastReason,lastSeenAt:c.lastSeenAt}:{},generations:d.generations.length,generationBytes:p,protectedGenerations:d.generations.filter(h=>i.has(h.generationId)).length,unreferencedGenerations:u.length,unreferencedBytes:u.reduce((h,f)=>h+f.size,0),temporaryGenerations:d.temporaries.length,sharedEvidence:{path:y,exists:g>0,bytes:g},cleanup:o?.lastResult}}function ye(t){return[t,`${t}-wal`,`${t}-shm`].reduce((e,n)=>{try{return e+Q(n).size}catch{return e}},0)}function ee(t,e,n,r){let a=new Set(O(t).map(i=>P(i.path))),s=[];for(let i of I(l(e,"worktrees"))){if(!i.endsWith(".json"))continue;let u=l(e,"worktrees",i),p=j(u);if(!p)continue;let y=P(p.projectRoot);s.push({leasePath:u,lease:p,managed:p.repositoryId===n&&T(p),live:a.has(y)||k(y),busy:E(p)})}let c=[];for(let i of I(l(e,"locks"))){let u=/^([a-f0-9]{64})\.lock$/.exec(i);if(!u)continue;let p=l(e,"locks",i),y=D(p),g=y!==void 0&&C(y),h=u[1];c.push({generationId:h,path:p,live:g})}let o=[],d=[];for(let i of I(l(e,"generations"))){let u=/^\.tmp-(\d+)-/.exec(i);if(u){let g=l(e,"generations",i),h=Number(u[1]);try{d.push({path:g,size:q(g),live:Number.isSafeInteger(h)&&C(h)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(i))continue;let p=l(e,"generations",i),y;try{y=b(p)}catch{continue}!y.isDirectory()||y.isSymbolicLink()||o.push({generationId:i,path:p,size:q(p),...r[i]===void 0?{}:{unreferencedAt:r[i]}})}return{leases:s,generations:o,locks:c,temporaries:d}}function T(t){if(t.ownershipChecksum!==M(t)||v(t.localCacheDir)!==v(N(t.projectRoot)))return!1;let e=v(l(m(),"projects"));return v(t.localCacheDir).startsWith(`${e}${V}`)}function he(t){if(!T(t))return!1;let e=P(m()),n=P(l(e,"projects")),r=P(t.localCacheDir);try{let a=b(e),s=b(n),c=b(r);if(!a.isDirectory()||a.isSymbolicLink()||!s.isDirectory()||s.isSymbolicLink()||!c.isDirectory()||c.isSymbolicLink())return!1;let o=U(n);return U(r).startsWith(`${o}${V}`)}catch{return!1}}function ge(t){for(let e of I(l(t,"worktrees"))){if(!e.endsWith(".json"))continue;let n=j(l(t,"worktrees",e));if(n)return n.projectRoot}}function E(t,e=!1){for(let r of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let a=D(l(t.localCacheDir,r));if(a!==void 0&&C(a))return!0}let n=D(L(t.localCacheDir).lockPath);return n!==void 0&&C(n)}function j(t){try{let e=JSON.parse(R(t,"worktree cache lease"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function D(t){try{let e=JSON.parse(R(t,"watch lock record"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function te(t){try{let e=JSON.parse(R(t,"repository cache GC state"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function re(t){try{let e=JSON.parse(R(t,"global repository cache GC state"));if(e.version!==1||typeof e.lastSweepAt!="string")return;let n=Date.parse(e.lastSweepAt);return Number.isFinite(n)?n:void 0}catch{return}}function I(t){try{return K(t)}catch{return[]}}function q(t){let e=0,n=[t];for(;n.length>0;){let r=n.pop();for(let a of K(r,{withFileTypes:!0})){let s=l(r,a.name);a.isDirectory()?n.push(s):a.isFile()&&(e+=Q(s).size)}}return e}export{Le as a,Ee as b};
3
+ //# sourceMappingURL=chunk-R4OJGTMP.js.map
@@ -1,2 +1,2 @@
1
- import{a as x}from"./chunk-YHPG3S2U.js";import{b as g}from"./chunk-B75HZHUP.js";import{c as k}from"./chunk-HENP2O4A.js";import{a as n}from"./chunk-BGBBVSH4.js";import{k as v}from"./chunk-J3GLP7Q5.js";import{a as L}from"./chunk-BRQL7AFJ.js";import{d as S}from"./chunk-GVAF222T.js";import{d as a}from"./chunk-3LCDIREB.js";function B(c,f={}){let{scope:P,minLoc:F=3,scanLimit:d}=f,o=new k(c),u=f.semantic!==!1,y=0,m=a("isolated.candidates",()=>{let t=g(o.productionCallableDefinitions({scope:P,minLoc:F,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof d=="number"&&d>0}),d).filter(w=>!x(c,w));return y=t.length,t},()=>({definitions:y})),p=0,i=a("isolated.strict-callees",()=>{let e=o.symbolsWithNonSelfCallees(m,{additive:!1,semantic:!1});return p=e.size,e},()=>({definitions:m.length,symbols:p})),r=m.filter(e=>!i.has(e.symbolId)),C=0,N=a("isolated.scip-callers",()=>{let e=o.crossFileCallerMap(r,{semantic:!1});return C=e.size,e},()=>({definitions:r.length,symbols:C})),s=new Set(N.keys());for(let e of o.frameworkReferencedSymbolIds(r))s.add(e);let l=r.filter(e=>!s.has(e.symbolId));if(u&&l.length>0){let e=v(c,l);for(let t of e.callers.keys())s.add(t);for(let t of e.incompleteSymbolIds)s.add(t);for(let t of e.unavailableSymbolIds)s.add(t);for(let t of o.symbolsWithNonSelfCallees(l,{additive:!1,semantic:!0}))i.add(t);l=l.filter(t=>!s.has(t.symbolId)).filter(t=>!i.has(t.symbolId))}let h=0,W=a("isolated.source-fallback-callers",()=>{let e=o.sourceFallbackCallerFiles(l,{skipPath:t=>L(t)==="test"});return h=e.size,e},()=>({definitions:l.length,symbols:h}));for(let e of W.keys())s.add(e);let b=l.filter(e=>!s.has(e.symbolId)),I=0,R=a("isolated.additive-callees",()=>{let e=o.symbolsWithNonSelfCallees(b,{additive:!0,semantic:u});return I=e.size,e},()=>({definitions:b.length,symbols:I}));for(let e of R)i.add(e);return b.filter(e=>!i.has(e.symbolId)).sort((e,t)=>n(t)-n(e)||e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine).map(e=>({symbol:e.symbol,shortName:S(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:n(e)}))}export{B as a};
2
- //# sourceMappingURL=chunk-UQE4XFSA.js.map
1
+ import{a as x}from"./chunk-YHPG3S2U.js";import{b as g}from"./chunk-B75HZHUP.js";import{c as k}from"./chunk-BPKNP3KZ.js";import{a as n}from"./chunk-BGBBVSH4.js";import{k as v}from"./chunk-KLX6NSWT.js";import{a as L}from"./chunk-BRQL7AFJ.js";import{d as S}from"./chunk-GVAF222T.js";import{d as a}from"./chunk-3LCDIREB.js";function B(c,f={}){let{scope:P,minLoc:F=3,scanLimit:d}=f,o=new k(c),u=f.semantic!==!1,y=0,m=a("isolated.candidates",()=>{let t=g(o.productionCallableDefinitions({scope:P,minLoc:F,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof d=="number"&&d>0}),d).filter(w=>!x(c,w));return y=t.length,t},()=>({definitions:y})),p=0,i=a("isolated.strict-callees",()=>{let e=o.symbolsWithNonSelfCallees(m,{additive:!1,semantic:!1});return p=e.size,e},()=>({definitions:m.length,symbols:p})),r=m.filter(e=>!i.has(e.symbolId)),C=0,N=a("isolated.scip-callers",()=>{let e=o.crossFileCallerMap(r,{semantic:!1});return C=e.size,e},()=>({definitions:r.length,symbols:C})),s=new Set(N.keys());for(let e of o.frameworkReferencedSymbolIds(r))s.add(e);let l=r.filter(e=>!s.has(e.symbolId));if(u&&l.length>0){let e=v(c,l);for(let t of e.callers.keys())s.add(t);for(let t of e.incompleteSymbolIds)s.add(t);for(let t of e.unavailableSymbolIds)s.add(t);for(let t of o.symbolsWithNonSelfCallees(l,{additive:!1,semantic:!0}))i.add(t);l=l.filter(t=>!s.has(t.symbolId)).filter(t=>!i.has(t.symbolId))}let h=0,W=a("isolated.source-fallback-callers",()=>{let e=o.sourceFallbackCallerFiles(l,{skipPath:t=>L(t)==="test"});return h=e.size,e},()=>({definitions:l.length,symbols:h}));for(let e of W.keys())s.add(e);let b=l.filter(e=>!s.has(e.symbolId)),I=0,R=a("isolated.additive-callees",()=>{let e=o.symbolsWithNonSelfCallees(b,{additive:!0,semantic:u});return I=e.size,e},()=>({definitions:b.length,symbols:I}));for(let e of R)i.add(e);return b.filter(e=>!i.has(e.symbolId)).sort((e,t)=>n(t)-n(e)||e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine).map(e=>({symbol:e.symbol,shortName:S(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:n(e)}))}export{B as a};
2
+ //# sourceMappingURL=chunk-RIO3JXHM.js.map
@@ -1,4 +1,4 @@
1
- import{a as $}from"./chunk-6VREELBC.js";import{f as C}from"./chunk-MSI3K7PJ.js";import{a as F,c as _}from"./chunk-SGMNWYTH.js";import{A as x,d as E,f as A,t as M}from"./chunk-GVAF222T.js";import{z as R}from"./chunk-ICUL7XRT.js";function q(t,o,n={}){return P(t,o,n).rows}function G(t,o,n={}){return P(t,o,n)}function P(t,o,n){let{maxDepth:r=5,scope:c}=n,a=r===Number.MAX_SAFE_INTEGER,l=a?null:500,y=F(t,o);if(!y)return{rows:[],coverage:{status:"incomplete",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:0,perSymbolEvidenceLimit:l,remainingFrontierSymbols:0,reasons:["The requested symbol could not be resolved."],semanticEvidence:"incomplete"}};let m=[],u=new Set([y.symbolId]),s=new Set,e=[y],d=0,p=!1,h=!1,g=!1;for(let b=1;b<=r&&e.length!==0;b++){d=b;let v=[],S=C(t,e,{...a?{}:{limit:l+1},semanticEvidence:$});S.incompleteSymbolIds.size>0&&(h=!0),S.unavailableSymbolIds.size>0&&(g=!0);for(let w of e){let I=S.rows.get(w.symbolId)??[];l!==null&&I.length>l&&(p=!0);let L=l===null?I:I.slice(0,l);for(let i of T(t,w,c,L)){let N=`${i.file}|${i.shortName}`;if(i.symbolId!==null){if(u.has(i.symbolId))continue;u.add(i.symbolId)}else if(s.has(N))continue;s.add(N),m.push({symbol:i.symbol,shortName:i.shortName,file:i.file,depth:b}),i.symbolId!==null&&i.symbolMatch&&v.push(i.symbolMatch)}}e=v}m.sort((b,v)=>b.depth-v.depth||b.file.localeCompare(v.file));let D=e.length>0,f=[];return D&&f.push(`${e.length} symbol(s) remain eligible beyond depth ${r}.`),p&&f.push(`At least one symbol had more than ${l} incoming evidence row(s).`),h&&f.push("Compiler-resolved incoming evidence was incomplete for at least one traversed symbol."),g&&f.push("Compiler-resolved incoming evidence was unavailable for at least one traversed symbol."),f.length===0&&f.push("The discovered reverse evidence frontier was exhausted."),{rows:m,coverage:{status:h||g?"incomplete":D||p?"bounded":"accounted",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:d,perSymbolEvidenceLimit:l,remainingFrontierSymbols:e.length,reasons:f,semanticEvidence:h&&g?"incomplete-and-unavailable":h?"incomplete":g?"unavailable":"complete"}}}function T(t,o,n,r){let c=r.filter(s=>!t.isIgnored(s.file)).filter(s=>!n||s.file.includes(n)),a=new Set(c.map(s=>s.file)),l=[];for(let s of k(t,o,n)){if(a.has(s))continue;let e=M(t,s),d=e.length>0?x(e,e[0].startLine):null;l.push({symbol:d?.symbol??s,file:s})}let y=[...c,...l],m=[],u=new Set;for(let s of y){let e=_(t,s.symbol);if(!e){let p=`${s.file}|${s.symbol}`;if(u.has(p))continue;u.add(p),m.push({symbolId:null,symbol:s.symbol,shortName:E(s.symbol),file:s.file,symbolMatch:null});continue}if(e.symbolId===o.symbolId||t.isIgnored(e.relativePath)||!B(e))continue;let d=`${e.symbolId}|${e.relativePath}`;u.has(d)||(u.add(d),m.push({symbolId:e.symbolId,symbol:e.symbol,shortName:E(e.symbol),file:e.relativePath,symbolMatch:e}))}return m}function k(t,o,n){let r=n?"AND consumer_d.relative_path LIKE ?":"",c=[o.symbolId,o.documentId];return n&&c.push(`%${n}%`),new Set(t.all(`SELECT DISTINCT consumer_d.relative_path
1
+ import{a as $}from"./chunk-57OPIQFM.js";import{f as C}from"./chunk-MSI3K7PJ.js";import{a as F,c as _}from"./chunk-SGMNWYTH.js";import{A as x,d as E,f as A,t as M}from"./chunk-GVAF222T.js";import{z as R}from"./chunk-ICUL7XRT.js";function q(t,o,n={}){return P(t,o,n).rows}function G(t,o,n={}){return P(t,o,n)}function P(t,o,n){let{maxDepth:r=5,scope:c}=n,a=r===Number.MAX_SAFE_INTEGER,l=a?null:500,y=F(t,o);if(!y)return{rows:[],coverage:{status:"incomplete",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:0,perSymbolEvidenceLimit:l,remainingFrontierSymbols:0,reasons:["The requested symbol could not be resolved."],semanticEvidence:"incomplete"}};let m=[],u=new Set([y.symbolId]),s=new Set,e=[y],d=0,p=!1,h=!1,g=!1;for(let b=1;b<=r&&e.length!==0;b++){d=b;let v=[],S=C(t,e,{...a?{}:{limit:l+1},semanticEvidence:$});S.incompleteSymbolIds.size>0&&(h=!0),S.unavailableSymbolIds.size>0&&(g=!0);for(let w of e){let I=S.rows.get(w.symbolId)??[];l!==null&&I.length>l&&(p=!0);let L=l===null?I:I.slice(0,l);for(let i of T(t,w,c,L)){let N=`${i.file}|${i.shortName}`;if(i.symbolId!==null){if(u.has(i.symbolId))continue;u.add(i.symbolId)}else if(s.has(N))continue;s.add(N),m.push({symbol:i.symbol,shortName:i.shortName,file:i.file,depth:b}),i.symbolId!==null&&i.symbolMatch&&v.push(i.symbolMatch)}}e=v}m.sort((b,v)=>b.depth-v.depth||b.file.localeCompare(v.file));let D=e.length>0,f=[];return D&&f.push(`${e.length} symbol(s) remain eligible beyond depth ${r}.`),p&&f.push(`At least one symbol had more than ${l} incoming evidence row(s).`),h&&f.push("Compiler-resolved incoming evidence was incomplete for at least one traversed symbol."),g&&f.push("Compiler-resolved incoming evidence was unavailable for at least one traversed symbol."),f.length===0&&f.push("The discovered reverse evidence frontier was exhausted."),{rows:m,coverage:{status:h||g?"incomplete":D||p?"bounded":"accounted",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:d,perSymbolEvidenceLimit:l,remainingFrontierSymbols:e.length,reasons:f,semanticEvidence:h&&g?"incomplete-and-unavailable":h?"incomplete":g?"unavailable":"complete"}}}function T(t,o,n,r){let c=r.filter(s=>!t.isIgnored(s.file)).filter(s=>!n||s.file.includes(n)),a=new Set(c.map(s=>s.file)),l=[];for(let s of k(t,o,n)){if(a.has(s))continue;let e=M(t,s),d=e.length>0?x(e,e[0].startLine):null;l.push({symbol:d?.symbol??s,file:s})}let y=[...c,...l],m=[],u=new Set;for(let s of y){let e=_(t,s.symbol);if(!e){let p=`${s.file}|${s.symbol}`;if(u.has(p))continue;u.add(p),m.push({symbolId:null,symbol:s.symbol,shortName:E(s.symbol),file:s.file,symbolMatch:null});continue}if(e.symbolId===o.symbolId||t.isIgnored(e.relativePath)||!B(e))continue;let d=`${e.symbolId}|${e.relativePath}`;u.has(d)||(u.add(d),m.push({symbolId:e.symbolId,symbol:e.symbol,shortName:E(e.symbol),file:e.relativePath,symbolMatch:e}))}return m}function k(t,o,n){let r=n?"AND consumer_d.relative_path LIKE ?":"",c=[o.symbolId,o.documentId];return n&&c.push(`%${n}%`),new Set(t.all(`SELECT DISTINCT consumer_d.relative_path
2
2
  FROM mentions m
3
3
  JOIN chunks c ON m.chunk_id = c.id
4
4
  JOIN documents consumer_d ON consumer_d.id = c.document_id
@@ -7,4 +7,4 @@ import{a as $}from"./chunk-6VREELBC.js";import{f as C}from"./chunk-MSI3K7PJ.js";
7
7
  AND c.document_id != ?
8
8
  ${t.pathExclusionsFor("consumer_d")}
9
9
  ${r}`,...c).map(a=>a.relative_path).filter(a=>!t.isIgnored(a)))}function B(t){if(t.symbol.startsWith("scip-clojure ")||R(t.relativePath)==="clojure")return!0;let o=A(t.symbol);return o==="method"||o==="type"||t.symbol.endsWith("().")}export{q as a,G as b};
10
- //# sourceMappingURL=chunk-CW6AXOLR.js.map
10
+ //# sourceMappingURL=chunk-SA7G6GJX.js.map
@@ -1,2 +1,2 @@
1
- import{c as h}from"./chunk-B75HZHUP.js";import{a as m}from"./chunk-6VREELBC.js";import{b,d as g}from"./chunk-MSI3K7PJ.js";import{a as u}from"./chunk-SGMNWYTH.js";import{d as o,h as p}from"./chunk-GVAF222T.js";function N(n,a,f={}){let i=u(n,a);if(!i)return null;let l=f.semantic!==!1,c=g(n,i,{semantic:l,semanticEvidence:m}),S=c.rows.filter(e=>p(e.symbol)).slice(0,50),t=b(n,i,{limit:50,additive:!0,callableOnly:!0,semantic:l,semanticEvidence:m}),E=h(t.rows),d=S.map(e=>({symbol:e.symbol,shortName:o(e.symbol),file:e.file,relationship:e.source!=="caller-map-inversion"?"reference-candidate":e.callEvidence==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:e.source==="caller-map-inversion"&&e.callEvidence!=="scip-chunk"?"exact":"candidate",evidenceSource:e.callEvidence??e.source})),v=E.map(e=>({symbol:e.symbol,shortName:o(e.symbol),file:e.file,relationship:e.source==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:e.source==="scip-chunk"?"candidate":"exact",evidenceSource:e.source}));return{symbol:i.symbol,shortName:o(i.symbol),callers:d.map(({symbol:e,shortName:s,file:r})=>({symbol:e,shortName:s,file:r})),callees:v.map(({symbol:e,shortName:s,file:r})=>({symbol:e,shortName:s,file:r})),callerEvidence:d,calleeEvidence:v,coverage:{scope:"indexed-static-call-graph",blindSpots:["unresolved dynamic dispatch and reflection","external or unindexed callees without a resolved symbol identity","SCIP chunk co-occurrence is retained only as candidate call evidence",...c.semanticIncomplete?["compiler-resolved incoming evidence was incomplete; known callers are retained"]:[],...c.semanticUnavailable?["compiler-resolved incoming evidence was unavailable; known callers are retained"]:[],...t.semanticIncomplete?["compiler-resolved outgoing evidence was incomplete; known callees are retained"]:[],...t.semanticUnavailable?["compiler-resolved outgoing evidence was unavailable; known callees are retained"]:[]],semanticEvidence:{enabled:l,incoming:y(l,c),outgoing:y(l,t)}}}}function y(n,a){return n?a.semanticIncomplete&&a.semanticUnavailable?"incomplete-and-unavailable":a.semanticIncomplete?"incomplete":a.semanticUnavailable?"unavailable":"complete":"disabled"}export{N as a};
2
- //# sourceMappingURL=chunk-Q4XEU3UH.js.map
1
+ import{c as h}from"./chunk-B75HZHUP.js";import{a as m}from"./chunk-57OPIQFM.js";import{b,d as g}from"./chunk-MSI3K7PJ.js";import{a as u}from"./chunk-SGMNWYTH.js";import{d as o,h as p}from"./chunk-GVAF222T.js";function N(n,a,f={}){let i=u(n,a);if(!i)return null;let l=f.semantic!==!1,c=g(n,i,{semantic:l,semanticEvidence:m}),S=c.rows.filter(e=>p(e.symbol)).slice(0,50),t=b(n,i,{limit:50,additive:!0,callableOnly:!0,semantic:l,semanticEvidence:m}),E=h(t.rows),d=S.map(e=>({symbol:e.symbol,shortName:o(e.symbol),file:e.file,relationship:e.source!=="caller-map-inversion"?"reference-candidate":e.callEvidence==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:e.source==="caller-map-inversion"&&e.callEvidence!=="scip-chunk"?"exact":"candidate",evidenceSource:e.callEvidence??e.source})),v=E.map(e=>({symbol:e.symbol,shortName:o(e.symbol),file:e.file,relationship:e.source==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:e.source==="scip-chunk"?"candidate":"exact",evidenceSource:e.source}));return{symbol:i.symbol,shortName:o(i.symbol),callers:d.map(({symbol:e,shortName:s,file:r})=>({symbol:e,shortName:s,file:r})),callees:v.map(({symbol:e,shortName:s,file:r})=>({symbol:e,shortName:s,file:r})),callerEvidence:d,calleeEvidence:v,coverage:{scope:"indexed-static-call-graph",blindSpots:["unresolved dynamic dispatch and reflection","external or unindexed callees without a resolved symbol identity","SCIP chunk co-occurrence is retained only as candidate call evidence",...c.semanticIncomplete?["compiler-resolved incoming evidence was incomplete; known callers are retained"]:[],...c.semanticUnavailable?["compiler-resolved incoming evidence was unavailable; known callers are retained"]:[],...t.semanticIncomplete?["compiler-resolved outgoing evidence was incomplete; known callees are retained"]:[],...t.semanticUnavailable?["compiler-resolved outgoing evidence was unavailable; known callees are retained"]:[]],semanticEvidence:{enabled:l,incoming:y(l,c),outgoing:y(l,t)}}}}function y(n,a){return n?a.semanticIncomplete&&a.semanticUnavailable?"incomplete-and-unavailable":a.semanticIncomplete?"incomplete":a.semanticUnavailable?"unavailable":"complete":"disabled"}export{N as a};
2
+ //# sourceMappingURL=chunk-SB53KPWA.js.map
@@ -1,5 +1,5 @@
1
- import{a as te,b as N,e as V,f as j,g as B,h as re,i as se}from"./chunk-NMTSZXCL.js";import{b as _}from"./chunk-B75HZHUP.js";import{c as q}from"./chunk-HENP2O4A.js";import{a as ie}from"./chunk-6VREELBC.js";import{b as ne}from"./chunk-MSI3K7PJ.js";import{a as D}from"./chunk-SGMNWYTH.js";import{d as v,e as K,h as $}from"./chunk-GVAF222T.js";import{a as E}from"./chunk-F74LZWCE.js";import{a as Y}from"./chunk-ICUL7XRT.js";import{h as z,l as J,t as Q,v as ee,w as U,x as H}from"./chunk-7GAK2F3H.js";import{a as A,d as y}from"./chunk-3LCDIREB.js";function Ie(e,n,t={}){let{minSimilarity:i=.4,limit:r=20}=t,s=()=>Ge(e,n,{minSimilarity:i,limit:r,scanLimit:t.scanLimit,candidateMode:t.sourceCandidateMode??"full"}),a=Be(e,n,{semantic:t.semantic!==!1});if(a.kind==="not-callable")return[];if(a.kind==="callee-evidence-unusable")return s();let o=a.target;if(!$(o.symbol))return[];if(o.callees.size===0)return s();let c=we(e,o,i,{scanLimit:t.scanLimit,semantic:t.semantic!==!1});return c.length>0?c.slice(0,r):s()}function Tn(e,n,t,i={}){let r=D(e,n),s=D(e,t);if(!r||!s)return null;let a=Ie(e,r.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:i.semantic,scanLimit:i.scanLimit}).find(m=>m.symbolB===s.symbol||m.symbolA===s.symbol);if(!a)return null;let o=r.endLine-r.startLine+1,c=s.endLine-s.startLine+1;return{symbolA:{symbol:r.symbol,shortName:v(r.symbol),file:r.relativePath,loc:o},symbolB:{symbol:s.symbol,shortName:v(s.symbol),file:s.relativePath,loc:c},similarity:a.similarity,similarityBasis:a.similarityBasis??"callees",sharedEvidence:a.sharedCallees,uniqueToA:a.uniqueToA,uniqueToB:a.uniqueToB,evidenceClass:a.evidenceClass,actionTier:a.actionTier,recommendation:a.recommendation,consolidationStrategy:ve(a)}}function ve(e){let n=e.similarityBasis==="source-tokens"?"source-token":"tracked callee";return e.sharedCallees.length===0?`No shared ${n} evidence survived similar's weighting. Inspect the source before attempting consolidation.`:e.uniqueToA.length===0&&e.uniqueToB.length===0?`The functions have identical ${n} evidence under similar's weighting. Verify signatures, guards, and return values before consolidating.`:e.uniqueToA.length===0?`A's ${n} 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 ${n} 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 ${n}(s). Pass the ${e.uniqueToA.length+e.uniqueToB.length} divergent point(s) as parameters or callbacks.`:`Extract the ${e.sharedCallees.length} shared ${n}(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 we(e,n,t,i){let r=G(e).calleeIndex({minCallees:3,scanLimit:i.scanLimit,semantic:i.semantic}),s=_e(n,r.corpus),a=Pe(s,r),o=Te(s,r),c=j(o),m=B(s.callees,o),g=[];for(let f of a){if(f.callees.size<3)continue;let l=B(f.callees,o),u=ce(s,f,o,{minSimilarity:t,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:m,magnitudeB:l});u&&g.push(u)}return g.sort((f,l)=>l.similarity-f.similarity),g}function Te(e,n){let t=new Map(n.docFreq);for(let i of e.callees)t.set(i,(t.get(i)??0)+1);return V(t,n.corpus.length+1)}function ce(e,n,t,i){let r=Le(e,n,t,i);if(!Re(r,i))return null;let{similarity:s,significantShared:a,trivialShared:o}=r,c=a.length>0?a:o,m=pe(c,"callees");return{symbolA:e.symbol,shortNameA:v(e.symbol),fileA:e.file,symbolB:n.symbol,shortNameB:v(n.symbol),fileB:n.file,similarity:s,similarityBasis:"callees",sharedCallees:c.map(v),uniqueToA:[...N(e.callees,n.callees)].map(v),uniqueToB:[...N(n.callees,e.callees)].map(v),...m}}function Me(e,n,t,i){let r=i.magnitudeA??B(e.callees,t),s=i.magnitudeB??B(n.callees,t),a=0,o=0,c=0,m=i.medianIdf??j(t);for(let l of e.callees){if(!n.callees.has(l))continue;let u=t.get(l)??0;a+=u*u,c+=1,u>=m&&(o+=1)}if(c===0)return!1;let g=r*s;return(g>0?a/g:0)<i.minSimilarity?!1:o>=i.requireSignificantShared||c>=i.requireSharedCount}function Le(e,n,t,i){return i.magnitudeA===void 0||i.magnitudeB===void 0?re(e.callees,n.callees,t,{medianIdf:i.medianIdf}):se(e.callees,n.callees,t,{medianIdf:i.medianIdf,magnitudeA:i.magnitudeA,magnitudeB:i.magnitudeB})}function Re(e,n){if(e.similarity<n.minSimilarity)return!1;let t=e.significantShared.length+e.trivialShared.length;return e.significantShared.length>=n.requireSignificantShared||t>=n.requireSharedCount}function Mn(e,n={}){let{minSimilarity:t=.5,limit:i=20,scope:r,minCallees:s=4,crossFileOnly:a=!1,scanLimit:o}=n,c=n.semantic!==!1,m=A(),g=0,f=0,l=0,u=0,d=0,p=0,b=0;return y("similar.all",()=>{let h=G(e).calleeIndex({minCallees:s,scope:r,scanLimit:o,semantic:c}),S=h.corpus;g=S.length;let F=n.focusFiles,I=[],P=0;return y("similar.all.pair-scan",()=>{for(let k=0;k<S.length;k+=1){let x=S[k],M=F?.has(x.file)??!1,w=h.weightedMagnitudes[k],T=new Set;for(let O of x.callees){let L=h.candidateIndexesByCallee.get(O);if(L)for(let R of L)R<=k||F&&!M&&!F.has(S[R].file)||T.add(R)}m&&(l+=T.size,T.size>0&&(f+=1));for(let O of T){let L=S[O];if(a&&x.file===L.file){m&&(d+=1);continue}if(ue(x,L)){m&&(p+=1);continue}m&&(u+=1);let R=ce(x,L,h.idfWeights,{minSimilarity:t,requireSignificantShared:2,requireSharedCount:4,medianIdf:h.medianIdf,magnitudeA:w,magnitudeB:h.weightedMagnitudes[O]});R&&(Ae(I,R,i,P),m&&(b+=1),P+=1)}}},()=>({corpusSize:g,candidateSets:f,candidatePairs:l,comparedPairs:u,crossFileSkips:d,signatureSkips:p,insertedResults:b,topResults:I.length})),y("similar.all.sort-project",()=>(I.sort((k,x)=>x.result.similarity-k.result.similarity||k.order-x.order),I.map(k=>k.result)),()=>({topResults:I.length}))},()=>({minSimilarity:t,limit:i,scope:r,minCallees:s,crossFileOnly:a,scanLimit:o,semantic:c,corpusSize:g,candidateSets:f,candidatePairs:l,comparedPairs:u,crossFileSkips:d,signatureSkips:p,insertedResults:b}))}function Ln(e,n={}){let{minSimilarity:t=.5,scope:i,minCallees:r=4,crossFileOnly:s=!1,scanLimit:a}=n,o=n.semantic!==!1,c=A(),m=0,g=0,f=0,l=0,u=0,d=0,p=0;return y("similar.all-count",()=>{let C=G(e).calleeIndex({minCallees:r,scope:i,scanLimit:a,semantic:o}),h=C.corpus;m=h.length;let S=n.focusFiles;return y("similar.all-count.pair-scan",()=>{for(let F=0;F<h.length;F+=1){let I=h[F],P=S?.has(I.file)??!1,k=C.weightedMagnitudes[F],x=new Set;for(let M of I.callees){let w=C.candidateIndexesByCallee.get(M);if(w)for(let T of w)T<=F||S&&!P&&!S.has(h[T].file)||x.add(T)}c&&(f+=x.size,x.size>0&&(g+=1));for(let M of x){let w=h[M];if(s&&I.file===w.file){c&&(u+=1);continue}if(ue(I,w)){c&&(d+=1);continue}c&&(l+=1),Me(I,w,C.idfWeights,{minSimilarity:t,requireSignificantShared:2,requireSharedCount:4,medianIdf:C.medianIdf,magnitudeA:k,magnitudeB:C.weightedMagnitudes[M]})&&(p+=1)}}},()=>({corpusSize:m,candidateSets:g,candidatePairs:f,comparedPairs:l,crossFileSkips:u,signatureSkips:d,insertedResults:p})),p},()=>({minSimilarity:t,scope:i,minCallees:r,crossFileOnly:s,scanLimit:a,semantic:o,corpusSize:m,candidateSets:g,candidatePairs:f,comparedPairs:l,crossFileSkips:u,signatureSkips:d,insertedResults:p}))}function ue(e,n){if(e.paramCount<0||n.paramCount<0)return!1;let t=Math.abs(e.paramCount-n.paramCount),i=Math.max(2,Math.ceil(Math.max(e.paramCount,n.paramCount)*.5));return t>i}var me=Q({kind:"source-fingerprints",invalidation:ee("source-fingerprints"),serialize:cn,deserialize:ln});function Ae(e,n,t,i){if(t<=0)return;if(e.length<t){e.push({result:n,order:i});return}let r=0;for(let a=1;a<e.length;a+=1){let o=e[a],c=e[r];(o.result.similarity<c.result.similarity||o.result.similarity===c.result.similarity&&o.order>c.order)&&(r=a)}let s=e[r];n.similarity<=s.result.similarity||(e[r]={result:n,order:i})}var Ee=["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 Be(e,n,t){let i=D(e,n);if(!i)return{kind:"not-callable"};if(!$(i.symbol))return{kind:"not-callable"};let r=new q(e),s=ne(e,i,{semantic:t.semantic,semanticEvidence:ie});return s.semanticIncomplete||s.semanticUnavailable?{kind:"callee-evidence-unusable"}:{kind:"resolved",target:{symbol:i.symbol,file:i.relativePath,callees:ge(s.rows.map(a=>a.symbol)),paramCount:r.callableSignature(i)?.paramCount??-1}}}var ze=z("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),De=z("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function de(e,n){let{minCallees:t,scope:i,excludeSymbol:r,scanLimit:s}=n,a=n.semantic!==!1,o=ze.get(e,()=>new Map),c=`${t}|${i??""}|${s??""}|${a}`,m=!0,g=0,f=0;return y("similar.callee-fingerprints.resolve",()=>{let l=o.get(c);if(m=l!==void 0,l||(l=Oe(e,{minCallees:t,scope:i,scanLimit:s,semantic:a}),o.set(c,l)),g=l.length,r===void 0)return l;let u=l.filter(d=>d.symbol!==r);return f=l.length-u.length,u},()=>({minCallees:t,scope:i,scanLimit:s,semantic:a,cacheHit:m,corpusSize:g,excludeSymbol:r!==void 0,excludedSymbols:f}))}function qe(e,n){let{minCallees:t,scope:i,scanLimit:r}=n,s=n.semantic!==!1,a=De.get(e,()=>new Map),o=`${t}|${i??""}|${r??""}|${s}`,c=!0,m=0,g=0,f=0;return y("similar.callee-index.resolve",()=>{let l=a.get(o);return c=l!==void 0,l||(l=Ne(de(e,{minCallees:t,scope:i,scanLimit:r,semantic:s})),a.set(o,l)),m=l.corpus.length,g=l.docFreq.size,f=l.candidateIndexesByCallee.size,l},()=>({minCallees:t,scope:i,scanLimit:r,semantic:s,cacheHit:c,corpusSize:m,indexedCallees:g,candidateBuckets:f}))}function G(e){return{calleeCorpus:n=>de(e,n),calleeIndex:n=>qe(e,n),sourceCorpus:(n={})=>Ce(e,n),sourceIndex:(n={})=>le(e,n),sourceCandidates:(n,t)=>(t.candidateMode??"full")==="target-pruned"?Qe(e,n,{minSimilarity:t.minSimilarity,scanLimit:t.scanLimit}):Ye(n,le(e,{scanLimit:t.scanLimit}))}}function Ne(e){let n=A(),t=0,i=y("similar.callee-index.doc-frequency",()=>{let l=new Map;for(let u of e)for(let d of u.callees)l.set(d,(l.get(d)??0)+1);return t=l.size,l},()=>({corpusSize:e.length,uniqueCallees:t})),r=Math.max(8,Math.ceil(Math.sqrt(e.length))),s=y("similar.callee-index.idf-weights",()=>V(i,e.length),()=>({corpusSize:e.length,uniqueCallees:i.size})),a=y("similar.callee-index.weighted-magnitudes",()=>e.map(l=>B(l.callees,s)),()=>({corpusSize:e.length})),o=0,c=0,m=0,g=y("similar.callee-index.candidate-buckets",()=>{let l=new Map;for(let u=0;u<e.length;u+=1){let d=e[u];for(let p of d.callees){if((i.get(p)??0)>r){n&&(c+=1);continue}let b=l.get(p);b||(b=[],l.set(p,b)),b.push(u),n&&(o+=1)}}return n&&(m=l.size),l},()=>({corpusSize:e.length,buckets:m,candidateRefs:o,ubiquitousSkips:c,ubiquityThreshold:r})),f=y("similar.callee-index.median-idf",()=>j(s),()=>({uniqueCallees:s.size}));return{corpus:e,candidateIndexesByCallee:g,docFreq:i,idfWeights:s,weightedMagnitudes:a,medianIdf:f,ubiquityThreshold:r}}function Pe(e,n){let t=new Map;for(let i of e.callees)for(let r of n.candidateIndexesByCallee.get(i)??[]){let s=n.corpus[r];s.symbol!==e.symbol&&t.set(s.symbol,s)}return t.size>0?[...t.values()]:n.corpus.filter(i=>i.symbol!==e.symbol)}function Oe(e,n){let{minCallees:t,scope:i,scanLimit:r,semantic:s}=n,a=A(),o=new q(e),c=0,m=y("similar.callee-fingerprints.candidates",()=>{let p=_(o.productionCallableDefinitions({scope:i,minLoc:5,sortByLocDesc:typeof r=="number"&&r>0}),r);return c=p.length,p},()=>({scope:i,scanLimit:r,candidateCount:c})),g=0,f=y("similar.callee-fingerprints.callee-map",()=>{let p=o.calleeEvidenceMap(m,{semantic:s});if(a)for(let b of p.rows.values())g+=b.length;return p},()=>({candidateCount:c,semantic:s,calleeEdges:g})),l=0,u=0,d=0;return y("similar.callee-fingerprints.shape",()=>{let b=m.filter(S=>!f.incompleteSymbolIds.has(S.symbolId)&&!f.unavailableSymbolIds.has(S.symbolId)).map(S=>({symbol:S.symbol,file:S.relativePath,callees:ge((f.rows.get(S.symbolId)??[]).map(F=>F.symbol)),paramCount:o.callableSignature(S)?.paramCount??-1})),C=$e(b);a&&(d=C.filter((S,F)=>S.callees.size!==b[F].callees.size).length);let h=C.filter(S=>S.callees.size>=t);return l=h.length,a&&(u=h.reduce((S,F)=>S+F.callees.size,0)),h},()=>({candidateCount:c,fingerprintCount:l,retainedCalleeCount:u,minCallees:t,siblingSaturatedFingerprints:d}))}var fe=5;function $e(e){let n=new Map;for(let t of e){let i=n.get(t.file);i||(i=new Map,n.set(t.file,i));for(let r of t.callees)i.set(r,(i.get(r)??0)+1)}return e.map(t=>{let i=n.get(t.file);if(!i)return t;let r=[...t.callees].filter(a=>(i.get(a)??0)>=fe);if(r.length===0)return t;let s=new Set(t.callees);for(let a of r)s.delete(a);return{...t,callees:s}})}function _e(e,n){let t=new Map;for(let s of n)if(!(s.file!==e.file||s.symbol===e.symbol))for(let a of s.callees)t.set(a,(t.get(a)??0)+1);let i=[...e.callees].filter(s=>(t.get(s)??0)+1>=fe);if(i.length===0)return e;let r=new Set(e.callees);for(let s of i)r.delete(s);return{...e,callees:r}}function ge(e){return new Set([...e].filter(n=>!je(n)))}function je(e){return Ee.some(n=>e.includes(n))}function Ge(e,n,t){let i=Ve(e,n);if(!i||i.tokens.size<3)return[];let r=t.minSimilarity>=.5?t.minSimilarity:.3,s=[],a=t.candidateMode??"full",o=0,c=0,m=0,g=0;return y("similar.source-shape",()=>{let l=G(e).sourceCandidates(i,{minSimilarity:r,scanLimit:t.scanLimit,candidateMode:a});o=l.length;for(let u of l){if(u.symbol===i.symbol||u.tokens.size<3)continue;c+=1;let d=te(i.tokens,u.tokens);if(d.size<2){m+=1;continue}let p=new Set([...i.tokens,...u.tokens]),b=p.size>0?d.size/p.size:0;if(b<r){g+=1;continue}s.push({symbolA:i.symbol,shortNameA:v(i.symbol),fileA:i.file,symbolB:u.symbol,shortNameB:v(u.symbol),fileB:u.file,similarity:b,similarityBasis:"source-tokens",sharedCallees:[...d].sort(),uniqueToA:[...N(i.tokens,u.tokens)].sort(),uniqueToB:[...N(u.tokens,i.tokens)].sort(),...pe([...d],"source-tokens")})}return s.sort((u,d)=>d.similarity-u.similarity||u.shortNameB.localeCompare(d.shortNameB)),s.slice(0,t.limit)},()=>({symbol:i.symbol,file:i.file,targetTokens:i.tokens.size,candidateMode:a,candidates:o,comparedPairs:c,sharedSkips:m,similaritySkips:g,results:s.length}))}function pe(e,n){let t=e.flatMap(W),i=e.flatMap(b=>ae(b,n)),r=Z(t,be),s=Z(t,Se),a=Z(i,X),o=[...new Set(i.filter(oe))],c=e.filter(b=>{let C=ae(b,n);return C.some(h=>X.has(h))&&C.some(oe)}).length,m=[];r.length>0&&m.push(`access/query scaffolding: ${r.slice(0,5).join(", ")}`),s.length>0&&m.push(`framework/generic scaffolding: ${s.slice(0,5).join(", ")}`),a.length>0&&m.push(`domain behavior verbs: ${a.slice(0,5).join(", ")}`),a.length>0&&o.length>0&&m.push(`domain-specific terms: ${o.slice(0,5).join(", ")}`);let g=n==="source-tokens"&&t.length>0&&t.every(b=>ye.has(b));g&&m.push("shared source tokens are generic scaffolding");let f=a.length>0&&o.length>0,l=r.length+s.length>0,u=n==="callees"&&f&&e.length>=4&&o.length>=4&&c>=2,d=u?"domain-behavior":f?l?"mixed":"domain-behavior":r.length>0?"access-query-scaffolding":s.length>0||g?"framework-scaffolding":"structural-overlap";d==="structural-overlap"&&e.length>0&&m.push(`shared ${n} overlap has no recognized domain or scaffolding category`);let p=d==="domain-behavior"&&(e.length>=3||u)?"direct":"signal";return{evidenceClass:d,actionTier:p,evidenceClassReasons:m,recommendation:Ue(d,p)}}function Ue(e,n){return n==="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 Z(e,n){return[...new Set(e.filter(t=>n.has(t)))]}function W(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(n=>n.length>1)}function ae(e,n){if(n==="source-tokens")return W(e);let t=K(e);return W(t.length>0?t:He(e))}function He(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(i=>i.trim()).filter(i=>/[A-Za-z]/.test(i)).at(-1)?.replace(/\.$/,"")??e}function oe(e){return e.length>3&&!X.has(e)&&!be.has(e)&&!Se.has(e)&&!ye.has(e)&&!Ke.has(e)}var X=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),be=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),Se=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"]),ye=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),Ke=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 Ve(e,n){let t=D(e,n);if(!t||!$(t.symbol))return null;let i=Ze(e,t);return i?{symbol:t.symbol,file:t.relativePath,tokens:i}:null}function Ze(e,n){let t=K(n.symbol),i=sn(e,n.relativePath,n.startLine,n.endLine,t),r=ke(i,t);return r.size>0?r:null}var We=z("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),Xe=z("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function he(e){return`${e.scanLimit??""}`}function Ce(e,n={}){let t=We.get(e,()=>new Map),i=he(n),r=t.get(i);return r||(r=rn(e,n),t.set(i,r)),r}function le(e,n={}){let t=Xe.get(e,()=>new Map),i=he(n),r=t.get(i);return r||(r=Je(Ce(e,n)),t.set(i,r)),r}function Je(e){let n=new Map;for(let r of e)for(let s of r.tokens)n.set(s,(n.get(s)??0)+1);let t=Math.max(8,Math.ceil(Math.sqrt(e.length))),i=new Map;for(let r of e)for(let s of r.tokens){if((n.get(s)??0)>t)continue;let a=i.get(s);a||(a=[],i.set(s,a)),a.push(r)}return{corpus:e,candidateByToken:i,docFreq:n,ubiquityThreshold:t}}function Ye(e,n){let t=new Map;for(let i of e.tokens)for(let r of n.candidateByToken.get(i)??[])r.symbol!==e.symbol&&t.set(r.symbol,r);return t.size>0?[...t.values()]:n.corpus.filter(i=>i.symbol!==e.symbol)}function Qe(e,n,t){let i=A(),r=new q(e),s=en(n.tokens.size,t.minSimilarity),a=0,o=0,c=0,m=y("similar.source-shape.target-files",()=>{let d=[...n.tokens],p=[];for(let b of Y(e,{includeIgnored:!1})){a+=1;let C=U(e,b);C&&(o+=1,nn(C,d,s)&&p.push(b))}return c=p.length,p},()=>({symbol:n.symbol,targetTokens:n.tokens.size,requiredSharedTokens:s,scannedFiles:a,readableFiles:o,candidateFiles:c})),g=0,f=y("similar.source-shape.target-definitions",()=>{let d=_(r.productionCallableDefinitions({files:m,sortByLocDesc:typeof t.scanLimit=="number"&&t.scanLimit>0}),t.scanLimit);return g=d.length,d},()=>({symbol:n.symbol,candidateFiles:c,scanLimit:t.scanLimit,definitionCount:g})),l=0;return y("similar.source-shape.target-fingerprints",()=>{let d=Fe(e,f);return i&&(l=d.length),d},()=>({symbol:n.symbol,definitionCount:g,fingerprintCount:l})).filter(d=>d.symbol!==n.symbol)}function en(e,n){return Math.max(2,Math.ceil(e*n))}function nn(e,n,t){if(n.length<t)return!1;let i=e.toLowerCase(),r=0;for(let s of n)if(tn(i,s)&&(r+=1,r>=t))return!0;return!1}function tn(e,n){return n==="num"?/\b\d+\b/.test(e):e.includes(n)}function rn(e,n={}){let t=new q(e),{scanLimit:i}=n,r=_(t.productionCallableDefinitions({sortByLocDesc:typeof i=="number"&&i>0}),i);return Fe(e,r)}function Fe(e,n){let t=new Map;for(let r of n){let s=t.get(r.relativePath)??[];s.push(r),t.set(r.relativePath,s)}let i=new Map;for(let[r,s]of t){let a=U(e,r);if(!a)continue;let o=J(e,r,a),c=on(e,r,o),m=!1,g=null;for(let f of s){let l=an(f),u=c.get(l),d=u?new Set(u.tokens):null;d||(g??=H(e,r),d=ke(xe(g,f.startLine,f.endLine,f.leaf),f.leaf),c.set(l,{key:l,symbol:f.symbol,startLine:f.startLine,endLine:f.endLine,leaf:f.leaf,tokens:[...d].sort()}),m=!0),d.size>0&&i.set(f.symbol,{symbol:f.symbol,file:f.relativePath,tokens:d})}m&&un(e,r,o,c)}return n.map(r=>i.get(r.symbol)).filter(r=>!!r)}function sn(e,n,t,i,r){let s=H(e,n);return s.length===0?"":xe(s,t,i,r)}function xe(e,n,t,i){if(t>=n&&t-n<=12)return e.slice(n,t+1).join(`
1
+ import{a as te,b as N,e as V,f as j,g as B,h as re,i as se}from"./chunk-NMTSZXCL.js";import{b as _}from"./chunk-B75HZHUP.js";import{c as q}from"./chunk-BPKNP3KZ.js";import{a as ie}from"./chunk-57OPIQFM.js";import{b as ne}from"./chunk-MSI3K7PJ.js";import{a as D}from"./chunk-SGMNWYTH.js";import{d as v,e as K,h as $}from"./chunk-GVAF222T.js";import{a as E}from"./chunk-F74LZWCE.js";import{a as Y}from"./chunk-ICUL7XRT.js";import{h as z,l as J,t as Q,v as ee,w as U,x as H}from"./chunk-7GAK2F3H.js";import{a as A,d as y}from"./chunk-3LCDIREB.js";function Ie(e,n,t={}){let{minSimilarity:i=.4,limit:r=20}=t,s=()=>Ge(e,n,{minSimilarity:i,limit:r,scanLimit:t.scanLimit,candidateMode:t.sourceCandidateMode??"full"}),a=Be(e,n,{semantic:t.semantic!==!1});if(a.kind==="not-callable")return[];if(a.kind==="callee-evidence-unusable")return s();let o=a.target;if(!$(o.symbol))return[];if(o.callees.size===0)return s();let c=we(e,o,i,{scanLimit:t.scanLimit,semantic:t.semantic!==!1});return c.length>0?c.slice(0,r):s()}function Tn(e,n,t,i={}){let r=D(e,n),s=D(e,t);if(!r||!s)return null;let a=Ie(e,r.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:i.semantic,scanLimit:i.scanLimit}).find(m=>m.symbolB===s.symbol||m.symbolA===s.symbol);if(!a)return null;let o=r.endLine-r.startLine+1,c=s.endLine-s.startLine+1;return{symbolA:{symbol:r.symbol,shortName:v(r.symbol),file:r.relativePath,loc:o},symbolB:{symbol:s.symbol,shortName:v(s.symbol),file:s.relativePath,loc:c},similarity:a.similarity,similarityBasis:a.similarityBasis??"callees",sharedEvidence:a.sharedCallees,uniqueToA:a.uniqueToA,uniqueToB:a.uniqueToB,evidenceClass:a.evidenceClass,actionTier:a.actionTier,recommendation:a.recommendation,consolidationStrategy:ve(a)}}function ve(e){let n=e.similarityBasis==="source-tokens"?"source-token":"tracked callee";return e.sharedCallees.length===0?`No shared ${n} evidence survived similar's weighting. Inspect the source before attempting consolidation.`:e.uniqueToA.length===0&&e.uniqueToB.length===0?`The functions have identical ${n} evidence under similar's weighting. Verify signatures, guards, and return values before consolidating.`:e.uniqueToA.length===0?`A's ${n} 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 ${n} 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 ${n}(s). Pass the ${e.uniqueToA.length+e.uniqueToB.length} divergent point(s) as parameters or callbacks.`:`Extract the ${e.sharedCallees.length} shared ${n}(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 we(e,n,t,i){let r=G(e).calleeIndex({minCallees:3,scanLimit:i.scanLimit,semantic:i.semantic}),s=_e(n,r.corpus),a=Pe(s,r),o=Te(s,r),c=j(o),m=B(s.callees,o),g=[];for(let f of a){if(f.callees.size<3)continue;let l=B(f.callees,o),u=ce(s,f,o,{minSimilarity:t,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:m,magnitudeB:l});u&&g.push(u)}return g.sort((f,l)=>l.similarity-f.similarity),g}function Te(e,n){let t=new Map(n.docFreq);for(let i of e.callees)t.set(i,(t.get(i)??0)+1);return V(t,n.corpus.length+1)}function ce(e,n,t,i){let r=Le(e,n,t,i);if(!Re(r,i))return null;let{similarity:s,significantShared:a,trivialShared:o}=r,c=a.length>0?a:o,m=pe(c,"callees");return{symbolA:e.symbol,shortNameA:v(e.symbol),fileA:e.file,symbolB:n.symbol,shortNameB:v(n.symbol),fileB:n.file,similarity:s,similarityBasis:"callees",sharedCallees:c.map(v),uniqueToA:[...N(e.callees,n.callees)].map(v),uniqueToB:[...N(n.callees,e.callees)].map(v),...m}}function Me(e,n,t,i){let r=i.magnitudeA??B(e.callees,t),s=i.magnitudeB??B(n.callees,t),a=0,o=0,c=0,m=i.medianIdf??j(t);for(let l of e.callees){if(!n.callees.has(l))continue;let u=t.get(l)??0;a+=u*u,c+=1,u>=m&&(o+=1)}if(c===0)return!1;let g=r*s;return(g>0?a/g:0)<i.minSimilarity?!1:o>=i.requireSignificantShared||c>=i.requireSharedCount}function Le(e,n,t,i){return i.magnitudeA===void 0||i.magnitudeB===void 0?re(e.callees,n.callees,t,{medianIdf:i.medianIdf}):se(e.callees,n.callees,t,{medianIdf:i.medianIdf,magnitudeA:i.magnitudeA,magnitudeB:i.magnitudeB})}function Re(e,n){if(e.similarity<n.minSimilarity)return!1;let t=e.significantShared.length+e.trivialShared.length;return e.significantShared.length>=n.requireSignificantShared||t>=n.requireSharedCount}function Mn(e,n={}){let{minSimilarity:t=.5,limit:i=20,scope:r,minCallees:s=4,crossFileOnly:a=!1,scanLimit:o}=n,c=n.semantic!==!1,m=A(),g=0,f=0,l=0,u=0,d=0,p=0,b=0;return y("similar.all",()=>{let h=G(e).calleeIndex({minCallees:s,scope:r,scanLimit:o,semantic:c}),S=h.corpus;g=S.length;let F=n.focusFiles,I=[],P=0;return y("similar.all.pair-scan",()=>{for(let k=0;k<S.length;k+=1){let x=S[k],M=F?.has(x.file)??!1,w=h.weightedMagnitudes[k],T=new Set;for(let O of x.callees){let L=h.candidateIndexesByCallee.get(O);if(L)for(let R of L)R<=k||F&&!M&&!F.has(S[R].file)||T.add(R)}m&&(l+=T.size,T.size>0&&(f+=1));for(let O of T){let L=S[O];if(a&&x.file===L.file){m&&(d+=1);continue}if(ue(x,L)){m&&(p+=1);continue}m&&(u+=1);let R=ce(x,L,h.idfWeights,{minSimilarity:t,requireSignificantShared:2,requireSharedCount:4,medianIdf:h.medianIdf,magnitudeA:w,magnitudeB:h.weightedMagnitudes[O]});R&&(Ae(I,R,i,P),m&&(b+=1),P+=1)}}},()=>({corpusSize:g,candidateSets:f,candidatePairs:l,comparedPairs:u,crossFileSkips:d,signatureSkips:p,insertedResults:b,topResults:I.length})),y("similar.all.sort-project",()=>(I.sort((k,x)=>x.result.similarity-k.result.similarity||k.order-x.order),I.map(k=>k.result)),()=>({topResults:I.length}))},()=>({minSimilarity:t,limit:i,scope:r,minCallees:s,crossFileOnly:a,scanLimit:o,semantic:c,corpusSize:g,candidateSets:f,candidatePairs:l,comparedPairs:u,crossFileSkips:d,signatureSkips:p,insertedResults:b}))}function Ln(e,n={}){let{minSimilarity:t=.5,scope:i,minCallees:r=4,crossFileOnly:s=!1,scanLimit:a}=n,o=n.semantic!==!1,c=A(),m=0,g=0,f=0,l=0,u=0,d=0,p=0;return y("similar.all-count",()=>{let C=G(e).calleeIndex({minCallees:r,scope:i,scanLimit:a,semantic:o}),h=C.corpus;m=h.length;let S=n.focusFiles;return y("similar.all-count.pair-scan",()=>{for(let F=0;F<h.length;F+=1){let I=h[F],P=S?.has(I.file)??!1,k=C.weightedMagnitudes[F],x=new Set;for(let M of I.callees){let w=C.candidateIndexesByCallee.get(M);if(w)for(let T of w)T<=F||S&&!P&&!S.has(h[T].file)||x.add(T)}c&&(f+=x.size,x.size>0&&(g+=1));for(let M of x){let w=h[M];if(s&&I.file===w.file){c&&(u+=1);continue}if(ue(I,w)){c&&(d+=1);continue}c&&(l+=1),Me(I,w,C.idfWeights,{minSimilarity:t,requireSignificantShared:2,requireSharedCount:4,medianIdf:C.medianIdf,magnitudeA:k,magnitudeB:C.weightedMagnitudes[M]})&&(p+=1)}}},()=>({corpusSize:m,candidateSets:g,candidatePairs:f,comparedPairs:l,crossFileSkips:u,signatureSkips:d,insertedResults:p})),p},()=>({minSimilarity:t,scope:i,minCallees:r,crossFileOnly:s,scanLimit:a,semantic:o,corpusSize:m,candidateSets:g,candidatePairs:f,comparedPairs:l,crossFileSkips:u,signatureSkips:d,insertedResults:p}))}function ue(e,n){if(e.paramCount<0||n.paramCount<0)return!1;let t=Math.abs(e.paramCount-n.paramCount),i=Math.max(2,Math.ceil(Math.max(e.paramCount,n.paramCount)*.5));return t>i}var me=Q({kind:"source-fingerprints",invalidation:ee("source-fingerprints"),serialize:cn,deserialize:ln});function Ae(e,n,t,i){if(t<=0)return;if(e.length<t){e.push({result:n,order:i});return}let r=0;for(let a=1;a<e.length;a+=1){let o=e[a],c=e[r];(o.result.similarity<c.result.similarity||o.result.similarity===c.result.similarity&&o.order>c.order)&&(r=a)}let s=e[r];n.similarity<=s.result.similarity||(e[r]={result:n,order:i})}var Ee=["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 Be(e,n,t){let i=D(e,n);if(!i)return{kind:"not-callable"};if(!$(i.symbol))return{kind:"not-callable"};let r=new q(e),s=ne(e,i,{semantic:t.semantic,semanticEvidence:ie});return s.semanticIncomplete||s.semanticUnavailable?{kind:"callee-evidence-unusable"}:{kind:"resolved",target:{symbol:i.symbol,file:i.relativePath,callees:ge(s.rows.map(a=>a.symbol)),paramCount:r.callableSignature(i)?.paramCount??-1}}}var ze=z("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),De=z("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function de(e,n){let{minCallees:t,scope:i,excludeSymbol:r,scanLimit:s}=n,a=n.semantic!==!1,o=ze.get(e,()=>new Map),c=`${t}|${i??""}|${s??""}|${a}`,m=!0,g=0,f=0;return y("similar.callee-fingerprints.resolve",()=>{let l=o.get(c);if(m=l!==void 0,l||(l=Oe(e,{minCallees:t,scope:i,scanLimit:s,semantic:a}),o.set(c,l)),g=l.length,r===void 0)return l;let u=l.filter(d=>d.symbol!==r);return f=l.length-u.length,u},()=>({minCallees:t,scope:i,scanLimit:s,semantic:a,cacheHit:m,corpusSize:g,excludeSymbol:r!==void 0,excludedSymbols:f}))}function qe(e,n){let{minCallees:t,scope:i,scanLimit:r}=n,s=n.semantic!==!1,a=De.get(e,()=>new Map),o=`${t}|${i??""}|${r??""}|${s}`,c=!0,m=0,g=0,f=0;return y("similar.callee-index.resolve",()=>{let l=a.get(o);return c=l!==void 0,l||(l=Ne(de(e,{minCallees:t,scope:i,scanLimit:r,semantic:s})),a.set(o,l)),m=l.corpus.length,g=l.docFreq.size,f=l.candidateIndexesByCallee.size,l},()=>({minCallees:t,scope:i,scanLimit:r,semantic:s,cacheHit:c,corpusSize:m,indexedCallees:g,candidateBuckets:f}))}function G(e){return{calleeCorpus:n=>de(e,n),calleeIndex:n=>qe(e,n),sourceCorpus:(n={})=>Ce(e,n),sourceIndex:(n={})=>le(e,n),sourceCandidates:(n,t)=>(t.candidateMode??"full")==="target-pruned"?Qe(e,n,{minSimilarity:t.minSimilarity,scanLimit:t.scanLimit}):Ye(n,le(e,{scanLimit:t.scanLimit}))}}function Ne(e){let n=A(),t=0,i=y("similar.callee-index.doc-frequency",()=>{let l=new Map;for(let u of e)for(let d of u.callees)l.set(d,(l.get(d)??0)+1);return t=l.size,l},()=>({corpusSize:e.length,uniqueCallees:t})),r=Math.max(8,Math.ceil(Math.sqrt(e.length))),s=y("similar.callee-index.idf-weights",()=>V(i,e.length),()=>({corpusSize:e.length,uniqueCallees:i.size})),a=y("similar.callee-index.weighted-magnitudes",()=>e.map(l=>B(l.callees,s)),()=>({corpusSize:e.length})),o=0,c=0,m=0,g=y("similar.callee-index.candidate-buckets",()=>{let l=new Map;for(let u=0;u<e.length;u+=1){let d=e[u];for(let p of d.callees){if((i.get(p)??0)>r){n&&(c+=1);continue}let b=l.get(p);b||(b=[],l.set(p,b)),b.push(u),n&&(o+=1)}}return n&&(m=l.size),l},()=>({corpusSize:e.length,buckets:m,candidateRefs:o,ubiquitousSkips:c,ubiquityThreshold:r})),f=y("similar.callee-index.median-idf",()=>j(s),()=>({uniqueCallees:s.size}));return{corpus:e,candidateIndexesByCallee:g,docFreq:i,idfWeights:s,weightedMagnitudes:a,medianIdf:f,ubiquityThreshold:r}}function Pe(e,n){let t=new Map;for(let i of e.callees)for(let r of n.candidateIndexesByCallee.get(i)??[]){let s=n.corpus[r];s.symbol!==e.symbol&&t.set(s.symbol,s)}return t.size>0?[...t.values()]:n.corpus.filter(i=>i.symbol!==e.symbol)}function Oe(e,n){let{minCallees:t,scope:i,scanLimit:r,semantic:s}=n,a=A(),o=new q(e),c=0,m=y("similar.callee-fingerprints.candidates",()=>{let p=_(o.productionCallableDefinitions({scope:i,minLoc:5,sortByLocDesc:typeof r=="number"&&r>0}),r);return c=p.length,p},()=>({scope:i,scanLimit:r,candidateCount:c})),g=0,f=y("similar.callee-fingerprints.callee-map",()=>{let p=o.calleeEvidenceMap(m,{semantic:s});if(a)for(let b of p.rows.values())g+=b.length;return p},()=>({candidateCount:c,semantic:s,calleeEdges:g})),l=0,u=0,d=0;return y("similar.callee-fingerprints.shape",()=>{let b=m.filter(S=>!f.incompleteSymbolIds.has(S.symbolId)&&!f.unavailableSymbolIds.has(S.symbolId)).map(S=>({symbol:S.symbol,file:S.relativePath,callees:ge((f.rows.get(S.symbolId)??[]).map(F=>F.symbol)),paramCount:o.callableSignature(S)?.paramCount??-1})),C=$e(b);a&&(d=C.filter((S,F)=>S.callees.size!==b[F].callees.size).length);let h=C.filter(S=>S.callees.size>=t);return l=h.length,a&&(u=h.reduce((S,F)=>S+F.callees.size,0)),h},()=>({candidateCount:c,fingerprintCount:l,retainedCalleeCount:u,minCallees:t,siblingSaturatedFingerprints:d}))}var fe=5;function $e(e){let n=new Map;for(let t of e){let i=n.get(t.file);i||(i=new Map,n.set(t.file,i));for(let r of t.callees)i.set(r,(i.get(r)??0)+1)}return e.map(t=>{let i=n.get(t.file);if(!i)return t;let r=[...t.callees].filter(a=>(i.get(a)??0)>=fe);if(r.length===0)return t;let s=new Set(t.callees);for(let a of r)s.delete(a);return{...t,callees:s}})}function _e(e,n){let t=new Map;for(let s of n)if(!(s.file!==e.file||s.symbol===e.symbol))for(let a of s.callees)t.set(a,(t.get(a)??0)+1);let i=[...e.callees].filter(s=>(t.get(s)??0)+1>=fe);if(i.length===0)return e;let r=new Set(e.callees);for(let s of i)r.delete(s);return{...e,callees:r}}function ge(e){return new Set([...e].filter(n=>!je(n)))}function je(e){return Ee.some(n=>e.includes(n))}function Ge(e,n,t){let i=Ve(e,n);if(!i||i.tokens.size<3)return[];let r=t.minSimilarity>=.5?t.minSimilarity:.3,s=[],a=t.candidateMode??"full",o=0,c=0,m=0,g=0;return y("similar.source-shape",()=>{let l=G(e).sourceCandidates(i,{minSimilarity:r,scanLimit:t.scanLimit,candidateMode:a});o=l.length;for(let u of l){if(u.symbol===i.symbol||u.tokens.size<3)continue;c+=1;let d=te(i.tokens,u.tokens);if(d.size<2){m+=1;continue}let p=new Set([...i.tokens,...u.tokens]),b=p.size>0?d.size/p.size:0;if(b<r){g+=1;continue}s.push({symbolA:i.symbol,shortNameA:v(i.symbol),fileA:i.file,symbolB:u.symbol,shortNameB:v(u.symbol),fileB:u.file,similarity:b,similarityBasis:"source-tokens",sharedCallees:[...d].sort(),uniqueToA:[...N(i.tokens,u.tokens)].sort(),uniqueToB:[...N(u.tokens,i.tokens)].sort(),...pe([...d],"source-tokens")})}return s.sort((u,d)=>d.similarity-u.similarity||u.shortNameB.localeCompare(d.shortNameB)),s.slice(0,t.limit)},()=>({symbol:i.symbol,file:i.file,targetTokens:i.tokens.size,candidateMode:a,candidates:o,comparedPairs:c,sharedSkips:m,similaritySkips:g,results:s.length}))}function pe(e,n){let t=e.flatMap(W),i=e.flatMap(b=>ae(b,n)),r=Z(t,be),s=Z(t,Se),a=Z(i,X),o=[...new Set(i.filter(oe))],c=e.filter(b=>{let C=ae(b,n);return C.some(h=>X.has(h))&&C.some(oe)}).length,m=[];r.length>0&&m.push(`access/query scaffolding: ${r.slice(0,5).join(", ")}`),s.length>0&&m.push(`framework/generic scaffolding: ${s.slice(0,5).join(", ")}`),a.length>0&&m.push(`domain behavior verbs: ${a.slice(0,5).join(", ")}`),a.length>0&&o.length>0&&m.push(`domain-specific terms: ${o.slice(0,5).join(", ")}`);let g=n==="source-tokens"&&t.length>0&&t.every(b=>ye.has(b));g&&m.push("shared source tokens are generic scaffolding");let f=a.length>0&&o.length>0,l=r.length+s.length>0,u=n==="callees"&&f&&e.length>=4&&o.length>=4&&c>=2,d=u?"domain-behavior":f?l?"mixed":"domain-behavior":r.length>0?"access-query-scaffolding":s.length>0||g?"framework-scaffolding":"structural-overlap";d==="structural-overlap"&&e.length>0&&m.push(`shared ${n} overlap has no recognized domain or scaffolding category`);let p=d==="domain-behavior"&&(e.length>=3||u)?"direct":"signal";return{evidenceClass:d,actionTier:p,evidenceClassReasons:m,recommendation:Ue(d,p)}}function Ue(e,n){return n==="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 Z(e,n){return[...new Set(e.filter(t=>n.has(t)))]}function W(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(n=>n.length>1)}function ae(e,n){if(n==="source-tokens")return W(e);let t=K(e);return W(t.length>0?t:He(e))}function He(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(i=>i.trim()).filter(i=>/[A-Za-z]/.test(i)).at(-1)?.replace(/\.$/,"")??e}function oe(e){return e.length>3&&!X.has(e)&&!be.has(e)&&!Se.has(e)&&!ye.has(e)&&!Ke.has(e)}var X=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),be=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),Se=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"]),ye=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),Ke=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 Ve(e,n){let t=D(e,n);if(!t||!$(t.symbol))return null;let i=Ze(e,t);return i?{symbol:t.symbol,file:t.relativePath,tokens:i}:null}function Ze(e,n){let t=K(n.symbol),i=sn(e,n.relativePath,n.startLine,n.endLine,t),r=ke(i,t);return r.size>0?r:null}var We=z("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),Xe=z("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function he(e){return`${e.scanLimit??""}`}function Ce(e,n={}){let t=We.get(e,()=>new Map),i=he(n),r=t.get(i);return r||(r=rn(e,n),t.set(i,r)),r}function le(e,n={}){let t=Xe.get(e,()=>new Map),i=he(n),r=t.get(i);return r||(r=Je(Ce(e,n)),t.set(i,r)),r}function Je(e){let n=new Map;for(let r of e)for(let s of r.tokens)n.set(s,(n.get(s)??0)+1);let t=Math.max(8,Math.ceil(Math.sqrt(e.length))),i=new Map;for(let r of e)for(let s of r.tokens){if((n.get(s)??0)>t)continue;let a=i.get(s);a||(a=[],i.set(s,a)),a.push(r)}return{corpus:e,candidateByToken:i,docFreq:n,ubiquityThreshold:t}}function Ye(e,n){let t=new Map;for(let i of e.tokens)for(let r of n.candidateByToken.get(i)??[])r.symbol!==e.symbol&&t.set(r.symbol,r);return t.size>0?[...t.values()]:n.corpus.filter(i=>i.symbol!==e.symbol)}function Qe(e,n,t){let i=A(),r=new q(e),s=en(n.tokens.size,t.minSimilarity),a=0,o=0,c=0,m=y("similar.source-shape.target-files",()=>{let d=[...n.tokens],p=[];for(let b of Y(e,{includeIgnored:!1})){a+=1;let C=U(e,b);C&&(o+=1,nn(C,d,s)&&p.push(b))}return c=p.length,p},()=>({symbol:n.symbol,targetTokens:n.tokens.size,requiredSharedTokens:s,scannedFiles:a,readableFiles:o,candidateFiles:c})),g=0,f=y("similar.source-shape.target-definitions",()=>{let d=_(r.productionCallableDefinitions({files:m,sortByLocDesc:typeof t.scanLimit=="number"&&t.scanLimit>0}),t.scanLimit);return g=d.length,d},()=>({symbol:n.symbol,candidateFiles:c,scanLimit:t.scanLimit,definitionCount:g})),l=0;return y("similar.source-shape.target-fingerprints",()=>{let d=Fe(e,f);return i&&(l=d.length),d},()=>({symbol:n.symbol,definitionCount:g,fingerprintCount:l})).filter(d=>d.symbol!==n.symbol)}function en(e,n){return Math.max(2,Math.ceil(e*n))}function nn(e,n,t){if(n.length<t)return!1;let i=e.toLowerCase(),r=0;for(let s of n)if(tn(i,s)&&(r+=1,r>=t))return!0;return!1}function tn(e,n){return n==="num"?/\b\d+\b/.test(e):e.includes(n)}function rn(e,n={}){let t=new q(e),{scanLimit:i}=n,r=_(t.productionCallableDefinitions({sortByLocDesc:typeof i=="number"&&i>0}),i);return Fe(e,r)}function Fe(e,n){let t=new Map;for(let r of n){let s=t.get(r.relativePath)??[];s.push(r),t.set(r.relativePath,s)}let i=new Map;for(let[r,s]of t){let a=U(e,r);if(!a)continue;let o=J(e,r,a),c=on(e,r,o),m=!1,g=null;for(let f of s){let l=an(f),u=c.get(l),d=u?new Set(u.tokens):null;d||(g??=H(e,r),d=ke(xe(g,f.startLine,f.endLine,f.leaf),f.leaf),c.set(l,{key:l,symbol:f.symbol,startLine:f.startLine,endLine:f.endLine,leaf:f.leaf,tokens:[...d].sort()}),m=!0),d.size>0&&i.set(f.symbol,{symbol:f.symbol,file:f.relativePath,tokens:d})}m&&un(e,r,o,c)}return n.map(r=>i.get(r.symbol)).filter(r=>!!r)}function sn(e,n,t,i,r){let s=H(e,n);return s.length===0?"":xe(s,t,i,r)}function xe(e,n,t,i){if(t>=n&&t-n<=12)return e.slice(n,t+1).join(`
2
2
  `);let r=[new RegExp(`\\bdef\\s+${E(i)}\\b`),new RegExp(`\\bfun\\s+${E(i)}\\b`),new RegExp(`\\bfn\\s+${E(i)}\\b`),new RegExp(`\\bfunction\\s+${E(i)}\\b`),new RegExp(`\\b${E(i)}\\s*\\(`)],s=e.findIndex(a=>r.some(o=>o.test(a)));if(s>=0){let a=s;for(let o=s+1;o<e.length&&o<=s+8;o++){let c=e[o]??"";if(o>s&&dn(c)||(a=o,c.trim()===""&&o>s+1))break}return e.slice(s,a+1).join(`
3
3
  `)}return e.slice(n,Math.min(e.length,n+8)).join(`
4
4
  `)}function an(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function on(e,n,t){return me.read(e,n,t)??new Map}function ln(e){try{let n=JSON.parse(e);if(!Array.isArray(n.entries))return null;let t=new Map;for(let i of n.entries){if(!i||typeof i.key!="string"||typeof i.symbol!="string"||typeof i.startLine!="number"||typeof i.endLine!="number"||typeof i.leaf!="string"||!Array.isArray(i.tokens)||!i.tokens.every(r=>typeof r=="string"))return null;t.set(i.key,i)}return t}catch{return null}}function cn(e){let n={entries:[...e.values()].sort((t,i)=>t.key.localeCompare(i.key))};return JSON.stringify(n)}function un(e,n,t,i){me.write(e,n,t,new Map(i))}function ke(e,n){if(!e)return new Set;let t=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),i=mn(n),s=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(a=>a.trim()).filter(a=>a.length>1).filter(a=>!t.has(a)).filter(a=>!i.has(a));return new Set(s)}function mn(e){return new Set(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9_]+|_/).map(n=>n.toLowerCase()).filter(n=>n.length>1))}function dn(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}export{Ie as a,Tn as b,Te as c,ce as d,Mn as e,Ln as f,Ae as g,de as h,qe as i,G as j,Ne as k,Pe as l,fe as m,$e as n,ge as o,pe as p};
5
- //# sourceMappingURL=chunk-36JC5BG2.js.map
5
+ //# sourceMappingURL=chunk-SUE7SHZL.js.map
@@ -1,4 +1,4 @@
1
- import{c as f}from"./chunk-HENP2O4A.js";import{a as b,d as g}from"./chunk-NDKOVQFG.js";import{d as m}from"./chunk-GVAF222T.js";import{o as u,p as _,q as a}from"./chunk-F74LZWCE.js";import{a as l}from"./chunk-ICUL7XRT.js";import{w as p}from"./chunk-7GAK2F3H.js";function B(e,t={}){let{scope:o,limit:r}=t,i=new f(e),s=T([...x(e,o),...y(e,i,o)]);return F(s),r?s.slice(0,r):s}function x(e,t){let o=[];for(let r of N(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||g(e,r.barrel_path)||p(e,r.barrel_path)&&a(e,r.barrel_path).length===0)continue;let i=I(e,r),s=i?.barrel_consumers??0,n=i?.direct_consumers??0;s!==0||n!==0||o.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:m(r.symbol),originalFile:r.original_path,barrelConsumers:s,directConsumers:n,...h(e,r.barrel_path)})}return o}function N(e,t){let o=t?"AND barrel_d.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`WITH barrel_refs AS MATERIALIZED (
1
+ import{c as f}from"./chunk-BPKNP3KZ.js";import{a as b,d as g}from"./chunk-NDKOVQFG.js";import{d as m}from"./chunk-GVAF222T.js";import{o as u,p as _,q as a}from"./chunk-F74LZWCE.js";import{a as l}from"./chunk-ICUL7XRT.js";import{w as p}from"./chunk-7GAK2F3H.js";function B(e,t={}){let{scope:o,limit:r}=t,i=new f(e),s=T([...x(e,o),...y(e,i,o)]);return F(s),r?s.slice(0,r):s}function x(e,t){let o=[];for(let r of N(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||g(e,r.barrel_path)||p(e,r.barrel_path)&&a(e,r.barrel_path).length===0)continue;let i=I(e,r),s=i?.barrel_consumers??0,n=i?.direct_consumers??0;s!==0||n!==0||o.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:m(r.symbol),originalFile:r.original_path,barrelConsumers:s,directConsumers:n,...h(e,r.barrel_path)})}return o}function N(e,t){let o=t?"AND barrel_d.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`WITH barrel_refs AS MATERIALIZED (
2
2
  SELECT DISTINCT
3
3
  barrel_d.id AS barrel_doc_id,
4
4
  barrel_d.relative_path AS barrel_path,
@@ -71,4 +71,4 @@ import{c as f}from"./chunk-HENP2O4A.js";import{a as b,d as g}from"./chunk-NDKOVQ
71
71
  ${e.pathExclusionsFor("consumer_d")}
72
72
  GROUP BY consumer_d.id
73
73
  )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function y(e,t,o){let r=[],i=C(e);for(let s of O(e,o))E(i,s,s)>0||r.push(...D(e,t,s,i));return r}function O(e,t){return l(e,{scope:t,includeIgnored:!1}).filter(o=>a(e,o).length>0||u(e,o).length>0)}function D(e,t,o,r){let i=a(e,o).filter(n=>n.sourcePath&&!e.isIgnored(n.sourcePath)).flatMap(n=>R(e,t,o,n.sourcePath,r,[A(n.specifier)])),s=u(e,o).filter(n=>n.sourcePath&&!e.isIgnored(n.sourcePath)).flatMap(n=>R(e,t,o,n.sourcePath,r,n.kind==="named"&&n.names.length>0?n.names:[n.kind==="star"?`* from ${n.sourcePath}`:`* namespace from ${n.sourcePath}`]));return[...i,...s]}function R(e,t,o,r,i,s){let n=t.definitionsForFile(r);return s.map(c=>{let d=n.find(S=>S.leaf===c);return{barrelFile:o,symbol:d?.symbol??`source-reexport:${o}:${c}`,shortName:d?m(d.symbol):c,originalFile:r,barrelConsumers:0,directConsumers:E(i,r,o),...h(e,o)}})}function A(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function h(e,t){return b(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 C(e){let t=new Map;for(let o of l(e,{includeIgnored:!1}))for(let r of _(e,o)){if(!r.sourcePath)continue;let i=t.get(r.sourcePath)??new Set;i.add(o),t.set(r.sourcePath,i)}return t}function E(e,t,o){let r=e.get(t);return r?r.size-(r.has(o)?1:0):0}function T(e){let t=new Set,o=[];for(let r of e){let i=`${r.barrelFile}|${r.symbol}|${r.originalFile}`;t.has(i)||(t.add(i),o.push(r))}return o}function F(e){e.sort((t,o)=>o.directConsumers-t.directConsumers||t.barrelFile.localeCompare(o.barrelFile)||t.shortName.localeCompare(o.shortName))}export{B as a};
74
- //# sourceMappingURL=chunk-ZAFGY22Q.js.map
74
+ //# sourceMappingURL=chunk-SZ4P7MF7.js.map