@easbot/codebase 0.3.28 → 0.3.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +1 -1
- package/README.md +1 -1
- package/dist/chunks/chunk-23YR2LAM.cjs +1 -0
- package/dist/chunks/chunk-3RVRPGJC.mjs +1 -0
- package/dist/chunks/chunk-3UGOMK4F.cjs +62 -0
- package/dist/chunks/chunk-4XKCGYFF.mjs +158 -0
- package/dist/chunks/chunk-5M2N7JFP.cjs +1 -0
- package/dist/chunks/chunk-A4YJ5ZVE.cjs +203 -0
- package/dist/chunks/chunk-J7AIRI5N.mjs +203 -0
- package/dist/chunks/chunk-LLO6DDXU.mjs +48 -0
- package/dist/chunks/{chunk-GWCRGM4D.mjs → chunk-LQVKXVBS.mjs} +3 -3
- package/dist/chunks/chunk-LZLPJAB6.mjs +62 -0
- package/dist/chunks/chunk-MZHDSOD7.mjs +1 -0
- package/dist/chunks/{chunk-VPWALTY7.cjs → chunk-OGTQ7MWV.cjs} +3 -3
- package/dist/chunks/chunk-V6PHJ4DG.cjs +48 -0
- package/dist/chunks/chunk-YJK7F6NJ.cjs +158 -0
- package/dist/chunks/cli-handler-B7WPIZRE.cjs +1 -0
- package/dist/chunks/cli-handler-EJX27R4Q.mjs +1 -0
- package/dist/chunks/code-base-FSOSU46G.mjs +1 -0
- package/dist/chunks/code-base-OWYMNEQG.cjs +1 -0
- package/dist/chunks/database-manager-7D7NDXJK.mjs +1 -0
- package/dist/chunks/database-manager-X4DMAUWC.cjs +1 -0
- package/dist/chunks/file-watcher-E2JROVI7.cjs +1 -0
- package/dist/chunks/file-watcher-KSLBUUPP.mjs +1 -0
- package/dist/chunks/{interfaces-DPFLQBQ6.mjs → interfaces-S7TJGWWS.mjs} +1 -1
- package/dist/chunks/interfaces-URUTHSR2.cjs +1 -0
- package/dist/chunks/llm-R2ZLKZDO.cjs +1 -0
- package/dist/chunks/llm-U57HNTZO.mjs +1 -0
- package/dist/chunks/stdio-server-DFKFFRSM.cjs +30 -0
- package/dist/chunks/stdio-server-NV5YAXJD.mjs +30 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1098 -80
- package/dist/index.d.ts +1098 -80
- package/dist/index.mjs +1 -1
- package/package.json +9 -9
- package/dist/chunks/chunk-34CU2EU4.mjs +0 -1
- package/dist/chunks/chunk-4HJ7RFP7.cjs +0 -1
- package/dist/chunks/chunk-4TCNRCEK.mjs +0 -48
- package/dist/chunks/chunk-7CL37IYG.mjs +0 -158
- package/dist/chunks/chunk-7N7UVPKB.cjs +0 -48
- package/dist/chunks/chunk-ICEJ23S3.mjs +0 -203
- package/dist/chunks/chunk-JCJFUUU2.cjs +0 -203
- package/dist/chunks/chunk-JVX6PHPN.cjs +0 -1
- package/dist/chunks/chunk-TGCR6O3S.cjs +0 -62
- package/dist/chunks/chunk-UHNJOT5S.cjs +0 -158
- package/dist/chunks/chunk-WRM2FP4O.mjs +0 -62
- package/dist/chunks/chunk-ZPEE2LSX.mjs +0 -1
- package/dist/chunks/cli-handler-DXLDGJFQ.mjs +0 -1
- package/dist/chunks/cli-handler-KKNIISIE.cjs +0 -1
- package/dist/chunks/code-base-BFLIOZXA.cjs +0 -1
- package/dist/chunks/code-base-DMVLROV6.mjs +0 -1
- package/dist/chunks/database-manager-GT3LOQUV.cjs +0 -1
- package/dist/chunks/database-manager-N5WLNG3F.mjs +0 -1
- package/dist/chunks/file-watcher-QS442D52.cjs +0 -1
- package/dist/chunks/file-watcher-X56TEWNY.mjs +0 -1
- package/dist/chunks/interfaces-YX56SVRQ.cjs +0 -1
- package/dist/chunks/llm-ADBGTSCV.mjs +0 -1
- package/dist/chunks/llm-BDMNIGOH.cjs +0 -1
- package/dist/chunks/stdio-server-4X7YFQA2.mjs +0 -30
- package/dist/chunks/stdio-server-5UQVBBZP.cjs +0 -30
package/README.en.md
CHANGED
package/README.md
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var os=require('os'),utils=require('@easbot/utils'),xdgBasedir=require('xdg-basedir');var o=null,r=null;function I(t){o=t;}function h(){o=null;}function n(){if(o)return o;let t=utils.Filesystem.normalize(os.homedir()),i=xdgBasedir.xdgData??utils.Filesystem.join(t,".local","share");return {Path:{home:t,data:process.env.EASBOT_DATA_PATH?.trim()||utils.Filesystem.join(i,"easbot"),config:process.env.EASBOT_CONFIG_PATH?.trim()||(xdgBasedir.xdgConfig?utils.Filesystem.join(xdgBasedir.xdgConfig,"easbot"):utils.Filesystem.join(t,".config","easbot")),state:process.env.EASBOT_STATE_PATH?.trim()||(xdgBasedir.xdgState??utils.Filesystem.join(i,"easbot","state")),cache:process.env.EASBOT_CACHE_PATH?.trim()||(xdgBasedir.xdgCache?utils.Filesystem.join(xdgBasedir.xdgCache,"easbot"):utils.Filesystem.join(t,".cache","easbot")),log:process.env.EASBOT_LOG_PATH?.trim()||(xdgBasedir.xdgState??utils.Filesystem.join(i,"easbot","log")),bin:process.env.EASBOT_BIN_PATH?.trim()||utils.Filesystem.join(t,".local","bin")}}}function j(t){r=t;}function x(){r=null;}function g(){if(r)return r;let t=utils.Filesystem.normalize(process.cwd());return {directory:t,worktree:t}}function l(){return n().Path.home||utils.Filesystem.normalize(os.homedir())}function d(){let t=n().Path.data;return t||(xdgBasedir.xdgData??utils.Filesystem.join(l(),".local","share"))}function T(){let t=n().Path.config;return t||(xdgBasedir.xdgConfig??utils.Filesystem.join(l(),".config"))}function _(){let t=n().Path.state;return t||(xdgBasedir.xdgState??utils.Filesystem.join(d(),"state"))}function P(){let t=n().Path.cache;return t||(xdgBasedir.xdgCache??utils.Filesystem.join(l(),".cache"))}function v(){return utils.Filesystem.normalize(g().directory||process.cwd())}exports.a=I;exports.b=h;exports.c=n;exports.d=j;exports.e=x;exports.f=g;exports.g=l;exports.h=d;exports.i=T;exports.j=_;exports.k=P;exports.l=v;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-2YMB6W5S.mjs';import {existsSync,readFileSync,promises}from'fs';import {isAbsolute,normalize,join}from'path';import {createRequire}from'module';import {Log,Ignore,errorMeta,NameErrors,PKG,Shell}from'@easbot/utils';var o=Log.create({service:"codebase-file-watcher"});function A(){return process.env.EASBOT_CACHE_PATH||join(process.cwd(),".easbot","cache")}var C=["node_modules/**",".git/**","dist/**","build/**","__pycache__/**","*.min.js","*.min.ts",".easbot/**",".codebase/**"],s=class s{constructor(){a(this,"wrapper",null);a(this,"error",null);}static get(){return s.instance||(s.instance=new s),s.instance}static clearCache(){s.instance&&(s.instance.wrapper=null,s.instance.error=null);}};a(s,"instance",null);var b=s;function R(){let r=process.platform==="linux"?`-${globalThis.EASBOT_LIBC||"glibc"}`:"";return `@parcel/watcher-${process.platform}-${process.arch}${r}`}async function T(){let r=b.get();if(r.wrapper)return r.wrapper;if(r.error)throw new NameErrors.OperationFailedError({message:r.error,operation:"parcel-watcher-binding-cache"});let e=R(),t=A(),i;try{await $(e,t)?i=join(t,"node_modules",e):(o.info("Parcel watcher binding not found, attempting to install",{binding:e,cachePath:t}),i=await q(e,t));}catch(u){let p=errorMeta(u).message,f=`binding "${e}" not found and auto-install failed. Run manually: pnpm install ${e}. Error: ${p}`;throw r.error=f,o.error("failed to install parcel watcher binding",{error:errorMeta(u),binding:e}),new NameErrors.OperationFailedError({message:f,operation:"parcel-watcher-binding-install"})}o.info("Loading Parcel watcher binding",{binding:e,modulePath:i});let{createWrapper:g}=await import('@parcel/watcher/wrapper.js'),l=createRequire(join(i,"package.json"))(e),c=g(l);return r.wrapper=c,c}async function $(r,e){try{return !!await PKG.resolve(r,void 0,{extraPaths:[e]})}catch{return false}}async function q(r,e){return o.info("Installing Parcel watcher binding",{binding:r,cachePath:e}),await Shell.install(r,"latest",e),join(e,"node_modules",r)}function P(){return process.platform==="darwin"?"fs-events":process.platform==="linux"?"inotify":process.platform==="win32"?"windows":"brute-force"}var v=class{constructor(e){a(this,"workspaceDir");a(this,"backendOpt");a(this,"ignorePatterns");a(this,"onLoadFailure");a(this,"ignoreInstance");a(this,"listeners",new Set);a(this,"unsubscribe",null);a(this,"disposed",false);a(this,"running",false);this.workspaceDir=isAbsolute(e.workspaceDir)?e.workspaceDir:normalize(e.workspaceDir),this.backendOpt=e.backend??"auto",this.ignorePatterns=e.ignorePatterns??[...C],this.onLoadFailure=e.onLoadFailure??"throw",this.ignoreInstance=Ignore.create().add(this.ignorePatterns);}getIgnoreInstance(){return this.ignoreInstance}getIgnorePatterns(){return this.ignorePatterns}getActiveBackend(){return this.backendOpt==="auto"?P():this.backendOpt}on(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async start(){if(this.running)return;this.running=true;let e=this.backendOpt==="auto"?P():this.backendOpt;o.info("FileWatcher start",{workspaceDir:this.workspaceDir,backend:e});let t;try{t=await T();}catch(i){if(this.running=false,this.onLoadFailure==="warn")return;throw i}await this.subscribeWithParcel(t,e);}async stop(){if(this.unsubscribe){try{await this.unsubscribe();}catch(e){o.warn("parcel unsubscribe error",{error:errorMeta(e)});}this.unsubscribe=null;}this.running=false;}async dispose(){await this.stop(),this.disposed=true,this.listeners.clear();}isRunning(){return this.running}isDisposed(){return this.disposed}static clearParcelWrapperCache(){b.clearCache();}async subscribeWithParcel(e,t){if(this.disposed)throw new NameErrors.OperationFailedError({message:"FileWatcher disposed before subscribe",operation:"file-watcher-disposed"});let i=(a,l)=>{if(this.disposed)return;let c=this.workspaceDir.replace(/\\/g,"/").replace(/\/$/,""),u=l.replace(/\\/g,"/"),p=l;if(u.startsWith(c+"/")&&(p=u.slice(c.length+1)),this.ignoreInstance.ignores(p,a==="create"&&p.endsWith("/")))return;let f=a==="create"?"add":a==="delete"?"unlink":"change";for(let y of this.listeners)try{y(f,p);}catch(W){o.warn("listener threw",{error:errorMeta(W)});}},g=await e.subscribe(this.workspaceDir,(a,l)=>{if(a){o.error("parcel subscribe callback error",{error:errorMeta(a)});return}for(let c of l)i(c.type,c.path);},{ignore:[...this.ignorePatterns],backend:t});if(this.disposed){await g.unsubscribe().catch(()=>{});return}this.unsubscribe=async()=>{await g.unsubscribe().catch(a=>{o.warn("parcel unsubscribe error",{error:errorMeta(a)});});};}};function m(r){return join(r,".watcher.pid")}function z(r){let e=m(r);if(!existsSync(e))return null;try{let t=readFileSync(e,"utf-8").trim(),i=parseInt(t,10);return Number.isFinite(i)?i:null}catch{return null}}async function K(r,e){let t=m(r);await promises.writeFile(t,String(e),"utf-8");}async function U(r){let e=m(r);try{await promises.unlink(e);}catch{}}export{v as a,m as b,z as c,K as d,U as e};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
'use strict';var chunkA4YJ5ZVE_cjs=require('./chunk-A4YJ5ZVE.cjs'),chunkYJK7F6NJ_cjs=require('./chunk-YJK7F6NJ.cjs'),utils=require('@easbot/utils'),types=require('@easbot/types'),fs=require('fs');var J=utils.Log.create({service:"codebase-service"}),N=utils.Filesystem.toUnixPath;function xe(e,t){let r={exact:1,qualified:.85,substring:.5}[e];return t?Math.min(1,r+.2):r}function Ne(e,t){if(!t)return false;if(e===t)return true;let r=e.split(/[/\\]/).pop()??"",o=t.split(/[/\\]/).pop()??"";return !!(r&&o&&r===o||t.includes("/")&&e.endsWith("/"+t))}async function T(e,t,r){if(r.nodeId){let i=e.getNode(r.nodeId);if(!i)throw new utils.ServiceError({code:"NOT_FOUND",message:`Node not found: nodeId=${r.nodeId}`,details:{name:r.nodeId}});return {node:i,candidates:[]}}if(!r.name)throw new utils.ServiceError({code:"NOT_FOUND",message:"Either name or nodeId is required",details:{...r}});let l=e.getDatabase().findNodesByName({name:r.name,file:r.file,kind:r.kind,limit:50});if(l.length===0)throw new utils.ServiceError({code:"NOT_FOUND",message:`Node not found: ${r.name}`,details:{name:r.name,candidates:[]}});let a=!!r.file,c=r.file?N(r.file):null,s=l.map(i=>{let m=c?Ne(N(i.node.file_path),c):false;return {node:i.node,score:xe(i.matchKind,m),matchKind:i.matchKind,inFile:m}});if(s.sort((i,m)=>m.score-i.score),s.length===1)return {node:s[0].node,candidates:s.map(i=>({node:i.node,score:i.score}))};let d=s[0].score,n=s.filter(i=>i.score===d);if(n.length===1)return {node:n[0].node,candidates:s.slice(0,10).map(i=>({node:i.node,score:i.score}))};if(a&&n.length>1){let i=n.filter(m=>m.inFile);if(i.length===1)return {node:i[0].node,candidates:s.slice(0,10).map(m=>({node:m.node,score:m.score}))}}throw new utils.ServiceError({code:"AMBIGUOUS",message:`Ambiguous name "${r.name}" \u2014 ${s.length} candidates`,details:{name:r.name,candidates:s.slice(0,10).map(i=>({node:i.node,score:i.score}))}})}async function P(e){let t=chunkA4YJ5ZVE_cjs.c(e.rootDir),r=new chunkA4YJ5ZVE_cjs.x({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 r.initialize(),r}function U(e,t,r,o){let l=r.map(()=>"?").join(","),a=t.name.split("@")[0]??t.name,c=a.includes(".")?a.split(".").pop()??a:a,s=new Set([`${t.language}:*:*:${a}`]);c!==a&&s.add(`${t.language}:*:*:${c}`);let d=[];c!==a&&d.push(`${t.language}:*:*:%${c}`);let n=Array.from(s),i=n.map(()=>"?").join(","),u=d.length>0?"OR LOWER(target) LIKE LOWER(?)":"";n.length>1&&J.warn("queryIncomingEdgesWithWildcard: multi-variant wildcards (bare+namespaced)",{rootName:t.name,wildcards:n,hint:"\u540C\u540D\u540C namespace \u4E0D\u540C file \u7684\u65B9\u6CD5\u53EF\u80FD\u90FD\u88AB\u547D\u4E2D\uFF0CLLM \u63A8\u7406\u8BF7\u7528 file \u8FC7\u6EE4\u8F85\u4F50"});let g=`
|
|
2
|
+
SELECT id, source, target, relation, created_at FROM edges
|
|
3
|
+
WHERE relation IN (${l})
|
|
4
|
+
AND source != target
|
|
5
|
+
AND (
|
|
6
|
+
target = ?
|
|
7
|
+
OR target IN (${i})
|
|
8
|
+
${u}
|
|
9
|
+
)
|
|
10
|
+
GROUP BY id
|
|
11
|
+
LIMIT ?
|
|
12
|
+
`;return e.queryAll(g,[...r,t.id,...n,...d,o])}function Pe(e){return e==="class_declaration"||e==="class_definition"||e==="interface_declaration"||e==="struct_declaration"||e==="struct_specifier"||e==="record_declaration"}function Re(e,t,r,o,l){let c=e.queryAll("SELECT id FROM nodes WHERE file_path = ? AND start_line >= ? AND end_line <= ? AND ast_type IN ('method_definition', 'method_declaration') LIMIT 1000",[t.file_path,t.start_line,t.end_line]).map(n=>n.id),s=new Set,d=[];for(let n of r)n.id&&!s.has(n.id)&&(s.add(n.id),d.push(n));if(c.length>0){let n=o.map(()=>"?").join(","),i=c.map(()=>"?").join(","),m=`
|
|
13
|
+
SELECT id, source, target, relation, created_at FROM edges
|
|
14
|
+
WHERE relation IN (${n})
|
|
15
|
+
AND source != target
|
|
16
|
+
AND source IN (${i})
|
|
17
|
+
GROUP BY id
|
|
18
|
+
LIMIT ?
|
|
19
|
+
`,u=e.queryAll(m,[...o,...c,l]);for(let g of u)g.id&&!s.has(g.id)&&(s.add(g.id),d.push(g));}return d.slice(0,l)}function Z(e,t,r,o){let a=`
|
|
20
|
+
SELECT id, source, target, relation, created_at FROM edges
|
|
21
|
+
WHERE relation IN (${r.map(()=>"?").join(",")})
|
|
22
|
+
AND source != target
|
|
23
|
+
AND source = ?
|
|
24
|
+
LIMIT ?
|
|
25
|
+
`;return e.queryAll(a,[...r,t.id,o])}function ee(e,t,r,o){let l=o==="in"?e.source:e.target;t.id;let c=r.getNodeById(l);if(!c&&l.includes(":*:")){let s=l.split(":").pop()??l,d=s.split("@")[0]??s;if(d&&d!==l){let n=r.findNodesByName({name:d}),i=t.file_path??"",m=i.split(/[/\\]/).pop()??"",u=i.split(/[/\\]/).filter(Boolean),g=n.find(p=>p.node.file_path?p.node.file_path===i:false)??n.find(p=>!p.node.file_path||!m?false:p.node.file_path.split(/[/\\]/).pop()===m)??n.find(p=>{if(!p.node.file_path)return false;let f=p.node.file_path.split(/[/\\]/).filter(Boolean);return u.length<2||f.length<2?false:u[0]===f[0]&&u[1]===f[1]})??null;g&&(c=g.node);}}if(!c){let s=l.split(":").pop()??l;return {id:l,name:s,astType:"unresolved",filePath:"(unresolved)",startLine:0,relation:e.relation}}return {id:c.id,name:c.name,astType:c.ast_type,filePath:N(c.file_path),startLine:c.start_line??0,relation:e.relation}}async function te(e,t){let r=Date.now(),c=await(await P(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 n=t.kind.toLowerCase();c=c.filter(i=>i.ast_type.includes(n)||i.name.toLowerCase().includes(n));}if(t.file){let n=N(t.file);c=c.filter(i=>N(i.file_path).endsWith(n)||N(i.file_path).includes(n));}let s=t.maxEdgesPerNode??10,d=c.map(n=>({nodeId:n.id,name:n.name,kind:n.ast_type??"unknown",filePath:N(n.file_path),startLine:n.start_line,endLine:n.end_line,edges:(n.edges??[]).slice(0,s),source:"basic",score:0,snippet:(n.text??"").slice(0,200).replace(/\s+/g," ").trim()}));return {total:d.length,hits:d,durationMs:Date.now()-r,truncated:false}}async function Se(e,t){let r=await P(e),o=r.getQuery(),l=r.getDatabase(),{node:a}=await T(o,e,t),c=[];if(t.includeEdges){let s=t.maxEdgesPerNode??10,d=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"],n=U(l,a,d,s+1),i=Z(l,a,d,s+1),m=new Set,u=[];for(let g of [...n,...i])g.id&&!m.has(g.id)&&(m.add(g.id),u.push(g));c=u.slice(0,s);}return {node:a,edges:c}}var Ce=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function Ie(e,t){let r=await P(e),o=r.getQuery(),l=r.getDatabase(),{node:a}=await T(o,e,t);if(!a)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let c=t.depth??2,s=t.maxNodes??100,d=t.direction??"both";t.maxEdgesPerNode??10;let i=new Map,m=[{nodeId:a.id,depth:0}];i.set(a.id,0);let u=[],g=false;for(;m.length>0;){let h=m.shift();if(h.depth>=c)continue;if(i.size>=s){g=true;break}let F=o.queryNeighbors(h.nodeId,{direction:d,relationTypes:t.relationTypes??Ce,limit:s-i.size+1});for(let y of F.edges){u.push(y);let I=y.source===h.nodeId?y.target:y.source;if(!i.has(I)&&(i.set(I,h.depth+1),m.push({nodeId:I,depth:h.depth+1}),i.size>=s)){g=true;break}}if(g)break}let p=new Set,f=[];for(let h of u)!h.id||p.has(h.id)||(p.add(h.id),f.push(h));let b=Array.from(i.keys()),E=b.length>0?l.queryNodes({ids:b}):[],C=new Map(E.map(h=>[h.id,h])),x=[];for(let[h,F]of i.entries()){let y=C.get(h);y&&x.push({node:y,depth:F});}return {root:a,nodes:x,edges:f,truncated:g,totalNodes:x.length,totalEdges:u.length}}var Le=["CALLS","IMPORTS","TYPE_REFERENCES"];async function Te(e,t){let r=await P(e),o=r.getQuery(),l=r.getDatabase(),{node:a}=await T(o,e,t);if(!a)return {root:null,totalImpacted:0,buckets:[]};let c=t.depth??2,s=t.maxResults??10,d=t.relationTypes??Le,n=t.maxEdgesPerNode??10,i=new Set([a.id]),m=[],u=[a.id];for(let g=1;g<=c&&!(u.length===0||i.size-1>=s);g++){let p=U(l,a,d,n+1),f=[],b=new Set;for(let E of p)if(!i.has(E.source)&&!b.has(E.source)&&(b.add(E.source),i.add(E.source),f.push(E.source),i.size-1>=s))break;if(f.length>0){let E=f.slice(0,10),C=l.queryNodes({ids:E}),x=new Map(C.map(y=>[y.id,y])),h=new Map;for(let y of p)h.has(y.source)||h.set(y.source,y.relation);let F=E.map(y=>{let I=x.get(y);return {id:y,name:I?.name??"(unknown)",filePath:I?N(I.file_path):"(unknown)",relation:h.get(y)??"CALLS"}});m.push({depth:g,count:f.length,sample:F});}u=f;}return m.length===0&&J.warn("impact: no incoming edges found",{root:a.name,depth:c,relationTypes:d}),{root:a,totalImpacted:i.size-1,buckets:m}}var ne=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function $e(e,t){return re(e,t)}async function _e(e,t){return oe(e,t)}async function re(e,t){let r=await P(e),o=r.getQuery(),l=r.getDatabase(),{node:a}=await T(o,e,t);if(!a)return {root:null,callers:[],truncated:false};let c=t.maxResults??10,s=t.maxEdgesPerNode??c,d=t.relationTypes??ne,n=U(l,a,d,s+1),i=[];for(let u of n){let g=ee(u,a,l,"in");g&&i.push(g);}let m=i.length>c;return {root:a,callers:m?i.slice(0,c):i,truncated:m}}async function oe(e,t){let r=await P(e),o=r.getQuery(),l=r.getDatabase(),{node:a}=await T(o,e,t);if(!a)return {root:null,callees:[],truncated:false};let c=t.maxResults??10,s=t.maxEdgesPerNode??c,d=t.relationTypes??ne,n=Z(l,a,d,s+1),i=Pe(a.ast_type)?Re(l,a,n,d,s+1):n,m=[];for(let g of i){let p=ee(g,a,l,"out");p&&m.push(p);}let u=m.length>c;return {root:a,callees:u?m.slice(0,c):m,truncated:u}}async function we(e,t){if(!t.query)throw new utils.ServiceError({code:"NOT_FOUND",message:"explore requires a non-empty query",details:{query:t.query}});let o=await P(e),l=o.getQuery(),a=o.getDatabase(),s=(await te(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true})).hits;if(t.file||t.kind)try{let u=await T(l,e,{name:t.query,file:t.file,kind:t.kind});if(u?.node){let g={nodeId:u.node.id,name:u.node.name,kind:u.node.ast_type,filePath:N(u.node.file_path),startLine:u.node.start_line,endLine:u.node.end_line,edges:[],source:"basic",score:0,snippet:(u.node.text??"").slice(0,200).replace(/\s+/g," ").trim()},p=s.filter(f=>f.nodeId!==g.nodeId);s=[g,...p];}}catch{}let d=new Map;for(let u of s){let g=N(u.filePath),p=d.get(g);p?p.push(u):d.set(g,[u]);}let n=t.maxSymbols??3,i=t.maxEdgesPerNode??10,m=[];for(let[u,g]of d){let p=g.slice(0,n),f=[];for(let b of p){let E=await re(e,{name:b.name,file:u,kind:t.kind,maxResults:i,maxEdgesPerNode:i}),C=await oe(e,{name:b.name,file:u,kind:t.kind,maxResults:i,maxEdgesPerNode:i});f.push({node:(()=>{let x={id:b.nodeId,name:b.name,ast_type:b.kind,language:"ts",file_path:b.filePath,start_line:b.startLine??0,end_line:b.endLine??0};try{let h=a.getNodeById(b.nodeId);return {...x,text:h?.text??""}}catch{return {...x,text:""}}})(),callers:E.callers,callees:C.callees});}m.push({file:u,symbols:f});}return {query:t.query,entryPoints:m,totalHits:s.length}}async function Fe(e,t){let o=await(await P(e)).getStatus();o.package="codebase",o.workspaceDir=e.workspaceDir;let l=chunkA4YJ5ZVE_cjs.b(e.workspaceDir),a=fs.existsSync(l),c=fs.existsSync(o.dbPath),s;if(c)try{s=fs.statSync(o.dbPath).size;}catch{}o.configPath=l,o.configExists=a,o.dbExists=c,o.dbSize=s,o.vectorEnabled=o.meta?.vector_enabled==="true"||o.meta?.vector_enabled==="1";let d=o.meta?.embeddingDims;d&&Number.isFinite(Number.parseInt(d,10))&&(o.embeddingDims=Number.parseInt(d,10));let n={initialized:false,capabilities:{embedding:false,graphLlm:false}};try{let{Llm:i}=await import('./llm-R2ZLKZDO.cjs');if(i.isInitialized()){n.initialized=!0;let m=i.capabilities();n.capabilities={embedding:m.embedding===!0,graphLlm:m.graphLlm===!0},n.embeddingModel=n.capabilities.embedding?"configured":void 0,n.graphModel=n.capabilities.graphLlm?"configured":void 0;}}catch{}o.llm=n;try{let{DatabaseManager:i}=await import('./database-manager-X4DMAUWC.cjs'),m=new i(o.dbPath);try{let{stats:u}=m.checkIntegrity();o.dbStats=u,o.ftsAvailable=m.isFtsAvailable();}finally{m.close();}}catch{}return o}async function Ae(e,t){return await(await P(e)).healthCheck()}var ke=utils.Log.create({service:"codebase-service-init"}),se=false;async function ve(){se||(se=true,ke.info("codebase service init"),await utils.ServiceErrorBus.init(),await chunkYJK7F6NJ_cjs.e());}var ie=utils.Filesystem.toUnixPath;function He(e){let t=e.text??"";if(!t)return false;let r=t.slice(0,80);return /\bexport\s/.test(r)||/\bpublic\s/.test(r)?true:(false)}function qe(e){let t=e.text??"";if(!t)return [];let r=t.slice(0,80),o=[];return /\basync\s/.test(r)&&o.push("async"),/\bstatic\s/.test(r)&&o.push("static"),/\babstract\s/.test(r)&&o.push("abstract"),/\breadonly\s/.test(r)&&o.push("readonly"),/\bconst\s/.test(r)&&o.push("const"),/\blet\s/.test(r)&&o.push("let"),o}function R(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:ie(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:He(e),modifiers:qe(e)}}function $(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function z(e){return e.map(t=>({node:{id:t.nodeId,name:t.name,astType:t.kind,language:"typescript",filePath:ie(t.filePath),startLine:t.startLine??0,endLine:t.endLine??0,isExported:false,modifiers:[]},source:t.source,score:t.score,snippet:(t.snippet??"").slice(0,200),edges:(t.edges??[]).slice(0,10).map(r=>$({...r}))}))}function K(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var ze=utils.Log.create({service:"codebase-format-truncate"}),j="**`",Ke="**",le=24e3,de=25e3;async function D(e,t={}){let r=t.softLimit??le,o=t.hardCeiling??de,l=t.toolName??"codebase",a=t.writeToDisk!==false;if(e.length<=r)return {content:e,truncated:false};let c=e.slice(0,o),s=c.lastIndexOf(`
|
|
26
|
+
${j}`),d=c.lastIndexOf(`
|
|
27
|
+
`),n;s>o*.5?n=s:d>0?n=d:n=-1;let i=n>0?c.slice(0,n):c,u=i+"\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(!a)return {content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-i.length}/${e.length} characters truncated ...`};try{let g=await utils.TruncateContent.truncate(e,{maxChars:i.length,direction:"head",label:`${l}-output`});return g.truncated?{content:u,truncated:!0,outputPath:g.outputPath,hint:utils.TruncateContent.formatHint(g),info:`... ${g.removedLength}/${g.originalLength} characters truncated ...`}:{content:u,truncated:!0,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-i.length}/${e.length} characters truncated ...`}}catch(g){return ze.warn("TruncateContent.truncate failed, returning without disk hint",{error:utils.errorMeta(g)}),{content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-i.length}/${e.length} characters truncated ...`}}}function O(e,t={}){let r=t.softLimit??le,o=t.hardCeiling??de;if(e.length<=r)return {content:e,truncated:false};let l=e.slice(0,o),a=l.lastIndexOf(`
|
|
28
|
+
${j}`),c=l.lastIndexOf(`
|
|
29
|
+
`),s;a>o*.5?s=a:c>0?s=c:s=-1;let d=s>0?l.slice(0,s):l;return {content:d+`
|
|
30
|
+
|
|
31
|
+
... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}function je(e,t=Date.now()){let r=Math.max(0,Math.floor((t-e)/1e3));return r>60?">60s ago":`${r}s ago`}function k(e,t){if(!e||e.length===0)return null;let r=e.filter(l=>t.has(l.path));return r.length===0?null:`\u26A0\uFE0F Index may be stale for: ${r.map(l=>`${l.path} (edited ${je(l.lastEventAt)})`).join(", ")}
|
|
32
|
+
|
|
33
|
+
`}function A(e,t,r={}){return (ce[e]??ce.default).replace(/<(\w+)>/g,(l,a)=>a==="tool"?t:r[a]??`<${a}>`)}var ce={search:`---
|
|
34
|
+
|
|
35
|
+
> **Complete source for N files is included above \u2014 do NOT re-read them.**
|
|
36
|
+
> If your question also needs files/symbols listed under "Not shown above" (or any area this call didn't cover), make ANOTHER \`<tool>\` targeting those names \u2014 it returns the same source with line numbers and is cheaper and more complete than reading.`,impact:"---\n\n> **Risk: <riskLevel>**. Before editing `<root>`, review d=1 first \u2014 those WILL BREAK.\n> Use `<tool>` to read full source of any direct caller.",context:"---\n\n> **Use `impact` for blast-radius analysis. Use `explore` to read source.**",default:`---
|
|
37
|
+
|
|
38
|
+
> **Output truncated to budget; the content above is the source of truth.**
|
|
39
|
+
> For more detail, call \`<tool>\` with refined parameters.`};async function v(e,t){let{pendingFiles:r,toolName:o,sync:l=false}=t;if(e.length===0)return _(o,"No matches found.","Try broader search terms, or use `explore` to read source.");let a=Ge(e),c=new Set(a.keys()),s=[];s.push(k(r,c)??"");let d="[[codebase-search-summary]]";s.push(d+`
|
|
40
|
+
`);let n=e.length;s.push(`**Files with matches:** ${a.size}
|
|
41
|
+
`);for(let[g,p]of a){let f=p.map(x=>x.node.name),b=f.slice(0,5).join(", "),E=f.length>5?`, +${f.length-5} more`:"";s.push(`**\`${g}\`** \u2014 ${b}${E}
|
|
42
|
+
`);let C=p[0]?.node.language??"";s.push("```"+C);for(let x of p)s.push(`L${x.node.startLine} ${x.snippet}`);s.push("```\n");}s.push(A("search",o,{}));let i=s.join(`
|
|
43
|
+
`),m=`Found ${n} symbol${n===1?"":"s"} across ${a.size} file${a.size===1?"":"s"}.`,u=i.replace(d,m);return w(u,t,l)}async function M(e,t,r){let{pendingFiles:o,toolName:l,sync:a=false}=r;if(t.length===0||t.every(n=>n.count===0))return _(l,`No incoming edges for \`${e.name}\`.`,"This symbol has no callers \u2014 safe to refactor.");let c=t.reduce((n,i)=>n+i.count,0),s=We(c),d=[];d.push(k(o,new Set([e.filePath]))??""),d.push(`**Impact for \`${e.name}\`** (root: ${e.filePath}:${e.startLine}, total impacted: ${c})
|
|
44
|
+
`);for(let n of t){d.push(`- **d=${n.depth}** (${n.count} nodes) \u2014 ${n.riskLabel}`);for(let i of n.samples.slice(0,5))d.push(` - \`${i.name}\` ${i.file}:${i.line} [${i.relation}]`);n.samples.length>5&&d.push(` - ... and ${n.samples.length-5} more`);}return d.push(A("impact",l,{root:e.name,riskLevel:s})),w(d.join(`
|
|
45
|
+
`),r,a)}function We(e){return e>=100?"CRITICAL":e>=50?"HIGH":e>=10?"MEDIUM":"LOW"}function W(e){return e===1?"WILL BREAK (direct callers)":e===2?"LIKELY AFFECTED (indirect)":"MAY NEED TESTING (transitive)"}async function G(e,t){let{root:r,incoming:o,outgoing:l,neighbors:a}=e,{pendingFiles:c,toolName:s,sync:d=false}=t;if(o.length===0&&l.length===0&&a.length===0)return _(s,`No relations found for \`${r.name}\`.`,"This is a leaf node.");let n=[];n.push(k(c,new Set([r.filePath]))??""),n.push(`**Context for \`${r.name}\`** (${r.astType}, ${r.language}, ${r.filePath}:${r.startLine})
|
|
46
|
+
`),n.push(`**Incoming** (${o.length}):`);for(let i of o.slice(0,10))n.push(`- ${i.source} \u2192 [${i.relation}] \u2192 \`${r.name}\``);o.length>10&&n.push(`- ... and ${o.length-10} more`),n.push(""),n.push(`**Outgoing** (${l.length}):`);for(let i of l.slice(0,10))n.push(`- \`${r.name}\` \u2192 [${i.relation}] \u2192 ${i.target}`);if(l.length>10&&n.push(`- ... and ${l.length-10} more`),n.push(""),a.length>0){n.push(`**Neighbors** (${a.length}):`);for(let i of a.slice(0,20))n.push(`- [d=${i.depth}] \`${i.node.name}\` (${i.node.astType}) ${i.node.filePath}:${i.node.startLine}`);a.length>20&&n.push(`- ... and ${a.length-20} more`),n.push("");}return n.push(A("context",s,{})),w(n.join(`
|
|
47
|
+
`),t,d)}async function H(e,t,r){let{pendingFiles:o,toolName:l,sync:a=false}=r;if(!e.id)return _(l,"Node not found.","Check the node ID or use `search` to find it.");let c=t.filter(n=>n.direction==="in"),s=t.filter(n=>n.direction==="out"),d=[];d.push(k(o,new Set([e.filePath]))??""),d.push(`**Node: \`${e.name}\`**
|
|
48
|
+
`),d.push(`- ID: \`${e.id}\``),d.push(`- Kind: ${e.astType}`),d.push(`- Language: ${e.language}`),d.push(`- Location: ${e.filePath}:${e.startLine}-${e.endLine}`),d.push(`- Exported: ${e.isExported}`),e.modifiers.length>0&&d.push(`- Modifiers: ${e.modifiers.join(", ")}`),d.push(""),d.push(`**Edges** (incoming: ${c.length} / outgoing: ${s.length}):`);for(let n of c.slice(0,5))d.push(`- \u2190 [${n.relation}] ${n.source}`);for(let n of s.slice(0,5))d.push(`- \u2192 [${n.relation}] ${n.target}`);return t.length>10&&d.push(`- ... and ${t.length-10} more`),d.push(A("default",l,{})),w(d.join(`
|
|
49
|
+
`),r,a)}async function q(e,t,r,o,l){let{toolName:a,sync:c=false}=l,s=r==="callers"?"Callers":"Callees",d="of",n=r==="callers"?"Use `node <name>` to read full source of any caller.":"Use `node <name>` to read full source of any callee.",i=t?.name??"?";if(e.length===0)return _(a,`**${s} ${d} \`${i}\`** (0)`,r==="callers"?"This symbol has no callers \u2014 safe to refactor.":"This symbol has no outgoing calls \u2014 leaf node.");let m=[];m.push(`**${s} ${d} \`${i}\`** (${e.length}${o?"+":""})
|
|
50
|
+
`);for(let u of e.slice(0,10)){let g=u.filePath==="(unresolved)",p=g?u.filePath:`${u.filePath}:${u.startLine}`,f=g?" _(wildcard)_":"";m.push(`- [${u.relation}] \`${u.name}\` ${p}${f}`);}return e.length>10&&m.push(`- ... and ${e.length-10} more`),m.push(`
|
|
51
|
+
---
|
|
52
|
+
> ${n}`),w(m.join(`
|
|
53
|
+
`),l,c)}async function ue(e,t){let{entryPoints:r,totalHits:o,query:l}=e,{toolName:a,sync:c=false}=t;if(r.length===0)return _(a,`No matches for \`${l}\`.`,"Try broader search terms, or use `callers` / `callees` to traverse from a known symbol.");let s=[];s.push(`## Code Context
|
|
54
|
+
`),s.push(`**Query:** ${l} `),s.push(`**Total hits:** ${o} `),s.push(`**Entry points:** ${r.length}
|
|
55
|
+
`);for(let d of r){s.push(`**\`${d.file}\`** \u2014 ${d.symbols.length} symbol${d.symbols.length===1?"":"s"}
|
|
56
|
+
`);for(let n of d.symbols){let i=(n.source??"").trim()||"(source not included)",m=n.node.language;if(s.push("```"+m),s.push(`L${n.node.startLine}-L${n.node.endLine} ${n.node.name} (${n.node.astType}${n.node.modifiers.length>0?`, ${n.node.modifiers.join(" ")}`:""})`),s.push(""),s.push(i),s.push("```\n"),n.callers.length>0){s.push(`**Callers of \`${n.node.name}\` (${n.callers.length}):**`);for(let u of n.callers.slice(0,5))s.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);n.callers.length>5&&s.push(`- ... and ${n.callers.length-5} more`),s.push("");}if(n.callees.length>0){s.push(`**Callees of \`${n.node.name}\` (${n.callees.length}):**`);for(let u of n.callees.slice(0,5))s.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);n.callees.length>5&&s.push(`- ... and ${n.callees.length-5} more`),s.push("");}}}return s.push(`---
|
|
57
|
+
`),s.push(A("context",a,{})),w(s.join(`
|
|
58
|
+
`),t,c)}function Ge(e){let t=new Map;for(let r of e){let o=r.node.filePath,l=t.get(o);l?l.push(r):t.set(o,[r]);}return t}function _(e,t,r){return `**${e}**
|
|
59
|
+
|
|
60
|
+
${t}
|
|
61
|
+
|
|
62
|
+
> **Tip:** ${r}`}async function w(e,t,r){let o={softLimit:t.softLimit,hardCeiling:t.hardCeiling,toolName:t.toolName,writeToDisk:r?false:t.writeToDisk};return (r?O(e,o):await D(e,o)).content}var Ye=utils.Log.create({service:"codebase-format-render"});async function Ve(e,t){if(e.length===0)return v([],t);let r=z(e);return v(r,t)}async function Xe(e,t,r){if(t.length===0)return M(R(e),[],r);let o=[{depth:1,count:t.length,riskLabel:W(1),samples:t.slice(0,10).map(l=>({name:l.source.name,file:R(l.source).filePath,line:l.source.start_line??0,relation:l.relation}))}];return M(R(e),o,r)}async function Je(e,t,r,o,l){let a=R(e),c=t.map(n=>$(n,"in")),s=r.map(n=>$(n,"out")),d=o.map(n=>({node:R(n),depth:1}));return G({root:a,incoming:c,outgoing:s,neighbors:d},l)}async function Ze(e,t){return q(e.callers,e.root,"callers",e.truncated,t)}async function et(e,t){return q(e.callees,e.root,"callees",e.truncated,t)}async function tt(e,t){let{renderKnowledgeStatus:r}=await import('@easbot/terminal');return r({packageName:"codebase",rootDir:e.workspaceDir,configPath:e.configPath??"",configExists:typeof e.configExists=="boolean"?e.configExists:false,dbPath:e.dbPath,dbExists:typeof e.dbExists=="boolean"?e.dbExists:true,dbSize:e.dbSize,indexState:e.indexState,schemaVersion:(()=>{let o=e.meta?.schema_version;return o&&Number.isFinite(Number.parseInt(o,10))?Number.parseInt(o,10):void 0})(),extractionVersion:e.extractionVersion,lastSyncAt:e.lastSync,vectorEnabled:typeof e.vectorEnabled=="boolean"?e.vectorEnabled:false,embeddingDims:typeof e.embeddingDims=="number"?e.embeddingDims:void 0,llm:e.llm??{initialized:false,capabilities:{}},healthy:e.healthy,dbStats:e.dbStats,extras:(()=>{let o={};if(e.isStale===true&&(o.stale="yes \u2014 reindex recommended"),typeof e.ftsAvailable=="boolean"&&(o.fts_available=e.ftsAvailable?"yes":"no"),e.meta&&typeof e.meta=="object")for(let[l,a]of Object.entries(e.meta))a!=null&&(o[`meta/${l}`]=String(a));return Object.keys(o).length>0?o:void 0})()})}async function nt(e,t,r){if(!e)return H(K(),[],r);let o=R(e),l=t.map(a=>{let c=a.target===e.id?"in":"out";return $(a,c)});return H(o,l,r)}async function rt(e,t){let r={query:e.query,totalHits:e.totalHits,entryPoints:e.entryPoints.map(o=>({file:o.file,symbols:o.symbols.map(l=>({node:R(l.node),source:l.node.text??"",callers:l.callers.map(a=>({name:a.name,filePath:a.filePath,startLine:a.startLine,relation:a.relation})),callees:l.callees.map(a=>({name:a.name,filePath:a.filePath,startLine:a.startLine,relation:a.relation}))}))}))};return ue(r,t)}Ye.debug("format/render.ts loaded");exports.A=Je;exports.B=Ze;exports.C=et;exports.D=tt;exports.E=nt;exports.F=rt;exports.a=te;exports.b=Se;exports.c=Ie;exports.d=Te;exports.e=$e;exports.f=_e;exports.g=we;exports.h=Fe;exports.i=Ae;exports.j=ve;exports.k=R;exports.l=$;exports.m=z;exports.n=K;exports.o=j;exports.p=Ke;exports.q=D;exports.r=O;exports.s=v;exports.t=M;exports.u=W;exports.v=G;exports.w=H;exports.x=q;exports.y=Ve;exports.z=Xe;
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import {a}from'./chunk-2YMB6W5S.mjs';import i from'zod';import {NamedError,Log,Filesystem,ServiceErrorBus,errorMeta,NameErrors}from'@easbot/utils';export{ServiceError as a}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var f;(E=>(E.ParserError=NamedError.create("CodebaseParserError",i.object({message:i.string(),filePath:i.string()})),E.DatabaseError=NamedError.create("CodebaseDatabaseError",i.object({message:i.string(),operation:i.string()})),E.SchemaError=NamedError.create("CodebaseSchemaError",i.object({message:i.string(),missing:i.array(i.string()).optional()})),E.FileSystemError=NamedError.create("CodebaseFileSystemError",i.object({message:i.string(),filePath:i.string()})),E.IndexError=NamedError.create("CodebaseIndexError",i.object({message:i.string(),filePath:i.string().optional()})),E.ConfigError=NamedError.create("CodebaseConfigError",i.object({message:i.string(),field:i.string().optional()})),E.QueryError=NamedError.create("CodebaseQueryError",i.object({message:i.string(),params:i.record(i.string(),i.unknown()).optional()})),E.UnsupportedLanguageError=NamedError.create("CodebaseUnsupportedLanguageError",i.object({extension:i.string(),filePath:i.string()})),E.NotFoundError=NamedError.create("CodebaseNotFoundError",i.object({message:i.string(),name:i.string(),candidates:i.array(i.object({node:i.unknown(),score:i.number()})).optional()})),E.AmbiguousError=NamedError.create("CodebaseAmbiguousError",i.object({message:i.string(),name:i.string(),candidates:i.array(i.object({node:i.unknown(),score:i.number()}))}))))(f||(f={}));var k=new Set(["NOT_FOUND","AMBIGUOUS","INTERNAL","NOT_INDEXED"]),B={NOT_FOUND:"codebase node not found; run codebase_query first to discover the symbol (by name / kind / file)",AMBIGUOUS:"multiple nodes match the name; pass either nodeId OR name+file to disambiguate (file is the strongest disambiguation signal)",NOT_INDEXED:"codebase index not ready; run `easbot codebase sync` first, then retry"};async function G(){await ServiceErrorBus.register("codebase",k,B);}var w=Log.create({service:"codebase-schema-migrations"}),O=1,q=[{id:1,description:"v1 baseline: nodes / edges / file_hashes / nodes_fts / meta / embedding_cache / node_embeddings + unresolved_refs / name_segment_vocab / project_metadata / parse_errors + \u6027\u80FD index (nodes.file_path / edges.source/target)",up:[`CREATE TABLE IF NOT EXISTS nodes (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
name TEXT NOT NULL,
|
|
4
|
+
ast_type TEXT NOT NULL,
|
|
5
|
+
language TEXT NOT NULL,
|
|
6
|
+
file_path TEXT NOT NULL,
|
|
7
|
+
start_line INTEGER,
|
|
8
|
+
start_col INTEGER,
|
|
9
|
+
end_line INTEGER,
|
|
10
|
+
end_col INTEGER,
|
|
11
|
+
text TEXT,
|
|
12
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
13
|
+
)`,`CREATE TABLE IF NOT EXISTS edges (
|
|
14
|
+
id TEXT PRIMARY KEY,
|
|
15
|
+
source TEXT NOT NULL,
|
|
16
|
+
target TEXT NOT NULL,
|
|
17
|
+
relation TEXT NOT NULL,
|
|
18
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
19
|
+
FOREIGN KEY (source) REFERENCES nodes(id) ON DELETE CASCADE,
|
|
20
|
+
FOREIGN KEY (target) REFERENCES nodes(id) ON DELETE CASCADE
|
|
21
|
+
)`,`CREATE TABLE IF NOT EXISTS file_hashes (
|
|
22
|
+
file_path TEXT PRIMARY KEY,
|
|
23
|
+
content_hash TEXT NOT NULL,
|
|
24
|
+
last_modified DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
25
|
+
)`,`CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(
|
|
26
|
+
id, name, ast_type, language, file_path, text,
|
|
27
|
+
tokenize='unicode61'
|
|
28
|
+
)`,`CREATE TABLE IF NOT EXISTS meta (
|
|
29
|
+
key TEXT PRIMARY KEY,
|
|
30
|
+
value TEXT
|
|
31
|
+
)`,`CREATE TABLE IF NOT EXISTS embedding_cache (
|
|
32
|
+
content_hash TEXT PRIMARY KEY,
|
|
33
|
+
embedding BLOB NOT NULL
|
|
34
|
+
)`,`CREATE TABLE IF NOT EXISTS node_embeddings (
|
|
35
|
+
node_id TEXT PRIMARY KEY,
|
|
36
|
+
embedding_text TEXT NOT NULL,
|
|
37
|
+
embedding BLOB NOT NULL,
|
|
38
|
+
FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
|
|
39
|
+
)`,`CREATE TABLE IF NOT EXISTS unresolved_refs (
|
|
40
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
41
|
+
from_node_id TEXT,
|
|
42
|
+
reference_name TEXT NOT NULL,
|
|
43
|
+
reference_kind TEXT NOT NULL,
|
|
44
|
+
line INTEGER,
|
|
45
|
+
col INTEGER,
|
|
46
|
+
file_path TEXT NOT NULL,
|
|
47
|
+
language TEXT NOT NULL,
|
|
48
|
+
candidates TEXT,
|
|
49
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
50
|
+
FOREIGN KEY (from_node_id) REFERENCES nodes(id) ON DELETE SET NULL
|
|
51
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_unresolved_refs_file_path ON unresolved_refs(file_path)","CREATE INDEX IF NOT EXISTS idx_unresolved_refs_kind ON unresolved_refs(reference_kind)",`CREATE TABLE IF NOT EXISTS name_segment_vocab (
|
|
52
|
+
segment TEXT NOT NULL,
|
|
53
|
+
name TEXT NOT NULL,
|
|
54
|
+
PRIMARY KEY (segment, name)
|
|
55
|
+
) WITHOUT ROWID`,"CREATE INDEX IF NOT EXISTS idx_name_segment ON name_segment_vocab(segment)",`CREATE TABLE IF NOT EXISTS project_metadata (
|
|
56
|
+
key TEXT PRIMARY KEY,
|
|
57
|
+
value TEXT,
|
|
58
|
+
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
59
|
+
)`,`CREATE TABLE IF NOT EXISTS parse_errors (
|
|
60
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
61
|
+
file_path TEXT NOT NULL,
|
|
62
|
+
language TEXT NOT NULL,
|
|
63
|
+
stage TEXT NOT NULL,
|
|
64
|
+
message TEXT NOT NULL,
|
|
65
|
+
line INTEGER,
|
|
66
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
67
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_parse_errors_file_path ON parse_errors(file_path)","CREATE INDEX IF NOT EXISTS idx_nodes_file_path ON nodes(file_path)","CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)"]}];function D(c,e=O,t={}){c.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
68
|
+
id INTEGER PRIMARY KEY,
|
|
69
|
+
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
70
|
+
)`);let s=c.prepare("SELECT id FROM schema_migrations").all(),n=new Set(s.map(a=>a.id)),r={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of q){if(a.id>e)break;if(n.has(a.id)){r.pending.push(a.id);continue}if(t.dryRun){r.applied.push(a.id);continue}try{c.execBatch([...a.up]),c.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),n.add(a.id),r.applied.push(a.id),w.debug("migration applied",{id:a.id,description:a.description});}catch(o){let d=errorMeta(o).message,u=a.up[0]??"";r.errors.push({migrationId:a.id,sql:u,error:d}),w.warn("migration step failed (may be idempotent)",{id:a.id,error:errorMeta(o),sqlCount:a.up.length});}}return r}function P(c){try{let e=c.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var g=Filesystem.toUnixPath,l=Log.create({service:"codebase-database"}),I=3,H=class{constructor(e){a(this,"db");a(this,"dbPath");a(this,"closed",false);a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:Filesystem.normalize(e),this.db=createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs:3e4}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){l.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:errorMeta(t)});}try{this.ensureSchema();let t=P(this.db);t>0&&this.setMeta("schema_version",String(t)),this.ftsAvailable=this.checkFtsAvailability(),this.detectAndMarkStaleOnInit();}catch(t){try{this.db.close();}catch{}throw this.closed=true,t}}ensureSchema(){try{D(this.db,O);let e=[["version","1.0.0"],["createdAt",new Date().toISOString()],["index_state","uninitialized"],["indexed_with_version","unknown"]],t=this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,n]of e)t.run(s,n);}catch(e){l.error("ensureSchema failed",{error:errorMeta(e)});let t=errorMeta(e).message,s=e instanceof Error?e.cause:void 0,n=s!==void 0?String(s):"",r=n&&n!==t?` (cause: ${n})`:"";throw new f.SchemaError({message:`Failed to create database schema: ${t}${r}`,missing:e instanceof Error?[t,n].filter(Boolean):[t]},{cause:e})}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:g(e.file_path)};this.db.prepare(`
|
|
71
|
+
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
72
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
73
|
+
`).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(r=>({...r,file_path:g(r.file_path)})),s=this.db.prepare(`
|
|
74
|
+
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
75
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
76
|
+
`);this.db.transaction(r=>{for(let a of r)s.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.start_line,a.start_col,a.end_line,a.end_col,a.text,a.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(r);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let r of e)try{let a=s.get(r.id);a&&t.run(a.rowid),n.run(r.id,r.name,r.ast_type,r.language,r.file_path,r.text);}catch(a){l.warn("FTS update failed for node",{nodeId:r.id,error:errorMeta(a)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){l.warn("FTS update failed for node",{nodeId:e.id,error:errorMeta(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(a=>{for(let o of a)try{let d=s.get(o.id);d&&t.run(d.rowid),n.run(o.id,o.name,o.ast_type,o.language,o.file_path,o.text);}catch(d){l.warn("FTS update failed for node",{nodeId:o.id,error:errorMeta(d)});}})(e);}insertEdge(e){this.db.prepare(`
|
|
77
|
+
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
78
|
+
VALUES (?, ?, ?, ?, ?)
|
|
79
|
+
`).run(e.id,e.source,e.target,e.relation,e.created_at);}insertEdges(e){if(e.length===0)return;let t=this.db.prepare(`
|
|
80
|
+
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
81
|
+
VALUES (?, ?, ?, ?, ?)
|
|
82
|
+
`);this.db.transaction(n=>{for(let r of n)t.run(r.id,r.source,r.target,r.relation,r.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${g(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),s.push(e.astType)),e.name&&(t.push("name = ?"),s.push(e.name)),e.language&&(t.push("language = ?"),s.push(e.language));let n="SELECT * FROM nodes";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY file_path, start_line",e.limit&&(n+=" LIMIT ?",s.push(e.limit)),e.offset&&(n+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(n).all(...s)}catch(r){throw new f.DatabaseError({message:"Failed to query nodes",operation:"queryNodes"},{cause:r})}}findNodesByName(e){if(!e.name)return [];let t=e.limit??50,s=e.kind?`%${e.kind.toLowerCase()}%`:null,n=new Set,r=[],a=(d,u)=>{n.has(d.id)||(n.add(d.id),r.push({node:d,matchKind:u}));},o=(d,u)=>{e.file&&(e.file.includes("/")?(d.push("file_path = ?"),u.push(e.file)):(d.push("file_path LIKE '%/' || ?"),u.push(e.file))),s&&(d.push("LOWER(ast_type) LIKE ?"),u.push(s));};try{let d=["name = ?"],u=[e.name];o(d,u),u.push(t);let E=this.db.prepare(`SELECT * FROM nodes WHERE ${d.join(" AND ")} LIMIT ?`).all(...u);for(let h of E)a(h,"exact");if(E.length>0&&e.file)return r.slice(0,t);if(r.length<t){let h=this.db.prepare("SELECT * FROM nodes WHERE name LIKE ? LIMIT ?").all(`%${e.name}%`,t);for(let p of h)a(p,"qualified");}if(r.length>0&&e.file)return r.slice(0,t);if(r.length===0&&e.name){let h=["name LIKE ?"],p=[`%${e.name}%`];e.file&&(e.file.includes("/")?(h.push("file_path = ?"),p.push(e.file)):(h.push("file_path LIKE '%/' || ?"),p.push(e.file))),s&&(h.push("LOWER(ast_type) LIKE ?"),p.push(s)),h.push("?"),p.push(t);let b=this.db.prepare(`SELECT * FROM nodes WHERE ${h.join(" AND ")}`).all(...p);for(let N of b)a(N,"substring");}return r.slice(0,t)}catch(d){throw new f.DatabaseError({message:"Failed to find nodes by name",operation:"findNodesByName"},{cause:d})}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let r=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${r}) OR target IN (${r}))`),s.push(...e.sourceOrTarget,...e.sourceOrTarget);}else e.source&&(t.push("source = ?"),s.push(e.source)),e.target&&(t.push("target = ?"),s.push(e.target));e.relation&&(t.push("relation = ?"),s.push(e.relation));let n="SELECT * FROM edges";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY created_at DESC",e.limit&&(n+=" LIMIT ?",s.push(e.limit)),e.offset&&(n+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(n).all(...s)}catch(r){throw new f.DatabaseError({message:"Failed to query edges",operation:"queryEdges"},{cause:r})}}queryAll(e,t){try{let s=this.db.prepare(e);return t?s.all(...t):s.all()}catch(s){throw new f.DatabaseError({message:"Failed to execute query",operation:"queryAll"},{cause:s})}}searchNodesFts(e,t=20){if(l.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return l.debug("searchNodesFts skip - FTS not available"),[];try{let s=e.split(/\s+/).map(o=>`${o}*`).join(" ");l.debug("searchNodesFts query",{ftsQuery:s});let a=this.db.prepare(`
|
|
83
|
+
SELECT
|
|
84
|
+
nodes_fts.id,
|
|
85
|
+
nodes_fts.name,
|
|
86
|
+
nodes_fts.ast_type,
|
|
87
|
+
nodes_fts.language,
|
|
88
|
+
nodes_fts.file_path,
|
|
89
|
+
nodes_fts.text,
|
|
90
|
+
nodes.start_line,
|
|
91
|
+
nodes.start_col,
|
|
92
|
+
nodes.end_line,
|
|
93
|
+
nodes.end_col,
|
|
94
|
+
bm25(nodes_fts) as score
|
|
95
|
+
FROM nodes_fts
|
|
96
|
+
JOIN nodes ON nodes.id = nodes_fts.id
|
|
97
|
+
WHERE nodes_fts.text MATCH ?
|
|
98
|
+
ORDER BY score DESC
|
|
99
|
+
LIMIT ?
|
|
100
|
+
`).all(s,t);return l.debug("searchNodesFts done",{resultCount:a.length}),a}catch(s){return l.warn("searchNodesFts failed",{error:errorMeta(s)}),[]}}deleteNodesByFile(e){let t=g(e);if(this.ftsAvailable)try{let n=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let r of n)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(r.rowid);}catch(n){l.warn("FTS delete failed for file",{filePath:t,error:errorMeta(n)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=g(e);return this.db.prepare(`
|
|
101
|
+
DELETE FROM edges
|
|
102
|
+
WHERE source IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
103
|
+
OR target IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
104
|
+
`).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(g(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
|
|
105
|
+
INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
|
|
106
|
+
VALUES (?, ?, ?)
|
|
107
|
+
`).run(g(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(g(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}checkIntegrity(){let e=S=>this.db.prepare(S).get().c,t=S=>e(S),s={nodes:t("SELECT COUNT(*) as c FROM nodes"),edges:t("SELECT COUNT(*) as c FROM edges"),file_hashes:t("SELECT COUNT(*) as c FROM file_hashes"),fts:t("SELECT COUNT(*) as c FROM nodes_fts"),node_embeddings:t("SELECT COUNT(*) as c FROM node_embeddings"),embedding_cache:t("SELECT COUNT(*) as c FROM embedding_cache"),parse_errors:t("SELECT COUNT(*) as c FROM parse_errors"),unresolved_refs:t("SELECT COUNT(*) as c FROM unresolved_refs"),name_segment_vocab:t("SELECT COUNT(*) as c FROM name_segment_vocab"),project_metadata:t("SELECT COUNT(*) as c FROM project_metadata"),schema_migrations:t("SELECT COUNT(*) as c FROM schema_migrations"),meta:t("SELECT COUNT(*) as c FROM meta")},n=[],r=t(`
|
|
108
|
+
SELECT COUNT(*) as c FROM node_embeddings e
|
|
109
|
+
LEFT JOIN nodes n ON n.id = e.node_id WHERE n.id IS NULL
|
|
110
|
+
`);r>0&&n.push({severity:"error",message:`orphan node_embeddings: ${r}`});let a=t(`
|
|
111
|
+
SELECT COUNT(*) as c FROM edges e
|
|
112
|
+
WHERE e.relation != 'IMPORTS'
|
|
113
|
+
AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
|
|
114
|
+
`);a>0&&n.push({severity:"error",message:`orphan edges (source): ${a}`});let o=t(`
|
|
115
|
+
SELECT COUNT(*) as c FROM edges e
|
|
116
|
+
WHERE e.relation NOT IN ('CALLS', 'IMPORTS')
|
|
117
|
+
AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
|
|
118
|
+
`);o>0&&n.push({severity:"error",message:`orphan edges (target): ${o}`});let d=t("SELECT COUNT(*) as c FROM edges WHERE source = target");d>0&&n.push({severity:"error",message:`self-loop edges: ${d} \u2014 re-run \`easbot codebase sync\` to filter (fixed in Wave 4 R3-2)`});t("SELECT COUNT(DISTINCT file_path) as c FROM nodes");let E=t(`
|
|
119
|
+
SELECT COUNT(*) as c FROM file_hashes fh
|
|
120
|
+
WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.file_path = fh.file_path)
|
|
121
|
+
`);E>0&&n.push({severity:"warn",message:`orphan file_hashes (no nodes): ${E} \u2014 run \`easbot codebase sync\` to cleanup`});let h=t(`
|
|
122
|
+
SELECT COUNT(DISTINCT n.file_path) as c FROM nodes n
|
|
123
|
+
WHERE NOT EXISTS (SELECT 1 FROM file_hashes fh WHERE fh.file_path = n.file_path)
|
|
124
|
+
`);h>0&&n.push({severity:"warn",message:`node files without hash: ${h}`});let p=t("SELECT COUNT(*) as c FROM nodes WHERE name IS NULL OR name = ''");p>0&&n.push({severity:"error",message:`nodes with null/empty name: ${p}`});let b=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");b>0&&n.push({severity:"error",message:`nodes with null/empty ast_type: ${b}`});let N=t("SELECT COUNT(*) as c FROM nodes WHERE language IS NULL OR language = ''");N>0&&n.push({severity:"error",message:`nodes with null/empty language: ${N}`});let L=t("SELECT COUNT(*) as c FROM nodes WHERE file_path IS NULL OR file_path = ''");L>0&&n.push({severity:"error",message:`nodes with null/empty file_path: ${L}`});let F=this.db.prepare("SELECT id, COUNT(*) as c FROM nodes GROUP BY id HAVING c > 1").all().length;F>0&&n.push({severity:"error",message:`duplicate node ids: ${F}`});let C=t("SELECT COUNT(*) as c FROM nodes WHERE file_path LIKE '%\\\\%'");C>0&&n.push({severity:"warn",message:`nodes with backslash in file_path: ${C}`});let y=t(`
|
|
125
|
+
SELECT COUNT(*) as c FROM nodes
|
|
126
|
+
WHERE start_line IS NOT NULL AND end_line IS NOT NULL AND start_line > end_line
|
|
127
|
+
`);y>0&&n.push({severity:"error",message:`invalid line ranges: ${y}`});let M=this.db.prepare("SELECT id, COUNT(*) as c FROM edges GROUP BY id HAVING c > 1").all().length;M>0&&n.push({severity:"error",message:`duplicate edge ids: ${M}`});let A=t("SELECT COUNT(*) as c FROM nodes_fts_content");return A!==s.nodes&&n.push({severity:"error",message:`FTS content desync: ${A} vs ${s.nodes} (run \`easbot codebase recreate\` to rebuild)`}),s.parse_errors>100&&n.push({severity:"warn",message:`parse_errors > 100 (${s.parse_errors}) \u2014\u2014 many files failed to parse`}),{issues:n,stats:s}}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),s=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),n=this.db.prepare("SELECT key, value FROM meta").all(),r={};for(let a of n)r[a.key]=a.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:s?.c??0,dbPath:this.dbPath,meta:r,indexState:this.getIndexState(),extractionVersion:parseInt(this.getMeta("indexed_with_extraction_version")??"0",10),isStale:this.isIndexStale()}}setLastSync(){this.db.prepare(`
|
|
128
|
+
INSERT OR REPLACE INTO meta (key, value)
|
|
129
|
+
VALUES ('lastSync', ?)
|
|
130
|
+
`).run(new Date().toISOString());}getIndexState(){return this.getMeta("index_state")??"uninitialized"}setIndexState(e){this.setMeta("index_state",e),this.setMeta("last_index_state_change",new Date().toISOString());}markIndexed(e){this.setMeta("indexed_with_version",e),this.setMeta("indexed_with_extraction_version",String(I)),this.setMeta("index_state","complete"),this.setMeta("last_index_state_change",new Date().toISOString());}isIndexStale(){let e=this.getMeta("indexed_with_extraction_version");if(!e)return false;let t=parseInt(e,10);return Number.isNaN(t)||t<I}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");l.warn("codebase db is stale",{recorded:e??"(none)",current:String(I),hint:"run `easbot codebase recreate` or `easbot codebase index --force` to rebuild"});let t=this.getIndexState();(t==="complete"||t==="partial")&&this.setIndexState("stale");}}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(e={}){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),e.keepEmbeddings||(this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache")),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let s=this.db.prepare(`
|
|
131
|
+
SELECT embedding FROM embedding_cache WHERE content_hash = ?
|
|
132
|
+
`).get(e);return s?new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.length/4):null}getVectorDims(){let e=this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims");return e?parseInt(e.value,10):void 0}ensureVectorDims(e){this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims")||this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)").run("vectorDims",String(e));}cacheEmbedding(e,t){if(this.db.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(e))return;this.ensureVectorDims(t.length),this.db.prepare(`
|
|
133
|
+
INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
|
|
134
|
+
VALUES (?, ?)
|
|
135
|
+
`).run(e,t);}deleteEmbeddingsByFile(e){let t=g(e);return this.db.prepare(`
|
|
136
|
+
DELETE FROM node_embeddings WHERE node_id IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
137
|
+
`).run(t).changes}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;this.ensureVectorDims(e[0].embedding.length);let t=this.db.prepare(`
|
|
138
|
+
INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
|
|
139
|
+
VALUES (?, ?, ?)
|
|
140
|
+
`);this.db.transaction(n=>{for(let r of n)try{t.run(r.nodeId,r.embeddingText,r.embedding);}catch(a){l.warn("Failed to store embedding for node",{nodeId:r.nodeId,error:errorMeta(a)});}})(e);}insertParseError(e){return this.db.prepare(`
|
|
141
|
+
INSERT INTO parse_errors (file_path, language, stage, message, line)
|
|
142
|
+
VALUES (?, ?, ?, ?, ?)
|
|
143
|
+
`).run(g(e.filePath),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
|
|
144
|
+
INSERT INTO unresolved_refs
|
|
145
|
+
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
146
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
147
|
+
`).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,g(e.filePath),e.language,e.candidates?JSON.stringify(e.candidates):null).changes}insertUnresolvedRefsBatch(e){if(e.length===0)return 0;let s=`
|
|
148
|
+
INSERT INTO unresolved_refs
|
|
149
|
+
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
150
|
+
VALUES ${e.map(()=>"(?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}
|
|
151
|
+
`,n=[];for(let o of e)n.push(o.fromNodeId??null,o.referenceName,o.referenceKind,o.line??null,o.col??null,g(o.filePath),o.language,o.candidates?JSON.stringify(o.candidates):null);return this.db.prepare(s).run(...n).changes}insertNameSegment(e,t){return this.db.prepare(`
|
|
152
|
+
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)
|
|
153
|
+
`).run(e,t).changes}insertNameSegmentsBatch(e){if(e.length===0)return 0;let s=`
|
|
154
|
+
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ${e.map(()=>"(?, ?)").join(", ")}
|
|
155
|
+
`,n=[];for(let o of e)n.push(o.segment,o.name);return this.db.prepare(s).run(...n).changes}setProjectMetadata(e,t){let s=e==="worktree"||e==="project"?g(t):t;return this.db.prepare(`
|
|
156
|
+
INSERT OR REPLACE INTO project_metadata (key, value, updated_at)
|
|
157
|
+
VALUES (?, ?, CURRENT_TIMESTAMP)
|
|
158
|
+
`).run(e,s).changes}getNodeIdsByFile(e){let t=e.replace(/\\/g,"/");return this.db.prepare("SELECT id FROM nodes WHERE file_path = ?").all(t).map(n=>n.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let n=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(a=>{for(let o of a)n.run(o);})(s),s.length}initialize(){if(this.closed)throw new f.DatabaseError({message:"Cannot initialize closed database",operation:"initialize"})}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){l.warn("Database close error",{error:errorMeta(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}countSqliteObjects(){if(!this.db)throw new NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});return this.db.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0}deleteMeta(e){if(!this.db)throw new NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});this.db.prepare("DELETE FROM meta WHERE key = ?").run(e);}};function ie(c){return c.isClosed()}function oe(c){return c.getDbPath()}function de(c,e){return c.transaction(e)}export{f as b,k as c,B as d,G as e,O as f,q as g,D as h,P as i,I as j,H as k,ie as l,oe as m,de as n};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkM2YU5LAI_cjs=require('./chunk-M2YU5LAI.cjs'),fs=require('fs'),path=require('path'),module$1=require('module'),utils=require('@easbot/utils');var o=utils.Log.create({service:"codebase-file-watcher"});function A(){return process.env.EASBOT_CACHE_PATH||path.join(process.cwd(),".easbot","cache")}var C=["node_modules/**",".git/**","dist/**","build/**","__pycache__/**","*.min.js","*.min.ts",".easbot/**",".codebase/**"],s=class s{constructor(){chunkM2YU5LAI_cjs.a(this,"wrapper",null);chunkM2YU5LAI_cjs.a(this,"error",null);}static get(){return s.instance||(s.instance=new s),s.instance}static clearCache(){s.instance&&(s.instance.wrapper=null,s.instance.error=null);}};chunkM2YU5LAI_cjs.a(s,"instance",null);var b=s;function R(){let r=process.platform==="linux"?`-${globalThis.EASBOT_LIBC||"glibc"}`:"";return `@parcel/watcher-${process.platform}-${process.arch}${r}`}async function T(){let r=b.get();if(r.wrapper)return r.wrapper;if(r.error)throw new utils.NameErrors.OperationFailedError({message:r.error,operation:"parcel-watcher-binding-cache"});let e=R(),t=A(),i;try{await $(e,t)?i=path.join(t,"node_modules",e):(o.info("Parcel watcher binding not found, attempting to install",{binding:e,cachePath:t}),i=await q(e,t));}catch(u){let p=utils.errorMeta(u).message,f=`binding "${e}" not found and auto-install failed. Run manually: pnpm install ${e}. Error: ${p}`;throw r.error=f,o.error("failed to install parcel watcher binding",{error:utils.errorMeta(u),binding:e}),new utils.NameErrors.OperationFailedError({message:f,operation:"parcel-watcher-binding-install"})}o.info("Loading Parcel watcher binding",{binding:e,modulePath:i});let{createWrapper:g}=await import('@parcel/watcher/wrapper.js'),l=module$1.createRequire(path.join(i,"package.json"))(e),c=g(l);return r.wrapper=c,c}async function $(r,e){try{return !!await utils.PKG.resolve(r,void 0,{extraPaths:[e]})}catch{return false}}async function q(r,e){return o.info("Installing Parcel watcher binding",{binding:r,cachePath:e}),await utils.Shell.install(r,"latest",e),path.join(e,"node_modules",r)}function P(){return process.platform==="darwin"?"fs-events":process.platform==="linux"?"inotify":process.platform==="win32"?"windows":"brute-force"}var v=class{constructor(e){chunkM2YU5LAI_cjs.a(this,"workspaceDir");chunkM2YU5LAI_cjs.a(this,"backendOpt");chunkM2YU5LAI_cjs.a(this,"ignorePatterns");chunkM2YU5LAI_cjs.a(this,"onLoadFailure");chunkM2YU5LAI_cjs.a(this,"ignoreInstance");chunkM2YU5LAI_cjs.a(this,"listeners",new Set);chunkM2YU5LAI_cjs.a(this,"unsubscribe",null);chunkM2YU5LAI_cjs.a(this,"disposed",false);chunkM2YU5LAI_cjs.a(this,"running",false);this.workspaceDir=path.isAbsolute(e.workspaceDir)?e.workspaceDir:path.normalize(e.workspaceDir),this.backendOpt=e.backend??"auto",this.ignorePatterns=e.ignorePatterns??[...C],this.onLoadFailure=e.onLoadFailure??"throw",this.ignoreInstance=utils.Ignore.create().add(this.ignorePatterns);}getIgnoreInstance(){return this.ignoreInstance}getIgnorePatterns(){return this.ignorePatterns}getActiveBackend(){return this.backendOpt==="auto"?P():this.backendOpt}on(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async start(){if(this.running)return;this.running=true;let e=this.backendOpt==="auto"?P():this.backendOpt;o.info("FileWatcher start",{workspaceDir:this.workspaceDir,backend:e});let t;try{t=await T();}catch(i){if(this.running=false,this.onLoadFailure==="warn")return;throw i}await this.subscribeWithParcel(t,e);}async stop(){if(this.unsubscribe){try{await this.unsubscribe();}catch(e){o.warn("parcel unsubscribe error",{error:utils.errorMeta(e)});}this.unsubscribe=null;}this.running=false;}async dispose(){await this.stop(),this.disposed=true,this.listeners.clear();}isRunning(){return this.running}isDisposed(){return this.disposed}static clearParcelWrapperCache(){b.clearCache();}async subscribeWithParcel(e,t){if(this.disposed)throw new utils.NameErrors.OperationFailedError({message:"FileWatcher disposed before subscribe",operation:"file-watcher-disposed"});let i=(a,l)=>{if(this.disposed)return;let c=this.workspaceDir.replace(/\\/g,"/").replace(/\/$/,""),u=l.replace(/\\/g,"/"),p=l;if(u.startsWith(c+"/")&&(p=u.slice(c.length+1)),this.ignoreInstance.ignores(p,a==="create"&&p.endsWith("/")))return;let f=a==="create"?"add":a==="delete"?"unlink":"change";for(let y of this.listeners)try{y(f,p);}catch(W){o.warn("listener threw",{error:utils.errorMeta(W)});}},g=await e.subscribe(this.workspaceDir,(a,l)=>{if(a){o.error("parcel subscribe callback error",{error:utils.errorMeta(a)});return}for(let c of l)i(c.type,c.path);},{ignore:[...this.ignorePatterns],backend:t});if(this.disposed){await g.unsubscribe().catch(()=>{});return}this.unsubscribe=async()=>{await g.unsubscribe().catch(a=>{o.warn("parcel unsubscribe error",{error:utils.errorMeta(a)});});};}};function m(r){return path.join(r,".watcher.pid")}function H(r){let e=m(r);if(!fs.existsSync(e))return null;try{let t=fs.readFileSync(e,"utf-8").trim(),i=parseInt(t,10);return Number.isFinite(i)?i:null}catch{return null}}async function z(r,e){let t=m(r);await fs.promises.writeFile(t,String(e),"utf-8");}async function K(r){let e=m(r);try{await fs.promises.unlink(e);}catch{}}exports.a=v;exports.b=m;exports.c=H;exports.d=z;exports.e=K;
|