@easbot/codebase 0.3.12 → 0.3.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{chunk-Z4Y3VCYS.mjs → chunk-3LYXIQYD.mjs} +1 -1
- package/dist/chunks/{chunk-RLZHDTHY.cjs → chunk-4A5VTYP7.cjs} +2 -2
- package/dist/chunks/{chunk-4KHRTABC.cjs → chunk-7DCULBXU.cjs} +6 -6
- package/dist/chunks/{chunk-7PW7HWOC.cjs → chunk-ADKQ7Q5L.cjs} +1 -1
- package/dist/chunks/{chunk-RPRDGNXG.cjs → chunk-AWWGTQOD.cjs} +1 -1
- package/dist/chunks/{chunk-W25T3SKH.mjs → chunk-CH3THMQI.mjs} +2 -2
- package/dist/chunks/{chunk-XQID3NKI.mjs → chunk-CUMSGE6Z.mjs} +1 -1
- package/dist/chunks/{chunk-DMRAZKIP.cjs → chunk-F7PTGJKR.cjs} +19 -19
- package/dist/chunks/{chunk-U5G7MP3K.cjs → chunk-LDFLM2CU.cjs} +1 -1
- package/dist/chunks/{chunk-P566CDI2.mjs → chunk-TURKZSUP.mjs} +1 -1
- package/dist/chunks/{chunk-PLRTEGLZ.mjs → chunk-Z66TPGV5.mjs} +13 -13
- package/dist/chunks/{chunk-7ZBQQZOA.mjs → chunk-ZL7LUJKP.mjs} +1 -1
- package/dist/chunks/cli-handler-O4FJ3VNT.mjs +1 -0
- package/dist/chunks/cli-handler-VTJIOO3G.cjs +1 -0
- package/dist/chunks/{code-base-MC4K4ST4.mjs → code-base-EC3JAMYN.mjs} +1 -1
- package/dist/chunks/code-base-FF7YI5C7.cjs +1 -0
- package/dist/chunks/database-manager-AR4NY5FD.mjs +1 -0
- package/dist/chunks/database-manager-WBTGLHRS.cjs +1 -0
- package/dist/chunks/file-watcher-DAS74BJ6.cjs +1 -0
- package/dist/chunks/file-watcher-OUSHAYHW.mjs +1 -0
- package/dist/chunks/{interfaces-4KLR5CPG.cjs → interfaces-55GBUBWQ.cjs} +1 -1
- package/dist/chunks/{interfaces-KGAFAHKZ.mjs → interfaces-IKVZFMWU.mjs} +1 -1
- package/dist/chunks/{stdio-server-C7OYLX4I.mjs → stdio-server-6FUGUP2N.mjs} +1 -1
- package/dist/chunks/{stdio-server-UDX3QZNZ.cjs → stdio-server-P2JPIJI7.cjs} +6 -6
- package/dist/chunks/sync-E3JJBUOP.mjs +1 -0
- package/dist/chunks/sync-EB2UCUW3.cjs +1 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +6 -6
- package/dist/chunks/cli-handler-47R23IC3.cjs +0 -1
- package/dist/chunks/cli-handler-KSSK773Z.mjs +0 -1
- package/dist/chunks/code-base-HBPZXJQZ.cjs +0 -1
- package/dist/chunks/database-manager-DRLNOQ6C.cjs +0 -1
- package/dist/chunks/database-manager-WOYUSWKD.mjs +0 -1
- package/dist/chunks/file-watcher-EASGLNDX.mjs +0 -1
- package/dist/chunks/file-watcher-P3ACFOV5.cjs +0 -1
- package/dist/chunks/sync-6VAWF5IL.mjs +0 -1
- package/dist/chunks/sync-OSAGPUO2.cjs +0 -1
- /package/dist/chunks/{chunk-TS4OAYIJ.cjs → chunk-NL2AZBPZ.cjs} +0 -0
- /package/dist/chunks/{chunk-G3IYU6TZ.mjs → chunk-TFZFSTQF.mjs} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunk7DCULBXU_cjs=require('./chunk-7DCULBXU.cjs'),chunk7XCIIOM6_cjs=require('./chunk-7XCIIOM6.cjs'),chunkNL2AZBPZ_cjs=require('./chunk-NL2AZBPZ.cjs'),utils=require('@easbot/utils'),types=require('@easbot/types');var R=class extends Error{constructor(n,l,a){super(n);chunkNL2AZBPZ_cjs.a(this,"code",l);chunkNL2AZBPZ_cjs.a(this,"details",a);this.name="ServiceError";}},P=class extends R{constructor(t,n=[]){super(`Node not found: ${t}`,"NOT_FOUND",{name:t,candidates:n});}},L=class extends R{constructor(t,n){super(`Ambiguous name "${t}" \u2014 ${n.length} candidates`,"AMBIGUOUS",{name:t,candidates:n});}};utils.Log.create({service:"codebase-service"});var N=utils.Filesystem.toUnixPath;async function k(e,t,n){if(n.nodeId){let o=e.getNode(n.nodeId);if(!o)throw new P(`nodeId=${n.nodeId}`);return {node:o,candidates:[]}}if(!n.name)throw new R("Either name or nodeId is required","NOT_FOUND",n);let a=e.queryNodes({limit:5e3});if(n.file){let o=N(n.file),r=a.filter(c=>N(c.file_path).endsWith(o)||N(c.file_path).includes(o));r.length>0&&(a=r);}if(n.kind){let o=n.kind.toLowerCase(),r=a.filter(c=>c.ast_type.includes(o)||c.name.toLowerCase().includes(o));r.length>0&&(a=r);}let i=a.find(o=>o.name===n.name||o.id.split(":").pop()===n.name);if(i)return {node:i,candidates:[]};let d=chunk7DCULBXU_cjs.l(n.name,a,{limit:10,minScore:.5});if(d.length===0)throw new P(n.name);if(d.length===1){let o=e.getNode(d[0].nodeId);if(!o)throw new P(n.name);return {node:o,candidates:d.map(r=>({node:o,score:r.score}))}}let s=[];for(let o of d){let r=e.getNode(o.nodeId);r&&s.push({node:r,score:o.score});}throw s.length===0?new P(n.name):new L(n.name,s)}async function C(e){let t=chunk7XCIIOM6_cjs.c(e.rootDir),n=new chunk7DCULBXU_cjs.o({workspaceDir:e.workspaceDir,database:{path:t,walMode:true},embedding:types.DEFAULT_EMBEDDING_CONFIG,indexer:types.DEFAULT_INDEXER_CONFIG,parser:types.DEFAULT_PARSER_CONFIG,search:types.DEFAULT_SEARCH_CONFIG,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});return await n.initialize(),n}function de(e,t,n,l){let a=l==="in"?e.source:e.target,i=n.getNodeById(a);return i?{id:i.id,name:i.name,astType:i.ast_type,filePath:N(i.file_path),startLine:i.start_line??0,relation:e.relation}:null}async function V(e,t){let n=Date.now(),d=await(await C(e)).getQuery().search(t.query??"",{maxResults:t.maxResults??10,language:t.language,filePath:t.file,astType:t.astType,includeEdges:true,enableFts:t.enableFts!==false,enableEmbedding:t.enableEmbedding!==false});if(t.kind){let o=t.kind.toLowerCase();d=d.filter(r=>r.ast_type.includes(o)||r.name.toLowerCase().includes(o));}if(t.file){let o=N(t.file);d=d.filter(r=>N(r.file_path).endsWith(o)||N(r.file_path).includes(o));}let s=d.map(o=>({node:o,edges:o.edges??[],source:"basic",score:0,snippet:(o.text??"").slice(0,200).replace(/\s+/g," ").trim()}));return {total:s.length,hits:s,durationMs:Date.now()-n,truncated:false}}async function ue(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await k(l,e,t),d=[];if(t.includeEdges){let s=t.edgesLimit??50;d=a.queryEdges({sourceOrTarget:[i.id],limit:s});}return {node:i,edges:d}}var pe=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function me(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await k(l,e,t);if(!i)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let d=t.depth??2,s=t.maxNodes??100,o=t.direction??"both",r=new Map,c=[{nodeId:i.id,depth:0}];r.set(i.id,0);let p=[],u=false;for(;c.length>0;){let g=c.shift();if(g.depth>=d)continue;if(r.size>=s){u=true;break}let f=l.queryNeighbors(g.nodeId,{direction:o,relationTypes:t.relationTypes??pe,limit:s-r.size+1});for(let h of f.edges){p.push(h);let $=h.source===g.nodeId?h.target:h.source;if(!r.has($)&&(r.set($,g.depth+1),c.push({nodeId:$,depth:g.depth+1}),r.size>=s)){u=true;break}}if(u)break}let m=Array.from(r.keys()),y=m.length>0?a.queryNodes({ids:m}):[],E=new Map(y.map(g=>[g.id,g])),b=[];for(let[g,f]of r.entries()){let h=E.get(g);h&&b.push({node:h,depth:f});}return {root:i,nodes:b,edges:p,truncated:u,totalNodes:b.length,totalEdges:p.length}}var ge=["CALLS","IMPORTS","TYPE_REFERENCES"];async function fe(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await k(l,e,t);if(!i)return {root:null,totalImpacted:0,buckets:[]};let d=t.depth??2,s=t.maxResults??50,o=t.relationTypes??ge,r=new Set([i.id]),c=[],p=[i.id];for(let u=1;u<=d&&!(p.length===0||r.size-1>=s);u++){let m=p.map(()=>"?").join(","),y=o.map(()=>"?").join(","),E=a.queryAll(`SELECT source, target, relation FROM edges WHERE target IN (${m}) AND relation IN (${y})`,[...p,...o]),b=[],g=new Set;for(let f of E)if(!r.has(f.source)&&!g.has(f.source)&&(g.add(f.source),r.add(f.source),b.push(f.source),r.size-1>=s))break;if(b.length>0){let f=b.slice(0,10),h=a.queryNodes({ids:f}),$=new Map(h.map(I=>[I.id,I])),re=f.map(I=>{let B=$.get(I);return {id:I,name:B?.name??"(unknown)",filePath:B?N(B.file_path):"(unknown)",relation:"CALLS"}});c.push({depth:u,count:b.length,sample:re});}p=b;}return {root:i,totalImpacted:r.size-1,buckets:c}}var he=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function ye(e,t){return A(e,t,"incoming")}async function be(e,t){return A(e,t,"outgoing")}async function A(e,t,n,l){let a=await C(e),i=a.getQuery(),d=a.getDatabase(),{node:s}=await k(i,e,t);if(!s)return {root:null,callers:[],truncated:false};let o=t.maxResults??20,r=t.relationTypes??he,c=i.queryNeighbors(s.id,{direction:n,relationTypes:r,limit:o+1}),p=[];for(let m of c.edges){let y=de(m,s.id,d,n==="incoming"?"in":"out");y&&p.push(y);}let u=p.length>o;return {root:s,callers:u?p.slice(0,o):p,truncated:u}}async function Ee(e,t){if(!t.query)throw new R("explore requires a non-empty query","NOT_FOUND",{query:t.query});let l=await C(e);l.getQuery();l.getDatabase();let s=(await V(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true})).hits,o=new Map;for(let p of s){let u=N(p.node.file_path),m=o.get(u);m?m.push(p):o.set(u,[p]);}let r=t.maxSymbols??3,c=[];for(let[p,u]of o){let m=u.slice(0,r),y=[];for(let E of m){let b=await A(e,{name:E.node.name,file:p,kind:t.kind,maxResults:5},"incoming"),g=await A(e,{name:E.node.name,file:p,kind:t.kind,maxResults:5},"outgoing");y.push({node:E.node,callers:b.callers,callees:g.callers});}c.push({file:p,symbols:y});}return {query:t.query,entryPoints:c,totalHits:s.length}}async function xe(e,t){return await(await C(e)).getStatus()}async function Ne(e,t){return await(await C(e)).healthCheck()}var Pe=utils.Filesystem.toUnixPath;function Ce(e){let t=e.text??"";if(!t)return false;let n=t.slice(0,80);return /\bexport\s/.test(n)||/\bpublic\s/.test(n)?true:(false)}function Se(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),l=[];return /\basync\s/.test(n)&&l.push("async"),/\bstatic\s/.test(n)&&l.push("static"),/\babstract\s/.test(n)&&l.push("abstract"),/\breadonly\s/.test(n)&&l.push("readonly"),/\bconst\s/.test(n)&&l.push("const"),/\blet\s/.test(n)&&l.push("let"),l}function x(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:Pe(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:Ce(e),modifiers:Se(e)}}function T(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function G(e,t,n){return e.map((l,a)=>({node:x(l),source:t[a]??"basic",score:n[a]??0,snippet:(l.text??"").slice(0,200).replace(/\s+/g," ").trim(),edges:(l.edges??[]).slice(0,10).map(i=>T(i))}))}function j(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var $e=utils.Log.create({service:"codebase-format-truncate"}),z="**`",Ie="**",Z=24e3,ee=25e3;async function D(e,t={}){let n=t.softLimit??Z,l=t.hardCeiling??ee,a=t.toolName??"codebase",i=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let d=e.slice(0,l),s=d.lastIndexOf(`
|
|
2
2
|
${z}`),o=d.lastIndexOf(`
|
|
3
3
|
`),r;s>l*.5?r=s:o>0?r=o:r=-1;let c=r>0?d.slice(0,r):d,u=c+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!i)return {content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`};try{let m=await utils.TruncateContent.truncate(e,{maxChars:c.length,direction:"head",label:`${a}-output`});return m.truncated?{content:u,truncated:!0,outputPath:m.outputPath,hint:utils.TruncateContent.formatHint(m),info:`... ${m.removedLength}/${m.originalLength} characters truncated ...`}:{content:u,truncated:!0,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`}}catch(m){return $e.warn("TruncateContent.truncate failed, returning without disk hint",{error:m instanceof Error?m.message:String(m)}),{content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`}}}function _(e,t={}){let n=t.softLimit??Z,l=t.hardCeiling??ee;if(e.length<=n)return {content:e,truncated:false};let a=e.slice(0,l),i=a.lastIndexOf(`
|
|
4
4
|
${z}`),d=a.lastIndexOf(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a as a$2,h,f,c,g,n,e,m}from'./chunk-
|
|
1
|
+
import {a as a$2,h,f,c,g,n,e,m}from'./chunk-3LYXIQYD.mjs';import {d}from'./chunk-UTKA3WG3.mjs';import {a as a$1,b}from'./chunk-TFZFSTQF.mjs';import U from'path';import {readFileSync}from'fs';import {fileURLToPath}from'url';import {xdgData}from'xdg-basedir';import {getDefaultDatabasePath,DEFAULT_SYNC_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_SEARCH_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';import {Filesystem,Log,Shell,Glob,Ignore}from'@easbot/utils';import {Worker}from'worker_threads';import {createRequire}from'module';import je from'fs/promises';import {createHash}from'crypto';import {streamText}from'ai';var ke={".ts":"ts",".tsx":"tsx",".js":"js",".jsx":"js",".mjs":"js",".cjs":"js",".py":"py",".rs":"rs",".go":"go",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".java":"java",".scala":"scala",".rb":"ruby",".php":"php",".zig":"zig"};var oe=Filesystem.toUnixPath,Je=`
|
|
2
2
|
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
3
3
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
4
4
|
`,Xe=`
|
|
@@ -231,4 +231,4 @@ ${h}
|
|
|
231
231
|
|
|
232
232
|
Predicted:
|
|
233
233
|
${y}`}function g(h){let y={score:0,details:"",missingEntities:[],extraEntities:[],wrongRelations:[],missingRelations:[]},_=h??"",x=_.trim();if(!x)return {...y,details:"LLM returned empty text"};let E=x,b=E.match(/```(?:json|JSON)?\s*([\s\S]*?)\s*```/);b&&(E=(b[1]??"").trim());let T=E.match(/\{[\s\S]*\}/);if(T)try{let v=JSON.parse(T[0]);return m(v)}catch{}for(let v of E.split(`
|
|
234
|
-
`)){let M=v.trim();if(M.startsWith("{"))try{let w=JSON.parse(M);return m(w)}catch{}}let N=E.match(/(\d+(?:\.\d+)?%?)/g);if(N)for(let v of N){let M=v;M.endsWith("%")&&(M=String(parseFloat(M)/100));let w=parseFloat(M);if(!Number.isNaN(w)&&w>=0&&w<=1)return {...y,score:w,details:`LLM returned non-JSON output; score extracted via heuristic from: ${_.slice(0,200)}`}}return {...y,details:`Failed to parse LLM output: ${_.slice(0,200)}`}}u.parseEvaluationResult=g;function m(h){return {score:typeof h.score=="number"?Math.max(0,Math.min(1,h.score)):0,details:typeof h.details=="string"?h.details:"",missingEntities:Array.isArray(h.missing_entities)?h.missing_entities.filter(_=>typeof _=="string"):[],extraEntities:Array.isArray(h.extra_entities)?h.extra_entities.filter(_=>typeof _=="string"):[],wrongRelations:Array.isArray(h.wrong_relations)?h.wrong_relations.filter(_=>typeof _=="string"):[],missingRelations:Array.isArray(h.missing_relations)?h.missing_relations.filter(_=>typeof _=="string"):[]}}})(ye||(ye={}));var P=Log.create({service:"codebase"}),cr={database:{path:getDefaultDatabasePath(xdgData,"codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true},sync:DEFAULT_SYNC_CONFIG},Ie=class{constructor(e={}){a$1(this,"config");a$1(this,"db");a$1(this,"writeBackend",null);a$1(this,"writeProxy",null);a$1(this,"parserManager");a$1(this,"indexer");a$1(this,"queryInterface");a$1(this,"initialized",false);a$1(this,"dirty",false);a$1(this,"syncTimer");a$1(this,"syncingInProgress",false);a$1(this,"codebasePackageVersion");a$1(this,"fileWatcher",null);this.config={...cr,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||getDefaultDatabasePath(xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...DEFAULT_SEARCH_CONFIG,...e.search},parser:{...DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm,graphLlm:e.graphLlm},ye.init({models:{graphLlm:e.graphLlm,embeddingLlm:e.embeddingLlm}}),this.validateConfig();let n$1=this.resolveDbPath();d(U.dirname(n$1)),this.db=new n(n$1),this.parserManager=new V,this.queryInterface=new X(this.db,this.config.embeddingLlm,this.config.search),this.codebasePackageVersion=dr();}get dbWriter(){return this.writeProxy??this.db}async initialize(){if(!this.initialized){this.db.initialize(),await this.parserManager.initialize(),this.writeBackend=new ue({dbPath:this.db.getDbPath()}),await this.writeBackend.ready,this.writeProxy=new ce(this.db,this.writeBackend,{ftsAvailable:this.db.isFtsAvailable()}),this.indexer=new J(this.db,this.parserManager,{workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??true,embedding:this.config.embeddingLlm},this.writeProxy);try{let e=this.config.workspaceDir??"";this.db.setProjectMetadata("worktree",e),this.db.setProjectMetadata("project",e),this.db.setProjectMetadata("version",this.codebasePackageVersion),this.db.setProjectMetadata("language","ts");}catch(e){P.warn("setProjectMetadata failed",{error:String(e)});}this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>P.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,P.info("Codebase initialized",{workspaceDir:this.config.workspaceDir,dbPath:this.config.database.path,embeddingEnabled:!!this.config.embeddingLlm,syncOnBoot:!!this.config.sync?.onBoot,syncIntervalMs:this.config.sync?.intervalMs??0,batchSize:this.config.indexer?.batchSize,incremental:this.config.indexer?.incremental,languages:this.config.parser?.languages?.length??0});}}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){P.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{P.error("Interval sync failed",{error:String(t)});}));},e));}stopSyncTimer(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=void 0);}ensureSynced(){this.dirty&&!this.syncingInProgress&&this.config.sync?.onSearch&&(this.dirty=false,this.sync().catch(e=>{P.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new e("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new e("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return U.isAbsolute(e)?e:U.join(this.config.workspaceDir,e)}async indexFile(e,t){return await this.ensureInitialized(),this.indexer.indexFile(e,t)}async indexDirectory(e,t){return await this.ensureInitialized(),this.indexer.indexDirectory(e,t)}async sync(e){if(await this.ensureInitialized(),this.syncingInProgress)return P.info("sync skipped \u2014 another sync is already in progress"),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0,skipped:true};this.syncingInProgress=true,this.dbWriter.setIndexState("indexing");try{let t=await this.indexer.sync(e),r=new Date().toISOString();return t.errors.length===0?this.dbWriter.markIndexed(this.codebasePackageVersion,m,r):t.nodesCreated>0||t.filesAdded>0||t.filesUpdated>0?(this.dbWriter.markIndexed(this.codebasePackageVersion,m,r),this.dbWriter.setIndexState("partial")):this.dbWriter.setIndexState("failed"),P.debug("Codebase sync completed",{success:t.success,filesAdded:t.filesAdded,filesUpdated:t.filesUpdated,filesDeleted:t.filesDeleted,filesSkipped:t.filesSkipped,nodesCreated:t.nodesCreated,edgesCreated:t.edgesCreated,errors:t.errors.length,duration:t.duration}),this.writeProxy&&await this.writeProxy.flush(),t}catch(t){throw this.dbWriter.setIndexState("failed"),this.writeProxy&&await this.writeProxy.flush(),t}finally{this.syncingInProgress=false;}}async watch(e){if(await this.ensureInitialized(),this.fileWatcher)return P.warn("watch already running, returning existing instance"),{stop:()=>this.fileWatcher.stop()};let{FileWatcher:t}=await import('./file-watcher-EASGLNDX.mjs'),r=this.config.workspaceDir,n=e?.debounceMs??200,i=e?.initialSync??true,s=new t({workspaceDir:r,ignorePatterns:e?.ignorePatterns??this.config.indexer?.ignorePatterns});this.fileWatcher=s;try{await s.start();}catch(p){throw this.fileWatcher=null,p}let l=null,c=new Set,o=()=>{l=null;let p=c.size;c.clear(),p!==0&&(P.info("file-watcher triggered sync",{changedFiles:p}),this.sync().catch(g=>{P.error("auto-sync after file change failed",{error:g instanceof Error?g.message:String(g)});}));},d=()=>{l&&clearTimeout(l),l=setTimeout(o,n);};return s.on((p,g)=>{P.debug("file change",{event:p,relPath:g}),c.add(g),d();}),i&&this.sync().catch(p=>{P.warn("initial sync in watch failed",{error:p instanceof Error?p.message:String(p)});}),P.info("file watcher started",{workspaceDir:r,debounceMs:n}),{stop:async()=>{l&&(clearTimeout(l),l=null),await s.stop(),this.fileWatcher=null,P.info("file watcher stopped");}}}async search(e,t){return await this.ensureInitialized(),this.ensureSynced(),this.queryInterface.search(e,t)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,t){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,t)}async queryCallGraph(e,t){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,t)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async queryMembers(e,t){return await this.ensureInitialized(),this.queryInterface.queryMembers(e,t)}async queryOverrides(e){return await this.ensureInitialized(),this.queryInterface.queryOverrides(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){let e=this.db.getStatus();return {dbPath:e.dbPath,nodeCount:e.nodeCount,edgeCount:e.edgeCount,indexedFiles:e.indexedFiles,workspaceDir:this.config.workspaceDir,meta:e.meta,healthy:this.initialized,indexState:e.indexState,extractionVersion:e.extractionVersion,isStale:e.isStale,indexedWithVersion:e.meta.indexed_with_version,lastSync:e.meta.lastSync}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let t=this.db.getNodeCount();return t===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:t,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(e={}){this.db.clearAll({keepEmbeddings:e.keepEmbeddings});}async close(){if(this.initialized){if(this.stopSyncTimer(),this.fileWatcher){try{await this.fileWatcher.stop();}catch(e){P.warn("fileWatcher stop during close failed",{error:String(e)});}this.fileWatcher=null;}if(this.writeProxy)try{await this.writeProxy.flush();}catch(e){P.warn("writeProxy flush during close failed",{error:String(e)});}if(this.writeBackend){try{await this.writeBackend.dispose();}catch(e){P.warn("writeBackend dispose during close failed",{error:String(e)});}this.writeBackend=null;}this.writeProxy=null,this.db.close(),this.parserManager.dispose(),this.initialized=false,P.info("Codebase closed");}}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}getWorkspaceDir(){return this.config.workspaceDir??process.cwd()}};async function Kn(f){let e=new Ie(f);return await e.initialize(),e}function dr(){try{let e=U.dirname(fileURLToPath(import.meta.url));for(let t=0;t<8;t++){let r=U.join(e,"package.json");try{let i=JSON.parse(readFileSync(r,"utf-8"));if(i&&i.name==="@easbot/codebase"&&typeof i.version=="string")return i.version}catch{}let n=U.dirname(e);if(n===e)break;e=n;}}catch{}return "0.0.0"}export{Oe as a,ke as b,V as c,Tt as d,wt as e,Y as f,At as g,K as h,Wt as i,J as j,Gt as k,Qe as l,X as m,Jt as n,Ie as o,Kn as p};
|
|
234
|
+
`)){let M=v.trim();if(M.startsWith("{"))try{let w=JSON.parse(M);return m(w)}catch{}}let N=E.match(/(\d+(?:\.\d+)?%?)/g);if(N)for(let v of N){let M=v;M.endsWith("%")&&(M=String(parseFloat(M)/100));let w=parseFloat(M);if(!Number.isNaN(w)&&w>=0&&w<=1)return {...y,score:w,details:`LLM returned non-JSON output; score extracted via heuristic from: ${_.slice(0,200)}`}}return {...y,details:`Failed to parse LLM output: ${_.slice(0,200)}`}}u.parseEvaluationResult=g;function m(h){return {score:typeof h.score=="number"?Math.max(0,Math.min(1,h.score)):0,details:typeof h.details=="string"?h.details:"",missingEntities:Array.isArray(h.missing_entities)?h.missing_entities.filter(_=>typeof _=="string"):[],extraEntities:Array.isArray(h.extra_entities)?h.extra_entities.filter(_=>typeof _=="string"):[],wrongRelations:Array.isArray(h.wrong_relations)?h.wrong_relations.filter(_=>typeof _=="string"):[],missingRelations:Array.isArray(h.missing_relations)?h.missing_relations.filter(_=>typeof _=="string"):[]}}})(ye||(ye={}));var P=Log.create({service:"codebase"}),cr={database:{path:getDefaultDatabasePath(xdgData,"codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true},sync:DEFAULT_SYNC_CONFIG},Ie=class{constructor(e={}){a$1(this,"config");a$1(this,"db");a$1(this,"writeBackend",null);a$1(this,"writeProxy",null);a$1(this,"parserManager");a$1(this,"indexer");a$1(this,"queryInterface");a$1(this,"initialized",false);a$1(this,"dirty",false);a$1(this,"syncTimer");a$1(this,"syncingInProgress",false);a$1(this,"codebasePackageVersion");a$1(this,"fileWatcher",null);this.config={...cr,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||getDefaultDatabasePath(xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...DEFAULT_SEARCH_CONFIG,...e.search},parser:{...DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm,graphLlm:e.graphLlm},ye.init({models:{graphLlm:e.graphLlm,embeddingLlm:e.embeddingLlm}}),this.validateConfig();let n$1=this.resolveDbPath();d(U.dirname(n$1)),this.db=new n(n$1),this.parserManager=new V,this.queryInterface=new X(this.db,this.config.embeddingLlm,this.config.search),this.codebasePackageVersion=dr();}get dbWriter(){return this.writeProxy??this.db}async initialize(){if(!this.initialized){this.db.initialize(),await this.parserManager.initialize(),this.writeBackend=new ue({dbPath:this.db.getDbPath()}),await this.writeBackend.ready,this.writeProxy=new ce(this.db,this.writeBackend,{ftsAvailable:this.db.isFtsAvailable()}),this.indexer=new J(this.db,this.parserManager,{workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??true,embedding:this.config.embeddingLlm},this.writeProxy);try{let e=this.config.workspaceDir??"";this.db.setProjectMetadata("worktree",e),this.db.setProjectMetadata("project",e),this.db.setProjectMetadata("version",this.codebasePackageVersion),this.db.setProjectMetadata("language","ts");}catch(e){P.warn("setProjectMetadata failed",{error:String(e)});}this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>P.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,P.info("Codebase initialized",{workspaceDir:this.config.workspaceDir,dbPath:this.config.database.path,embeddingEnabled:!!this.config.embeddingLlm,syncOnBoot:!!this.config.sync?.onBoot,syncIntervalMs:this.config.sync?.intervalMs??0,batchSize:this.config.indexer?.batchSize,incremental:this.config.indexer?.incremental,languages:this.config.parser?.languages?.length??0});}}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){P.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{P.error("Interval sync failed",{error:String(t)});}));},e));}stopSyncTimer(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=void 0);}ensureSynced(){this.dirty&&!this.syncingInProgress&&this.config.sync?.onSearch&&(this.dirty=false,this.sync().catch(e=>{P.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new e("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new e("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return U.isAbsolute(e)?e:U.join(this.config.workspaceDir,e)}async indexFile(e,t){return await this.ensureInitialized(),this.indexer.indexFile(e,t)}async indexDirectory(e,t){return await this.ensureInitialized(),this.indexer.indexDirectory(e,t)}async sync(e){if(await this.ensureInitialized(),this.syncingInProgress)return P.info("sync skipped \u2014 another sync is already in progress"),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0,skipped:true};this.syncingInProgress=true,this.dbWriter.setIndexState("indexing");try{let t=await this.indexer.sync(e),r=new Date().toISOString();return t.errors.length===0?this.dbWriter.markIndexed(this.codebasePackageVersion,m,r):t.nodesCreated>0||t.filesAdded>0||t.filesUpdated>0?(this.dbWriter.markIndexed(this.codebasePackageVersion,m,r),this.dbWriter.setIndexState("partial")):this.dbWriter.setIndexState("failed"),P.debug("Codebase sync completed",{success:t.success,filesAdded:t.filesAdded,filesUpdated:t.filesUpdated,filesDeleted:t.filesDeleted,filesSkipped:t.filesSkipped,nodesCreated:t.nodesCreated,edgesCreated:t.edgesCreated,errors:t.errors.length,duration:t.duration}),this.writeProxy&&await this.writeProxy.flush(),t}catch(t){throw this.dbWriter.setIndexState("failed"),this.writeProxy&&await this.writeProxy.flush(),t}finally{this.syncingInProgress=false;}}async watch(e){if(await this.ensureInitialized(),this.fileWatcher)return P.warn("watch already running, returning existing instance"),{stop:()=>this.fileWatcher.stop()};let{FileWatcher:t}=await import('./file-watcher-OUSHAYHW.mjs'),r=this.config.workspaceDir,n=e?.debounceMs??200,i=e?.initialSync??true,s=new t({workspaceDir:r,ignorePatterns:e?.ignorePatterns??this.config.indexer?.ignorePatterns});this.fileWatcher=s;try{await s.start();}catch(p){throw this.fileWatcher=null,p}let l=null,c=new Set,o=()=>{l=null;let p=c.size;c.clear(),p!==0&&(P.info("file-watcher triggered sync",{changedFiles:p}),this.sync().catch(g=>{P.error("auto-sync after file change failed",{error:g instanceof Error?g.message:String(g)});}));},d=()=>{l&&clearTimeout(l),l=setTimeout(o,n);};return s.on((p,g)=>{P.debug("file change",{event:p,relPath:g}),c.add(g),d();}),i&&this.sync().catch(p=>{P.warn("initial sync in watch failed",{error:p instanceof Error?p.message:String(p)});}),P.info("file watcher started",{workspaceDir:r,debounceMs:n}),{stop:async()=>{l&&(clearTimeout(l),l=null),await s.stop(),this.fileWatcher=null,P.info("file watcher stopped");}}}async search(e,t){return await this.ensureInitialized(),this.ensureSynced(),this.queryInterface.search(e,t)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,t){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,t)}async queryCallGraph(e,t){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,t)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async queryMembers(e,t){return await this.ensureInitialized(),this.queryInterface.queryMembers(e,t)}async queryOverrides(e){return await this.ensureInitialized(),this.queryInterface.queryOverrides(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){let e=this.db.getStatus();return {dbPath:e.dbPath,nodeCount:e.nodeCount,edgeCount:e.edgeCount,indexedFiles:e.indexedFiles,workspaceDir:this.config.workspaceDir,meta:e.meta,healthy:this.initialized,indexState:e.indexState,extractionVersion:e.extractionVersion,isStale:e.isStale,indexedWithVersion:e.meta.indexed_with_version,lastSync:e.meta.lastSync}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let t=this.db.getNodeCount();return t===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:t,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(e={}){this.db.clearAll({keepEmbeddings:e.keepEmbeddings});}async close(){if(this.initialized){if(this.stopSyncTimer(),this.fileWatcher){try{await this.fileWatcher.stop();}catch(e){P.warn("fileWatcher stop during close failed",{error:String(e)});}this.fileWatcher=null;}if(this.writeProxy)try{await this.writeProxy.flush();}catch(e){P.warn("writeProxy flush during close failed",{error:String(e)});}if(this.writeBackend){try{await this.writeBackend.dispose();}catch(e){P.warn("writeBackend dispose during close failed",{error:String(e)});}this.writeBackend=null;}this.writeProxy=null,this.db.close(),this.parserManager.dispose(),this.initialized=false,P.info("Codebase closed");}}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}getWorkspaceDir(){return this.config.workspaceDir??process.cwd()}};async function Kn(f){let e=new Ie(f);return await e.initialize(),e}function dr(){try{let e=U.dirname(fileURLToPath(import.meta.url));for(let t=0;t<8;t++){let r=U.join(e,"package.json");try{let i=JSON.parse(readFileSync(r,"utf-8"));if(i&&i.name==="@easbot/codebase"&&typeof i.version=="string")return i.version}catch{}let n=U.dirname(e);if(n===e)break;e=n;}}catch{}return "0.0.0"}export{Oe as a,ke as b,V as c,Tt as d,wt as e,Y as f,At as g,K as h,Wt as i,J as j,Gt as k,Qe as l,X as m,Jt as n,Ie as o,Kn as p};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {o,l}from'./chunk-
|
|
1
|
+
import {o,l}from'./chunk-CH3THMQI.mjs';import {c}from'./chunk-UTKA3WG3.mjs';import {a}from'./chunk-TFZFSTQF.mjs';import {Log,Filesystem,TruncateContent}from'@easbot/utils';import {DEFAULT_SEARCH_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';var R=class extends Error{constructor(n,l,a$1){super(n);a(this,"code",l);a(this,"details",a$1);this.name="ServiceError";}},P=class extends R{constructor(t,n=[]){super(`Node not found: ${t}`,"NOT_FOUND",{name:t,candidates:n});}},F=class extends R{constructor(t,n){super(`Ambiguous name "${t}" \u2014 ${n.length} candidates`,"AMBIGUOUS",{name:t,candidates:n});}};Log.create({service:"codebase-service"});var N=Filesystem.toUnixPath;async function D(e,t,n){if(n.nodeId){let o=e.getNode(n.nodeId);if(!o)throw new P(`nodeId=${n.nodeId}`);return {node:o,candidates:[]}}if(!n.name)throw new R("Either name or nodeId is required","NOT_FOUND",n);let a=e.queryNodes({limit:5e3});if(n.file){let o=N(n.file),r=a.filter(c=>N(c.file_path).endsWith(o)||N(c.file_path).includes(o));r.length>0&&(a=r);}if(n.kind){let o=n.kind.toLowerCase(),r=a.filter(c=>c.ast_type.includes(o)||c.name.toLowerCase().includes(o));r.length>0&&(a=r);}let i=a.find(o=>o.name===n.name||o.id.split(":").pop()===n.name);if(i)return {node:i,candidates:[]};let d=l(n.name,a,{limit:10,minScore:.5});if(d.length===0)throw new P(n.name);if(d.length===1){let o=e.getNode(d[0].nodeId);if(!o)throw new P(n.name);return {node:o,candidates:d.map(r=>({node:o,score:r.score}))}}let s=[];for(let o of d){let r=e.getNode(o.nodeId);r&&s.push({node:r,score:o.score});}throw s.length===0?new P(n.name):new F(n.name,s)}async function C(e){let t=c(e.rootDir),n=new o({workspaceDir:e.workspaceDir,database:{path:t,walMode:true},embedding:DEFAULT_EMBEDDING_CONFIG,indexer:DEFAULT_INDEXER_CONFIG,parser:DEFAULT_PARSER_CONFIG,search:DEFAULT_SEARCH_CONFIG,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});return await n.initialize(),n}function ue(e,t,n,l){let a=l==="in"?e.source:e.target,i=n.getNodeById(a);return i?{id:i.id,name:i.name,astType:i.ast_type,filePath:N(i.file_path),startLine:i.start_line??0,relation:e.relation}:null}async function J(e,t){let n=Date.now(),d=await(await C(e)).getQuery().search(t.query??"",{maxResults:t.maxResults??10,language:t.language,filePath:t.file,astType:t.astType,includeEdges:true,enableFts:t.enableFts!==false,enableEmbedding:t.enableEmbedding!==false});if(t.kind){let o=t.kind.toLowerCase();d=d.filter(r=>r.ast_type.includes(o)||r.name.toLowerCase().includes(o));}if(t.file){let o=N(t.file);d=d.filter(r=>N(r.file_path).endsWith(o)||N(r.file_path).includes(o));}let s=d.map(o=>({node:o,edges:o.edges??[],source:"basic",score:0,snippet:(o.text??"").slice(0,200).replace(/\s+/g," ").trim()}));return {total:s.length,hits:s,durationMs:Date.now()-n,truncated:false}}async function pe(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await D(l,e,t),d=[];if(t.includeEdges){let s=t.edgesLimit??50;d=a.queryEdges({sourceOrTarget:[i.id],limit:s});}return {node:i,edges:d}}var me=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function ge(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await D(l,e,t);if(!i)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let d=t.depth??2,s=t.maxNodes??100,o=t.direction??"both",r=new Map,c=[{nodeId:i.id,depth:0}];r.set(i.id,0);let p=[],u=false;for(;c.length>0;){let g=c.shift();if(g.depth>=d)continue;if(r.size>=s){u=true;break}let f=l.queryNeighbors(g.nodeId,{direction:o,relationTypes:t.relationTypes??me,limit:s-r.size+1});for(let h of f.edges){p.push(h);let I=h.source===g.nodeId?h.target:h.source;if(!r.has(I)&&(r.set(I,g.depth+1),c.push({nodeId:I,depth:g.depth+1}),r.size>=s)){u=true;break}}if(u)break}let m=Array.from(r.keys()),y=m.length>0?a.queryNodes({ids:m}):[],E=new Map(y.map(g=>[g.id,g])),b=[];for(let[g,f]of r.entries()){let h=E.get(g);h&&b.push({node:h,depth:f});}return {root:i,nodes:b,edges:p,truncated:u,totalNodes:b.length,totalEdges:p.length}}var fe=["CALLS","IMPORTS","TYPE_REFERENCES"];async function he(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await D(l,e,t);if(!i)return {root:null,totalImpacted:0,buckets:[]};let d=t.depth??2,s=t.maxResults??50,o=t.relationTypes??fe,r=new Set([i.id]),c=[],p=[i.id];for(let u=1;u<=d&&!(p.length===0||r.size-1>=s);u++){let m=p.map(()=>"?").join(","),y=o.map(()=>"?").join(","),E=a.queryAll(`SELECT source, target, relation FROM edges WHERE target IN (${m}) AND relation IN (${y})`,[...p,...o]),b=[],g=new Set;for(let f of E)if(!r.has(f.source)&&!g.has(f.source)&&(g.add(f.source),r.add(f.source),b.push(f.source),r.size-1>=s))break;if(b.length>0){let f=b.slice(0,10),h=a.queryNodes({ids:f}),I=new Map(h.map(L=>[L.id,L])),oe=f.map(L=>{let U=I.get(L);return {id:L,name:U?.name??"(unknown)",filePath:U?N(U.file_path):"(unknown)",relation:"CALLS"}});c.push({depth:u,count:b.length,sample:oe});}p=b;}return {root:i,totalImpacted:r.size-1,buckets:c}}var ye=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function be(e,t){return k(e,t,"incoming")}async function Ee(e,t){return k(e,t,"outgoing")}async function k(e,t,n,l){let a=await C(e),i=a.getQuery(),d=a.getDatabase(),{node:s}=await D(i,e,t);if(!s)return {root:null,callers:[],truncated:false};let o=t.maxResults??20,r=t.relationTypes??ye,c=i.queryNeighbors(s.id,{direction:n,relationTypes:r,limit:o+1}),p=[];for(let m of c.edges){let y=ue(m,s.id,d,n==="incoming"?"in":"out");y&&p.push(y);}let u=p.length>o;return {root:s,callers:u?p.slice(0,o):p,truncated:u}}async function xe(e,t){if(!t.query)throw new R("explore requires a non-empty query","NOT_FOUND",{query:t.query});let l=await C(e);l.getQuery();l.getDatabase();let s=(await J(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true})).hits,o=new Map;for(let p of s){let u=N(p.node.file_path),m=o.get(u);m?m.push(p):o.set(u,[p]);}let r=t.maxSymbols??3,c=[];for(let[p,u]of o){let m=u.slice(0,r),y=[];for(let E of m){let b=await k(e,{name:E.node.name,file:p,kind:t.kind,maxResults:5},"incoming"),g=await k(e,{name:E.node.name,file:p,kind:t.kind,maxResults:5},"outgoing");y.push({node:E.node,callers:b.callers,callees:g.callers});}c.push({file:p,symbols:y});}return {query:t.query,entryPoints:c,totalHits:s.length}}async function Ne(e,t){return await(await C(e)).getStatus()}async function Re(e,t){return await(await C(e)).healthCheck()}var Ce=Filesystem.toUnixPath;function Se(e){let t=e.text??"";if(!t)return false;let n=t.slice(0,80);return /\bexport\s/.test(n)||/\bpublic\s/.test(n)?true:(false)}function Te(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),l=[];return /\basync\s/.test(n)&&l.push("async"),/\bstatic\s/.test(n)&&l.push("static"),/\babstract\s/.test(n)&&l.push("abstract"),/\breadonly\s/.test(n)&&l.push("readonly"),/\bconst\s/.test(n)&&l.push("const"),/\blet\s/.test(n)&&l.push("let"),l}function x(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:Ce(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:Se(e),modifiers:Te(e)}}function $(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function j(e,t,n){return e.map((l,a)=>({node:x(l),source:t[a]??"basic",score:n[a]??0,snippet:(l.text??"").slice(0,200).replace(/\s+/g," ").trim(),edges:(l.edges??[]).slice(0,10).map(i=>$(i))}))}function z(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var Ie=Log.create({service:"codebase-format-truncate"}),Q="**`",Le="**",ee=24e3,te=25e3;async function _(e,t={}){let n=t.softLimit??ee,l=t.hardCeiling??te,a=t.toolName??"codebase",i=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let d=e.slice(0,l),s=d.lastIndexOf(`
|
|
2
2
|
${Q}`),o=d.lastIndexOf(`
|
|
3
3
|
`),r;s>l*.5?r=s:o>0?r=o:r=-1;let c=r>0?d.slice(0,r):d,u=c+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!i)return {content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`};try{let m=await TruncateContent.truncate(e,{maxChars:c.length,direction:"head",label:`${a}-output`});return m.truncated?{content:u,truncated:!0,outputPath:m.outputPath,hint:TruncateContent.formatHint(m),info:`... ${m.removedLength}/${m.originalLength} characters truncated ...`}:{content:u,truncated:!0,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`}}catch(m){return Ie.warn("TruncateContent.truncate failed, returning without disk hint",{error:m instanceof Error?m.message:String(m)}),{content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`}}}function v(e,t={}){let n=t.softLimit??ee,l=t.hardCeiling??te;if(e.length<=n)return {content:e,truncated:false};let a=e.slice(0,l),i=a.lastIndexOf(`
|
|
4
4
|
${Q}`),d=a.lastIndexOf(`
|