@easbot/codebase 0.3.23 → 0.3.25
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-UAWXUGY5.cjs → chunk-3IB5XZ2D.cjs} +22 -22
- package/dist/chunks/chunk-4HJ7RFP7.cjs +1 -0
- package/dist/chunks/{chunk-GWR5LCUV.mjs → chunk-7CL37IYG.mjs} +28 -24
- package/dist/chunks/chunk-ICEJ23S3.mjs +203 -0
- package/dist/chunks/chunk-JCJFUUU2.cjs +203 -0
- package/dist/chunks/chunk-QMTGRU63.mjs +47 -0
- package/dist/chunks/chunk-TGCR6O3S.cjs +62 -0
- package/dist/chunks/{chunk-3NTIN3AN.cjs → chunk-UHNJOT5S.cjs} +28 -24
- package/dist/chunks/chunk-WRM2FP4O.mjs +62 -0
- package/dist/chunks/chunk-ZPEE2LSX.mjs +1 -0
- package/dist/chunks/cli-handler-FQ7LQDAN.cjs +1 -0
- package/dist/chunks/cli-handler-Z6VGOAMV.mjs +1 -0
- package/dist/chunks/code-base-BFLIOZXA.cjs +1 -0
- package/dist/chunks/{code-base-HAX5SGRL.mjs → code-base-DMVLROV6.mjs} +1 -1
- package/dist/chunks/database-manager-GT3LOQUV.cjs +1 -0
- package/dist/chunks/database-manager-N5WLNG3F.mjs +1 -0
- package/dist/chunks/file-watcher-QS442D52.cjs +1 -0
- package/dist/chunks/file-watcher-X56TEWNY.mjs +1 -0
- package/dist/chunks/stdio-server-4X7YFQA2.mjs +30 -0
- package/dist/chunks/stdio-server-5UQVBBZP.cjs +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 +39 -4
- package/dist/index.d.ts +39 -4
- package/dist/index.mjs +1 -1
- package/package.json +8 -8
- package/dist/chunks/chunk-A4EAKE3M.mjs +0 -49
- package/dist/chunks/chunk-DHH2XXGJ.mjs +0 -203
- package/dist/chunks/chunk-HRFLFP6O.cjs +0 -1
- package/dist/chunks/chunk-KU6UZET2.cjs +0 -49
- package/dist/chunks/chunk-QQXDOGRV.mjs +0 -1
- package/dist/chunks/chunk-XXH7ZLAJ.mjs +0 -47
- package/dist/chunks/chunk-YY3Z7NGV.cjs +0 -203
- package/dist/chunks/cli-handler-7XFZK7GK.cjs +0 -1
- package/dist/chunks/cli-handler-H6VHMEHB.mjs +0 -1
- package/dist/chunks/code-base-E5TX7O7M.cjs +0 -1
- package/dist/chunks/database-manager-WTV3TBJS.cjs +0 -1
- package/dist/chunks/database-manager-YGQQHLYR.mjs +0 -1
- package/dist/chunks/file-watcher-HVST5PAC.cjs +0 -1
- package/dist/chunks/file-watcher-LCQ55MPE.mjs +0 -1
- package/dist/chunks/stdio-server-2QHQ7ESX.cjs +0 -47
- package/dist/chunks/stdio-server-5YSJE5E5.mjs +0 -47
|
@@ -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 O(){return process.env.EASBOT_CACHE_PATH||path.join(process.cwd(),".easbot","cache")}var S=["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 f=s;function A(){let r=process.platform==="linux"?`-${globalThis.EASBOT_LIBC||"glibc"}`:"";return `@parcel/watcher-${process.platform}-${process.arch}${r}`}async function C(){let r=f.get();if(r.wrapper)return r.wrapper;if(r.error)throw new Error(r.error);let e=A(),t=O(),i;try{await R(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 T(e,t));}catch(l){let p=l instanceof Error?l.message:String(l),g=`binding "${e}" not found and auto-install failed. Run manually: pnpm install ${e}. Error: ${p}`;throw r.error=g,o.error("failed to install parcel watcher binding",{error:l,binding:e}),new Error(g)}o.info("Loading Parcel watcher binding",{binding:e,modulePath:i});let{createWrapper:h}=await import('@parcel/watcher/wrapper.js'),u=module$1.createRequire(path.join(i,"package.json"))(e),c=h(u);return r.wrapper=c,c}async function R(r,e){try{return !!await utils.PKG.resolve(r,void 0,{extraPaths:[e]})}catch{return false}}async function T(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 w(){return process.platform==="darwin"?"fs-events":process.platform==="linux"?"inotify":process.platform==="win32"?"windows":"brute-force"}var m=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??[...S],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"?w():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"?w():this.backendOpt;o.info("FileWatcher start",{workspaceDir:this.workspaceDir,backend:e});let t;try{t=await C();}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: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(){f.clearCache();}async subscribeWithParcel(e,t){if(this.disposed)throw new Error("FileWatcher disposed before subscribe");let i=(a,u)=>{if(this.disposed)return;let c=this.workspaceDir.replace(/\\/g,"/").replace(/\/$/,""),l=u.replace(/\\/g,"/"),p=u;if(l.startsWith(c+"/")&&(p=l.slice(c.length+1)),this.ignoreInstance.ignores(p,a==="create"&&p.endsWith("/")))return;let g=a==="create"?"add":a==="delete"?"unlink":"change";for(let v of this.listeners)try{v(g,p);}catch(k){o.warn("listener threw",{error:k});}},h=await e.subscribe(this.workspaceDir,(a,u)=>{if(a){o.error("parcel subscribe callback error",{error:a});return}for(let c of u)i(c.type,c.path);},{ignore:[...this.ignorePatterns],backend:t});if(this.disposed){await h.unsubscribe().catch(()=>{});return}this.unsubscribe=async()=>{await h.unsubscribe().catch(a=>{o.warn("parcel unsubscribe error",{error:a});});};}};function b(r){return path.join(r,".watcher.pid")}function H(r){let e=b(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 M(r,e){let t=b(r);await fs.promises.writeFile(t,String(e),"utf-8");}async function N(r){let e=b(r);try{await fs.promises.unlink(e);}catch{}}exports.a=m;exports.b=b;exports.c=H;exports.d=M;exports.e=N;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a}from'./chunk-2YMB6W5S.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var F=class o extends Error{constructor(t,s,r){super(t);a(this,"name","ParserError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},p=class o extends Error{constructor(t,s,r){super(t);a(this,"name","DatabaseError");a(this,"operation");a(this,"cause");this.operation=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},M=class o extends Error{constructor(t,s,r){super(t);a(this,"name","FileSystemError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},
|
|
1
|
+
import {a}from'./chunk-2YMB6W5S.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var F=class o extends Error{constructor(t,s,r){super(t);a(this,"name","ParserError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},p=class o extends Error{constructor(t,s,r){super(t);a(this,"name","DatabaseError");a(this,"operation");a(this,"cause");this.operation=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},M=class o extends Error{constructor(t,s,r){super(t);a(this,"name","FileSystemError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},_=class o extends Error{constructor(t,s){super(t);a(this,"name","SchemaError");a(this,"missing");this.missing=s,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},A=class o extends Error{constructor(t,s){super(t);a(this,"name","ConfigError");a(this,"field");this.field=s,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},v=class o extends Error{constructor(t,s,r){super(t);a(this,"name","IndexError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},x=class o extends Error{constructor(t,s,r){super(t);a(this,"name","QueryError");a(this,"params");a(this,"cause");this.params=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",s=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${s}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},w=class o extends Error{constructor(t,s){super(`Unsupported language: ${t}`);a(this,"name","UnsupportedLanguageError");a(this,"extension");a(this,"filePath");this.extension=t,this.filePath=s,Object.setPrototypeOf(this,o.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var D=Log.create({service:"codebase-schema-migrations"}),S=1,V=[{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
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
name TEXT NOT NULL,
|
|
4
4
|
ast_type TEXT NOT NULL,
|
|
@@ -67,19 +67,19 @@ import {a}from'./chunk-2YMB6W5S.mjs';import {Log,Filesystem}from'@easbot/utils';
|
|
|
67
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 H(o,e=S,t={}){o.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
68
68
|
id INTEGER PRIMARY KEY,
|
|
69
69
|
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
70
|
-
)`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(
|
|
70
|
+
)`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(i=>i.id)),n={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(i=>i.id)),targetVersion:e};for(let i of V){if(i.id>e)break;if(r.has(i.id)){n.pending.push(i.id);continue}if(t.dryRun){n.applied.push(i.id);continue}try{o.execBatch([...i.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(i.id),r.add(i.id),n.applied.push(i.id),D.info("migration applied",{id:i.id,description:i.description});}catch(a){let c=a instanceof Error?a.message:String(a),u=i.up[0]??"";n.errors.push({migrationId:i.id,sql:u,error:c}),D.warn("migration step failed (may be idempotent)",{id:i.id,error:c,sqlCount:i.up.length});}}return n}function X(o){try{let e=o.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var l=Filesystem.toUnixPath,E=Log.create({service:"codebase-database"}),b=3,$=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){E.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:String(t)});}try{this.ensureSchema();let t=X(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{H(this.db,S);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,r]of e)t.run(s,r);}catch(e){E.error("ensureSchema failed",{message:e instanceof Error?e.message:String(e),cause:e instanceof Error?e.cause:void 0,stack:e instanceof Error?e.stack:void 0});let t=e instanceof Error?e.message:String(e),s=e instanceof Error?e.cause:void 0,r=s!==void 0?String(s):"",n=r&&r!==t?` (cause: ${r})`:"";throw new _(`Failed to create database schema: ${t}${n}`,e instanceof Error?[t,r].filter(Boolean):[t])}}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:l(e.file_path)};this.db.prepare(`
|
|
71
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
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(
|
|
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(n=>({...n,file_path:l(n.file_path)})),s=this.db.prepare(`
|
|
74
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
75
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
76
|
-
`);this.db.transaction(
|
|
76
|
+
`);this.db.transaction(n=>{for(let i of n)s.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.start_line,i.start_col,i.end_line,i.end_col,i.text,i.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(n);})(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 = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let n of e)try{let i=s.get(n.id);i&&t.run(i.rowid),r.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.text);}catch(i){E.warn("FTS update failed for node",{nodeId:n.id,error:String(i)});}}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){E.warn("FTS update failed for node",{nodeId:e.id,error:String(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 = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(i=>{for(let a of i)try{let c=s.get(a.id);c&&t.run(c.rowid),r.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.text);}catch(c){E.warn("FTS update failed for node",{nodeId:a.id,error:String(c)});}})(e);}insertEdge(e){this.db.prepare(`
|
|
77
77
|
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
78
78
|
VALUES (?, ?, ?, ?, ?)
|
|
79
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
80
|
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
81
81
|
VALUES (?, ?, ?, ?, ?)
|
|
82
|
-
`);this.db.transaction(r=>{for(let
|
|
82
|
+
`);this.db.transaction(r=>{for(let n of r)t.run(n.id,n.source,n.target,n.relation,n.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${l(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 r="SELECT * FROM nodes";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY file_path, start_line",e.limit&&(r+=" LIMIT ?",s.push(e.limit)),e.offset&&(r+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(r).all(...s)}catch(n){throw new p("Failed to query nodes","queryNodes",n instanceof Error?n:new Error(String(n)))}}findNodesByName(e){if(!e.name)return [];let t=e.limit??50,s=e.kind?`%${e.kind.toLowerCase()}%`:null,r=new Set,n=[],i=(c,u)=>{r.has(c.id)||(r.add(c.id),n.push({node:c,matchKind:u}));},a=(c,u)=>{e.file&&(e.file.includes("/")?(c.push("file_path = ?"),u.push(e.file)):(c.push("file_path LIKE '%/' || ?"),u.push(e.file))),s&&(c.push("LOWER(ast_type) LIKE ?"),u.push(s));};try{let c=["name = ?"],u=[e.name];a(c,u),u.push(t);let m=this.db.prepare(`SELECT * FROM nodes WHERE ${c.join(" AND ")} LIMIT ?`).all(...u);for(let g of m)i(g,"exact");if(m.length>0&&e.file)return n.slice(0,t);if(n.length<t){let g=this.db.prepare("SELECT * FROM nodes WHERE name LIKE ? LIMIT ?").all(`%${e.name}%`,t);for(let h of g)i(h,"qualified");}if(n.length>0&&e.file)return n.slice(0,t);if(n.length===0&&e.name){let g=["name LIKE ?"],h=[`%${e.name}%`];e.file&&(e.file.includes("/")?(g.push("file_path = ?"),h.push(e.file)):(g.push("file_path LIKE '%/' || ?"),h.push(e.file))),s&&(g.push("LOWER(ast_type) LIKE ?"),h.push(s)),g.push("?"),h.push(t);let T=this.db.prepare(`SELECT * FROM nodes WHERE ${g.join(" AND ")}`).all(...h);for(let f of T)i(f,"substring");}return n.slice(0,t)}catch(c){throw new p("Failed to find nodes by name","findNodesByName",c instanceof Error?c:new Error(String(c)))}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let n=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${n}) OR target IN (${n}))`),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 r="SELECT * FROM edges";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY created_at DESC",e.limit&&(r+=" LIMIT ?",s.push(e.limit)),e.offset&&(r+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(r).all(...s)}catch(n){throw new p("Failed to query edges","queryEdges",n instanceof Error?n:new Error(String(n)))}}queryAll(e,t){try{let s=this.db.prepare(e);return t?s.all(...t):s.all()}catch(s){throw new p("Failed to execute query","queryAll",s instanceof Error?s:new Error(String(s)))}}searchNodesFts(e,t=20){if(E.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return E.debug("searchNodesFts skip - FTS not available"),[];try{let s=e.split(/\s+/).map(a=>`${a}*`).join(" ");E.debug("searchNodesFts query",{ftsQuery:s});let i=this.db.prepare(`
|
|
83
83
|
SELECT
|
|
84
84
|
nodes_fts.id,
|
|
85
85
|
nodes_fts.name,
|
|
@@ -97,58 +97,62 @@ import {a}from'./chunk-2YMB6W5S.mjs';import {Log,Filesystem}from'@easbot/utils';
|
|
|
97
97
|
WHERE nodes_fts.text MATCH ?
|
|
98
98
|
ORDER BY score DESC
|
|
99
99
|
LIMIT ?
|
|
100
|
-
`).all(s,t);return
|
|
100
|
+
`).all(s,t);return E.debug("searchNodesFts done",{resultCount:i.length}),i}catch(s){return E.warn("searchNodesFts failed",{error:String(s)}),[]}}deleteNodesByFile(e){let t=l(e);if(this.ftsAvailable)try{let r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let n of r)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(n.rowid);}catch(r){E.warn("FTS delete failed for file",{filePath:t,error:String(r)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=l(e);return this.db.prepare(`
|
|
101
101
|
DELETE FROM edges
|
|
102
102
|
WHERE source IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
103
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(
|
|
104
|
+
`).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(l(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
|
|
105
105
|
INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
|
|
106
106
|
VALUES (?, ?, ?)
|
|
107
|
-
`).run(
|
|
107
|
+
`).run(l(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(l(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}checkIntegrity(){let e=R=>this.db.prepare(R).get().c,t=R=>e(R),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")},r=[],n=t(`
|
|
108
108
|
SELECT COUNT(*) as c FROM node_embeddings e
|
|
109
109
|
LEFT JOIN nodes n ON n.id = e.node_id WHERE n.id IS NULL
|
|
110
|
-
`);
|
|
111
|
-
SELECT COUNT(*) as c FROM edges e
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
`);
|
|
110
|
+
`);n>0&&r.push({severity:"error",message:`orphan node_embeddings: ${n}`});let i=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
|
+
`);i>0&&r.push({severity:"error",message:`orphan edges (source): ${i}`});let a=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
|
+
`);a>0&&r.push({severity:"error",message:`orphan edges (target): ${a}`});let c=t("SELECT COUNT(*) as c FROM edges WHERE source = target");c>0&&r.push({severity:"error",message:`self-loop edges: ${c} \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 m=t(`
|
|
115
119
|
SELECT COUNT(*) as c FROM file_hashes fh
|
|
116
120
|
WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.file_path = fh.file_path)
|
|
117
|
-
`);
|
|
121
|
+
`);m>0&&r.push({severity:"warn",message:`orphan file_hashes (no nodes): ${m} \u2014 run \`easbot codebase sync\` to cleanup`});let g=t(`
|
|
118
122
|
SELECT COUNT(DISTINCT n.file_path) as c FROM nodes n
|
|
119
123
|
WHERE NOT EXISTS (SELECT 1 FROM file_hashes fh WHERE fh.file_path = n.file_path)
|
|
120
|
-
`);
|
|
124
|
+
`);g>0&&r.push({severity:"warn",message:`node files without hash: ${g}`});let h=t("SELECT COUNT(*) as c FROM nodes WHERE name IS NULL OR name = ''");h>0&&r.push({severity:"error",message:`nodes with null/empty name: ${h}`});let T=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");T>0&&r.push({severity:"error",message:`nodes with null/empty ast_type: ${T}`});let f=t("SELECT COUNT(*) as c FROM nodes WHERE language IS NULL OR language = ''");f>0&&r.push({severity:"error",message:`nodes with null/empty language: ${f}`});let N=t("SELECT COUNT(*) as c FROM nodes WHERE file_path IS NULL OR file_path = ''");N>0&&r.push({severity:"error",message:`nodes with null/empty file_path: ${N}`});let O=this.db.prepare("SELECT id, COUNT(*) as c FROM nodes GROUP BY id HAVING c > 1").all().length;O>0&&r.push({severity:"error",message:`duplicate node ids: ${O}`});let I=t("SELECT COUNT(*) as c FROM nodes WHERE file_path LIKE '%\\\\%'");I>0&&r.push({severity:"warn",message:`nodes with backslash in file_path: ${I}`});let L=t(`
|
|
121
125
|
SELECT COUNT(*) as c FROM nodes
|
|
122
126
|
WHERE start_line IS NOT NULL AND end_line IS NOT NULL AND start_line > end_line
|
|
123
|
-
`);L>0&&r.push({severity:"error",message:`invalid line ranges: ${L}`});let y=this.db.prepare("SELECT id, COUNT(*) as c FROM edges GROUP BY id HAVING c > 1").all().length;y>0&&r.push({severity:"error",message:`duplicate edge ids: ${y}`});let C=t("SELECT COUNT(*) as c FROM nodes_fts_content");return C!==s.nodes&&r.push({severity:"error",message:`FTS content desync: ${C} vs ${s.nodes} (run \`easbot codebase recreate\` to rebuild)`}),s.parse_errors>100&&r.push({severity:"warn",message:`parse_errors > 100 (${s.parse_errors}) \u2014\u2014 many files failed to parse`}),{issues:r,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(),r=this.db.prepare("SELECT key, value FROM meta").all(),
|
|
127
|
+
`);L>0&&r.push({severity:"error",message:`invalid line ranges: ${L}`});let y=this.db.prepare("SELECT id, COUNT(*) as c FROM edges GROUP BY id HAVING c > 1").all().length;y>0&&r.push({severity:"error",message:`duplicate edge ids: ${y}`});let C=t("SELECT COUNT(*) as c FROM nodes_fts_content");return C!==s.nodes&&r.push({severity:"error",message:`FTS content desync: ${C} vs ${s.nodes} (run \`easbot codebase recreate\` to rebuild)`}),s.parse_errors>100&&r.push({severity:"warn",message:`parse_errors > 100 (${s.parse_errors}) \u2014\u2014 many files failed to parse`}),{issues:r,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(),r=this.db.prepare("SELECT key, value FROM meta").all(),n={};for(let i of r)n[i.key]=i.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:s?.c??0,dbPath:this.dbPath,meta:n,indexState:this.getIndexState(),extractionVersion:parseInt(this.getMeta("indexed_with_extraction_version")??"0",10),isStale:this.isIndexStale()}}setLastSync(){this.db.prepare(`
|
|
124
128
|
INSERT OR REPLACE INTO meta (key, value)
|
|
125
129
|
VALUES ('lastSync', ?)
|
|
126
|
-
`).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(
|
|
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(b)),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<b}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");E.warn("codebase db is stale",{recorded:e??"(none)",current:String(b),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(`
|
|
127
131
|
SELECT embedding FROM embedding_cache WHERE content_hash = ?
|
|
128
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(`
|
|
129
133
|
INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
|
|
130
134
|
VALUES (?, ?)
|
|
131
|
-
`).run(e,t);}deleteEmbeddingsByFile(e){let t=
|
|
135
|
+
`).run(e,t);}deleteEmbeddingsByFile(e){let t=l(e);return this.db.prepare(`
|
|
132
136
|
DELETE FROM node_embeddings WHERE node_id IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
133
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(`
|
|
134
138
|
INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
|
|
135
139
|
VALUES (?, ?, ?)
|
|
136
|
-
`);this.db.transaction(r=>{for(let
|
|
140
|
+
`);this.db.transaction(r=>{for(let n of r)try{t.run(n.nodeId,n.embeddingText,n.embedding);}catch(i){E.warn("Failed to store embedding for node",{nodeId:n.nodeId,error:String(i)});}})(e);}insertParseError(e){return this.db.prepare(`
|
|
137
141
|
INSERT INTO parse_errors (file_path, language, stage, message, line)
|
|
138
142
|
VALUES (?, ?, ?, ?, ?)
|
|
139
|
-
`).run(
|
|
143
|
+
`).run(l(e.filePath),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
|
|
140
144
|
INSERT INTO unresolved_refs
|
|
141
145
|
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
142
146
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
143
|
-
`).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,
|
|
147
|
+
`).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,l(e.filePath),e.language,e.candidates?JSON.stringify(e.candidates):null).changes}insertUnresolvedRefsBatch(e){if(e.length===0)return 0;let s=`
|
|
144
148
|
INSERT INTO unresolved_refs
|
|
145
149
|
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
146
150
|
VALUES ${e.map(()=>"(?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}
|
|
147
|
-
`,r=[];for(let a of e)r.push(a.fromNodeId??null,a.referenceName,a.referenceKind,a.line??null,a.col??null,
|
|
151
|
+
`,r=[];for(let a of e)r.push(a.fromNodeId??null,a.referenceName,a.referenceKind,a.line??null,a.col??null,l(a.filePath),a.language,a.candidates?JSON.stringify(a.candidates):null);return this.db.prepare(s).run(...r).changes}insertNameSegment(e,t){return this.db.prepare(`
|
|
148
152
|
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)
|
|
149
153
|
`).run(e,t).changes}insertNameSegmentsBatch(e){if(e.length===0)return 0;let s=`
|
|
150
154
|
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ${e.map(()=>"(?, ?)").join(", ")}
|
|
151
|
-
`,r=[];for(let a of e)r.push(a.segment,a.name);return this.db.prepare(s).run(...r).changes}setProjectMetadata(e,t){let s=e==="worktree"||e==="project"?
|
|
155
|
+
`,r=[];for(let a of e)r.push(a.segment,a.name);return this.db.prepare(s).run(...r).changes}setProjectMetadata(e,t){let s=e==="worktree"||e==="project"?l(t):t;return this.db.prepare(`
|
|
152
156
|
INSERT OR REPLACE INTO project_metadata (key, value, updated_at)
|
|
153
157
|
VALUES (?, ?, CURRENT_TIMESTAMP)
|
|
154
|
-
`).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(r=>r.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let r=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(
|
|
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(r=>r.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let r=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(i=>{for(let a of i)r.run(a);})(s),s.length}initialize(){if(this.closed)throw new p("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){E.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}countSqliteObjects(){if(!this.db)throw new Error("Database 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 Error("Database not initialized");this.db.prepare("DELETE FROM meta WHERE key = ?").run(e);}};function se(o){return o.isClosed()}function re(o){return o.getDbPath()}function ne(o,e){return o.transaction(e)}export{F as a,p as b,M as c,_ as d,A as e,v as f,x as g,w as h,S as i,V as j,H as k,X as l,b as m,$ as n,se as o,re as p,ne as q};
|